source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
DRACC_OMP_047_Counter_no_lock_simd_Intra_non_deteministic_yes.c | /*
Concurrent access on a counter with no lock with simd. Atomicity Violation. Data Race in line 28. Intra Region.
Forcing the execution to use more threads per team than the accelerator can handle per Warp, resulting in implicit Inter Region Data Races.
*/
#include <stdio.h>
#include <stdbool.h>
#define N 100000
#define C 64
int countervar[C];
int init(){
for(int i=0; i<C; i++){
countervar[i]=0;
}
return 0;
}
int count(){
#pragma omp target map(tofrom:countervar[0:C]) device(0)
#pragma omp teams num_teams(1) thread_limit(1048)
#pragma omp distribute parallel for
for (int i=0; i<N; i++){
#pragma omp simd
for(int i=0; i<C; i++){
countervar[i]++;
}
}
return 0;
}
int check(){
bool test = false;
for(int i=0; i<C; i++){
if(countervar[i]!=N){
test = true;
}
}
printf("Memory Access Issue visible: %s\n",test ? "true" : "false");
return 0;
}
int main(){
init();
count();
check();
return 0;
} |
if-clause.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main(int argc, char **argv)
{
int i, n=20, tid, x;
int a[n],suma=0,sumalocal;
if(argc < 3) {
fprintf(stderr,"Uso: \n %s <num-iteraciones> <num-hebras>\n", argv[0]);
exit(-1);
}
n = atoi(argv[1]); if (n>20) n=20;
for (i=0; i<n; i++) {
a[i] = i;
}
x = atoi(argv[2]); if (x < 1) x = 1;
#pragma omp parallel if(n>4) default(none) private(sumalocal,tid) \
shared(a,suma,n,x) num_threads(x)
{ sumalocal=0;
tid=omp_get_thread_num();
#pragma omp for private(i) schedule(static) nowait
for (i=0; i<n; i++)
{ sumalocal += a[i];
printf(" thread %d suma de a[%d]=%d sumalocal=%d \n",tid,i,a[i],sumalocal);
}
#pragma omp atomic
suma += sumalocal;
#pragma omp barrier
#pragma omp master
printf("thread master=%d imprime suma=%d\n",tid,suma);
}
}
|
trans2d.c | /*Daala video codec
Copyright (c) 2013 Daala project contributors. 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.
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.*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include "od_defs.h"
#include "od_filter.h"
#include "stats_tools.h"
#include "trans_tools.h"
#include "int_search.h"
#include "kiss99.h"
#define USE_FILES (0)
#define USE_AR95 (1)
#define USE_SUBSET1 (0)
#define USE_SUBSET3 (0)
#define PRINT_COV (0)
#define CG_SEARCH (0)
#define USE_SIMPLEX (1)
#define RAMP_DYADIC (0)
#if CG_SEARCH
# if USE_TYPE3 && RAMP_DYADIC
# error "Dyadic ramp constraint not supported for Type-III transform."
# endif
# if USE_SIMPLEX && RAMP_DYADIC
# error "Dyadic ramp constraint not supported with simplex search."
# endif
static void coding_gain_search(const double _r[2*B_SZ*2*B_SZ]){
# if !USE_SIMPLEX
# if B_SZ==4
{
int f[4];
int p0;
int q0;
int s0;
int s1;
double cg;
double best_cg;
best_cg=0;
# if RAMP_DYADIC
for(q0=(1<<FILTER_BITS);q0>=-(1<<FILTER_BITS);q0--){
int t0;
f[3]=q0;
/* S0 = 4/1*(1-q0/64)
* S0 >= 1 -> 64-q0 >= 16
*/
t0=(1<<FILTER_BITS)-q0;
s0=1*t0-0;
if(s0>=(1<<FILTER_BITS-2)){
s0*=4;
f[0]=s0;
for(p0=-(1<<FILTER_BITS);p0<=(1<<FILTER_BITS);p0++){
f[2]=p0;
/* S1 = 4/3*(1-(1-q0/64)*p0/64)
* S1 >= 1 -> 64^2-(64-q0)*p0 >= 64*48
* S1 = x/64 -> 64^2-(64-q0)*p0 = 0 MOD 48
*/
s1=(1<<2*FILTER_BITS)-t0*p0;
if(s1>=(1<<FILTER_BITS)*(3<<FILTER_BITS-2)&&s1%(3<<FILTER_BITS-2)==0){
s1/=(3<<FILTER_BITS-2);
f[1]=s1;
cg=coding_gain_2d_collapsed(_r,f);
if(cg>best_cg){
best_cg=cg;
printf("%i %i %i %i %G\n",p0,q0,s0,s1,cg);
}
}
}
}
}
# else
for(p0=-(1<<FILTER_BITS);p0<=(1<<FILTER_BITS);p0++){
f[2]=p0;
for(q0=(1<<FILTER_BITS);q0>=-(1<<FILTER_BITS);q0--){
f[3]=q0;
for(s0=(1<<FILTER_BITS);s0<=2*(1<<FILTER_BITS);s0++){
f[0]=s0;
for(s1=(1<<FILTER_BITS);s1<=2*(1<<FILTER_BITS);s1++){
f[1]=s1;
cg=coding_gain_2d_collapsed(_r,f);
if(cg>best_cg){
best_cg=cg;
printf("%i %i %i %i %G\n",p0,q0,s0,s1,cg);
}
}
}
}
}
# endif
}
# elif B_SZ==8
{
int f[10];
int p0;
int p1;
int p2;
int q0;
int q1;
int q2;
int s0;
int s1;
int s2;
int s3;
double cg;
double best_cg;
best_cg=0;
# if RAMP_DYADIC
for(q0=(1<<FILTER_BITS);q0>=-(1<<FILTER_BITS);q0--){
int t0;
f[7]=q0;
/* S0 = 8/1*(1-q0/64)
* S0 >= 1 -> 64-q0 >= 8
*/
t0=(1<<FILTER_BITS)-q0;
s0=1*t0-0;
if(s0>=(1<<FILTER_BITS-3)){
s0*=8;
f[0]=s0;
for(p0=-(1<<FILTER_BITS);p0<=(1<<FILTER_BITS);p0++){
f[4]=p0;
for(q1=(1<<FILTER_BITS);q1>=-(1<<FILTER_BITS);q1--){
int t1;
f[8]=q1;
/* S1 = 8/3*((1-q1/64)-(1-q0/64)*p0/64)
* S1 >= 1 -> 64*t1-t0*p0 >= 64*24
* S1 = x/64 -> 64*t1-t0*p0 = 0 MOD 24
*/
t1=(1<<FILTER_BITS)-q1;
s1=(1<<FILTER_BITS)*t1-t0*p0;
if(s1>=(1<<FILTER_BITS)*(3<<FILTER_BITS-3)&&
s1%(3<<FILTER_BITS-3)==0){
s1/=(3<<FILTER_BITS-3);
f[1]=s1;
for(p1=-(1<<FILTER_BITS);p1<=(1<<FILTER_BITS);p1++){
f[5]=p1;
for(q2=(1<<FILTER_BITS);q2>=-(1<<FILTER_BITS);q2--){
int t2;
f[9]=q2;
/* S2 = 8/5*((1-q2/64)-(1-q1/64)*p1/64)
* S2 >= 1 -> 64*t2-t1*p1) >= 64*40
* S2 = x/64 -> 64*t2-t1*p1 = 0 MOD 40
*/
t2=(1<<FILTER_BITS)-q2;
s2=(1<<FILTER_BITS)*t2-t1*p1;
if(s2>=(1<<FILTER_BITS)*(5<<FILTER_BITS-3)&&
s2%(5<<FILTER_BITS-3)==0){
s2/=(5<<FILTER_BITS-3);
f[2]=s2;
for(p2=-(1<<FILTER_BITS);p2<=(1<<FILTER_BITS);p2++){
f[6]=p2;
/* S3 = 8/7*(1-(1-q2/64)*p2/64)
* S3 >= 1 -> 64^2-t2*p2 >= 64*56
* S3 = x/64 -> 64^2-t2*p2 = 0 MOD 56
*/
s3=(1<<2*FILTER_BITS)-t2*p2;
if(s3>=(1<<FILTER_BITS)*(7<<FILTER_BITS-3)&&
s3%(7<<FILTER_BITS-3)==0){
s3/=(7<<FILTER_BITS-3);
f[3]=s3;
cg=coding_gain_2d_collapsed(_r,f);
if(cg>best_cg){
best_cg=cg;
printf("%i %i %i %i %i %i %i %i %i %i %-24.18G\n",
p0,p1,p2,q0,q1,q2,s0,s1,s2,s3,cg);
}
}
}
}
}
}
}
}
}
}
}
# else
# error "Exhaustive search for B_SZ==8 only supported using RAMP_DYADIC (1)."
# endif
}
# else
# error "Exhaustive search not supported for this block size."
# endif
# else
{
int dims;
int i;
kiss99_ctx ks[NUM_PROCS];
int lb[22];
int ub[22];
# if B_SZ==4
dims=4;
# elif B_SZ==8
dims=10;
# elif B_SZ==16
dims=22;
# else
# error "Unsupported block size."
# endif
for(i=0;i<dims;i++){
lb[i]=i<(B_SZ>>1)?(1<<FILTER_BITS):-(1<<FILTER_BITS);
ub[i]=i<(B_SZ>>1)?2*(1<<FILTER_BITS):(1<<FILTER_BITS);
}
for(i=0;i<NUM_PROCS;i++){
uint32_t srand;
srand=i*16843009; /*Broadcast char to 4xchar*/
kiss99_srand(&ks[i],(unsigned char *)&srand,sizeof(srand));
}
#pragma omp parallel for schedule(dynamic)
for(i=0;i<128;i++){
int tid;
int j;
# if B_SZ==4
int f[4];
# elif B_SZ==8
int f[10];
# elif B_SZ==16
int f[22];
# else
# error "Unsupported block size."
# endif
double cg;
tid=OD_OMP_GET_THREAD;
for(j=0;j<dims;j++){
int range;
int mask;
int rng;
range=ub[j]-lb[j];
mask=(1<<OD_ILOG_NZ(range))-1;
do {
rng=((int)kiss99_rand(&ks[tid]))&mask;
}
while(rng>range);
f[j]=lb[j]+rng;
}
j=int_simplex_max(&cg,dims,coding_gain_2d_collapsed,_r,lb,ub,f);
fprintf(stdout,"obj=%-24.18G steps=%4d params={",cg,j);
for(j=0;j<dims;j++){
fprintf(stdout,"%3d%c",f[j],j==dims-1?'}':',');
}
fprintf(stdout,"\n");
}
}
# endif
}
#endif
#if USE_FILES
static int t_start(void *_ctx,const char *_name,const th_info *_ti,int _pli,
int _nxblocks,int _nyblocks){
trans_ctx *ctx;
fprintf(stdout,"%s %i %i\n",_name,_nxblocks,_nyblocks);
fflush(stdout);
ctx=(trans_ctx *)_ctx;
image_ctx_init(&ctx->img,_name,_nxblocks,_nyblocks);
return EXIT_SUCCESS;
}
static void t_load_data(void *_ctx,const unsigned char *_data,int _stride,
int _bi,int _bj){
trans_ctx *ctx;
ctx=(trans_ctx *)_ctx;
if(_bi==0&&_bj==0){
int y;
int x;
int j;
int i;
unsigned char buf[2*B_SZ*2*B_SZ];
for(y=0;y<ctx->img.nyblocks*B_SZ-(2*B_SZ-1);y++){
for(x=0;x<ctx->img.nxblocks*B_SZ-(2*B_SZ-1);x++){
for(j=0;j<2*B_SZ;j++){
for(i=0;i<2*B_SZ;i++){
buf[j*2*B_SZ+i]=_data[(y+j)*_stride+(x+i)];
}
}
trans_data_add(&ctx->td,buf);
}
}
}
}
#define PADDING (0)
const block_func BLOCKS[]={
t_load_data
};
const int NBLOCKS=sizeof(BLOCKS)/sizeof(*BLOCKS);
#endif
int main(int _argc,const char *_argv[]){
trans_ctx ctx[NUM_PROCS];
const int *f;
int i;
double r[2*B_SZ*2*B_SZ];
const double *cov;
(void)_argc;
(void)_argv;
#if B_SZ==4
f=OD_FILTER_PARAMS4;
#elif B_SZ==8
f=OD_FILTER_PARAMS8;
#elif B_SZ==16
f=OD_FILTER_PARAMS16;
#else
# error "Need filter params for this block size."
#endif
for(i=0;i<NUM_PROCS;i++){
trans_data_init(&ctx[i].td,2*B_SZ*2*B_SZ);
}
cov=r;
#if USE_FILES
OD_OMP_SET_THREADS(NUM_PROCS);
ne_apply_to_blocks(ctx,sizeof(*ctx),0x1,PADDING,t_start,NBLOCKS,BLOCKS,NULL,
_argc,_argv);
for(i=1;i<NUM_PROCS;i++){
trans_data_combine(&ctx[0].td,&ctx[i].td);
}
trans_data_normalize(&ctx[0].td);
# if PRINT_COV
trans_data_print(&ctx[0].td,stderr);
# endif
fprintf(stdout,"original cg=%- 24.16G\n",coding_gain_2d(ctx[0].td.cov,f));
trans_data_collapse(&ctx[0].td,2*B_SZ,r);
fprintf(stdout,"collapse cg=%- 24.16G\n",coding_gain_2d_collapsed(r,f));
trans_data_expand(&ctx[0].td,2*B_SZ,r);
fprintf(stdout,"expanded cg=%- 24.16G\n",coding_gain_2d(ctx[0].td.cov,f));
#elif USE_AR95
auto_regressive_collapsed(r,2*B_SZ*2*B_SZ,2*B_SZ,0.95);
#elif USE_SUBSET1
# if B_SZ_LOG>=OD_LOG_BSIZE0&&B_SZ_LOG<OD_LOG_BSIZE0+OD_NBSIZES
cov=SUBSET1_2D[B_SZ_LOG-OD_LOG_BSIZE0];
# else
# error "Need auto-correlation matrix for subset1 for this block size."
# endif
#elif USE_SUBSET3
# if B_SZ_LOG>=OD_LOG_BSIZE0&&B_SZ_LOG<OD_LOG_BSIZE0+OD_NBSIZES
cov=SUBSET3_2D[B_SZ_LOG-OD_LOG_BSIZE0];
# else
# error "Need auto-correlation matrix for subset3 for this block size."
# endif
#endif
#if CG_SEARCH
coding_gain_search(cov);
#else
fprintf(stdout,"cg=%-24.18G\n",coding_gain_2d_collapsed(cov,f));
#endif
for(i=0;i<NUM_PROCS;i++){
trans_data_clear(&ctx[i].td);
}
return EXIT_SUCCESS;
}
|
image.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% IIIII M M AAA GGGG EEEEE %
% I MM MM A A G E %
% I M M M AAAAA G GG EEE %
% I M M A A G G E %
% IIIII M M A A GGGG EEEEE %
% %
% %
% MagickCore Image Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/animate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/client.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/compress.h"
#include "MagickCore/constitute.h"
#include "MagickCore/delegate.h"
#include "MagickCore/display.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/magick-private.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantize.h"
#include "MagickCore/random_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/timer.h"
#include "MagickCore/timer-private.h"
#include "MagickCore/token.h"
#include "MagickCore/token-private.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/version.h"
#include "MagickCore/xwindow-private.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImage() returns a pointer to an image structure initialized to
% default values.
%
% The format of the AcquireImage method is:
%
% Image *AcquireImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: Many of the image default values are set from this
% structure. For example, filename, compression, depth, background color,
% and others.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AcquireImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
const char
*option;
Image
*image;
MagickStatusType
flags;
/*
Allocate image structure.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
image=(Image *) AcquireCriticalMemory(sizeof(*image));
(void) memset(image,0,sizeof(*image));
/*
Initialize Image structure.
*/
(void) CopyMagickString(image->magick,"MIFF",MagickPathExtent);
image->storage_class=DirectClass;
image->depth=MAGICKCORE_QUANTUM_DEPTH;
image->colorspace=sRGBColorspace;
image->rendering_intent=PerceptualIntent;
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.red_primary.z=0.0300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.green_primary.z=0.1000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.blue_primary.z=0.7900f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
image->chromaticity.white_point.z=0.3583f;
image->interlace=NoInterlace;
image->ticks_per_second=UndefinedTicksPerSecond;
image->compose=OverCompositeOp;
(void) QueryColorCompliance(MatteColor,AllCompliance,&image->matte_color,
exception);
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,&image->border_color,
exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image->transparent_color,exception);
GetTimerInfo(&image->timer);
image->cache=AcquirePixelCache(0);
image->channel_mask=DefaultChannels;
image->channel_map=AcquirePixelChannelMap();
image->blob=CloneBlobInfo((BlobInfo *) NULL);
image->timestamp=GetMagickTime();
image->debug=IsEventLogging();
image->reference_count=1;
image->semaphore=AcquireSemaphoreInfo();
image->signature=MagickCoreSignature;
if (image_info == (ImageInfo *) NULL)
return(image);
/*
Transfer image info.
*/
SetBlobExempt(image,image_info->file != (FILE *) NULL ? MagickTrue :
MagickFalse);
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,image_info->magick,MagickPathExtent);
if (image_info->size != (char *) NULL)
{
(void) ParseAbsoluteGeometry(image_info->size,&image->extract_info);
image->columns=image->extract_info.width;
image->rows=image->extract_info.height;
image->offset=image->extract_info.x;
image->extract_info.x=0;
image->extract_info.y=0;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
(void) memset(&geometry,0,sizeof(geometry));
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
if (((flags & XValue) != 0) || ((flags & YValue) != 0))
{
image->extract_info=geometry;
Swap(image->columns,image->extract_info.width);
Swap(image->rows,image->extract_info.height);
}
}
image->compression=image_info->compression;
image->quality=image_info->quality;
image->endian=image_info->endian;
image->interlace=image_info->interlace;
image->units=image_info->units;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(image_info->density,&geometry_info);
if ((flags & RhoValue) != 0)
image->resolution.x=geometry_info.rho;
image->resolution.y=image->resolution.x;
if ((flags & SigmaValue) != 0)
image->resolution.y=geometry_info.sigma;
}
if (image_info->page != (char *) NULL)
{
char
*geometry;
image->page=image->extract_info;
geometry=GetPageGeometry(image_info->page);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
if (image_info->depth != 0)
image->depth=image_info->depth;
image->dither=image_info->dither;
image->matte_color=image_info->matte_color;
image->background_color=image_info->background_color;
image->border_color=image_info->border_color;
image->transparent_color=image_info->transparent_color;
image->ping=image_info->ping;
image->progress_monitor=image_info->progress_monitor;
image->client_data=image_info->client_data;
if (image_info->cache != (void *) NULL)
ClonePixelCacheMethods(image->cache,image_info->cache);
/*
Set all global options that map to per-image settings.
*/
(void) SyncImageSettings(image_info,image,exception);
/*
Global options that are only set for new images.
*/
option=GetImageOption(image_info,"delay");
if (option != (const char *) NULL)
{
GeometryInfo
geometry_info;
flags=ParseGeometry(option,&geometry_info);
if ((flags & GreaterValue) != 0)
{
if ((double) image->delay > floor(geometry_info.rho+0.5))
image->delay=(size_t) CastDoubleToLong(floor(
geometry_info.rho+0.5));
}
else
if ((flags & LessValue) != 0)
{
if ((double) image->delay < floor(geometry_info.rho+0.5))
image->ticks_per_second=CastDoubleToLong(floor(
geometry_info.sigma+0.5));
}
else
image->delay=(size_t) CastDoubleToLong(floor(
geometry_info.rho+0.5));
if ((flags & SigmaValue) != 0)
image->ticks_per_second=CastDoubleToLong(floor(
geometry_info.sigma+0.5));
}
option=GetImageOption(image_info,"dispose");
if (option != (const char *) NULL)
image->dispose=(DisposeType) ParseCommandOption(MagickDisposeOptions,
MagickFalse,option);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireImageInfo() allocates the ImageInfo structure.
%
% The format of the AcquireImageInfo method is:
%
% ImageInfo *AcquireImageInfo(void)
%
*/
MagickExport ImageInfo *AcquireImageInfo(void)
{
ImageInfo
*image_info;
image_info=(ImageInfo *) AcquireCriticalMemory(sizeof(*image_info));
GetImageInfo(image_info);
return(image_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e N e x t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireNextImage() initializes the next image in a sequence to
% default values. The next member of image points to the newly allocated
% image. If there is a memory shortage, next is assigned NULL.
%
% The format of the AcquireNextImage method is:
%
% void AcquireNextImage(const ImageInfo *image_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: Many of the image default values are set from this
% structure. For example, filename, compression, depth, background color,
% and others.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport void AcquireNextImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
/*
Allocate image structure.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
image->next=AcquireImage(image_info,exception);
if (GetNextImageInList(image) == (Image *) NULL)
return;
(void) CopyMagickString(GetNextImageInList(image)->filename,image->filename,
MagickPathExtent);
if (image_info != (ImageInfo *) NULL)
(void) CopyMagickString(GetNextImageInList(image)->filename,
image_info->filename,MagickPathExtent);
DestroyBlob(GetNextImageInList(image));
image->next->blob=ReferenceBlob(image->blob);
image->next->endian=image->endian;
image->next->scene=image->scene+1;
image->next->previous=image;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A p p e n d I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AppendImages() takes all images from the current image pointer to the end
% of the image list and appends them to each other top-to-bottom if the
% stack parameter is true, otherwise left-to-right.
%
% The current gravity setting effects how the image is justified in the
% final image.
%
% The format of the AppendImages method is:
%
% Image *AppendImages(const Image *images,const MagickBooleanType stack,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o stack: A value other than 0 stacks the images top-to-bottom.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AppendImages(const Image *images,
const MagickBooleanType stack,ExceptionInfo *exception)
{
#define AppendImageTag "Append/Image"
CacheView
*append_view;
Image
*append_image;
ImageType
image_type;
MagickBooleanType
homogeneous_colorspace,
status;
MagickOffsetType
n;
PixelTrait
alpha_trait;
RectangleInfo
geometry;
const Image
*next;
size_t
depth,
height,
number_images,
width;
ssize_t
x_offset,
y,
y_offset;
/*
Compute maximum area of appended area.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
alpha_trait=images->alpha_trait;
number_images=1;
width=images->columns;
height=images->rows;
depth=images->depth;
image_type=images->type;
homogeneous_colorspace=MagickTrue;
next=GetNextImageInList(images);
for ( ; next != (Image *) NULL; next=GetNextImageInList(next))
{
if (next->depth > depth)
depth=next->depth;
if (next->type != images->type)
image_type=UndefinedType;
if (next->colorspace != images->colorspace)
homogeneous_colorspace=MagickFalse;
if (next->alpha_trait != UndefinedPixelTrait)
alpha_trait=BlendPixelTrait;
number_images++;
if (stack != MagickFalse)
{
if (next->columns > width)
width=next->columns;
height+=next->rows;
continue;
}
width+=next->columns;
if (next->rows > height)
height=next->rows;
}
/*
Append images.
*/
append_image=CloneImage(images,width,height,MagickTrue,exception);
if (append_image == (Image *) NULL)
return((Image *) NULL);
if (image_type != BilevelType)
{
if (SetImageStorageClass(append_image,DirectClass,exception) == MagickFalse)
{
append_image=DestroyImage(append_image);
return((Image *) NULL);
}
if (homogeneous_colorspace == MagickFalse)
(void) SetImageColorspace(append_image,sRGBColorspace,exception);
}
append_image->depth=depth;
append_image->alpha_trait=alpha_trait;
append_image->page=images->page;
(void) SetImageBackgroundColor(append_image,exception);
status=MagickTrue;
x_offset=0;
y_offset=0;
next=images;
append_view=AcquireAuthenticCacheView(append_image,exception);
for (n=0; n < (MagickOffsetType) number_images; n++)
{
CacheView
*image_view;
MagickBooleanType
proceed;
SetGeometry(append_image,&geometry);
GravityAdjustGeometry(next->columns,next->rows,next->gravity,&geometry);
if (stack != MagickFalse)
x_offset-=geometry.x;
else
y_offset-=geometry.y;
image_view=AcquireVirtualCacheView(next,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(next,next,next->rows,1)
#endif
for (y=0; y < (ssize_t) next->rows; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,next->columns,1,exception);
q=QueueCacheViewAuthenticPixels(append_view,x_offset,y+y_offset,
next->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
GetPixelInfo(next,&pixel);
for (x=0; x < (ssize_t) next->columns; x++)
{
GetPixelInfoPixel(next,p,&pixel);
SetPixelViaPixelInfo(append_image,&pixel,q);
p+=GetPixelChannels(next);
q+=GetPixelChannels(append_image);
}
sync=SyncCacheViewAuthenticPixels(append_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (stack == MagickFalse)
{
x_offset+=(ssize_t) next->columns;
y_offset=0;
}
else
{
x_offset=0;
y_offset+=(ssize_t) next->rows;
}
proceed=SetImageProgress(append_image,AppendImageTag,n,number_images);
if (proceed == MagickFalse)
break;
next=GetNextImageInList(next);
}
append_view=DestroyCacheView(append_view);
if (status == MagickFalse)
append_image=DestroyImage(append_image);
return(append_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C a t c h I m a g e E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CatchImageException() returns if no exceptions are found in the image
% sequence, otherwise it determines the most severe exception and reports
% it as a warning or error depending on the severity.
%
% The format of the CatchImageException method is:
%
% ExceptionType CatchImageException(Image *image)
%
% A description of each parameter follows:
%
% o image: An image sequence.
%
*/
MagickExport ExceptionType CatchImageException(Image *image)
{
ExceptionInfo
*exception;
ExceptionType
severity;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
exception=AcquireExceptionInfo();
CatchException(exception);
severity=exception->severity;
exception=DestroyExceptionInfo(exception);
return(severity);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l i p I m a g e P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClipImagePath() sets the image clip mask based any clipping path information
% if it exists.
%
% The format of the ClipImagePath method is:
%
% MagickBooleanType ClipImagePath(Image *image,const char *pathname,
% const MagickBooleanType inside,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o pathname: name of clipping path resource. If name is preceded by #, use
% clipping path numbered by name.
%
% o inside: if non-zero, later operations take effect inside clipping path.
% Otherwise later operations take effect outside clipping path.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClipImage(Image *image,ExceptionInfo *exception)
{
return(ClipImagePath(image,"#1",MagickTrue,exception));
}
MagickExport MagickBooleanType ClipImagePath(Image *image,const char *pathname,
const MagickBooleanType inside,ExceptionInfo *exception)
{
#define ClipImagePathTag "ClipPath/Image"
char
*property;
const char
*value;
Image
*clip_mask;
ImageInfo
*image_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pathname != NULL);
property=AcquireString(pathname);
(void) FormatLocaleString(property,MagickPathExtent,"8BIM:1999,2998:%s",
pathname);
value=GetImageProperty(image,property,exception);
property=DestroyString(property);
if (value == (const char *) NULL)
{
ThrowFileException(exception,OptionError,"NoClipPathDefined",
image->filename);
return(MagickFalse);
}
image_info=AcquireImageInfo();
(void) CopyMagickString(image_info->filename,image->filename,
MagickPathExtent);
(void) ConcatenateMagickString(image_info->filename,pathname,
MagickPathExtent);
clip_mask=BlobToImage(image_info,value,strlen(value),exception);
image_info=DestroyImageInfo(image_info);
if (clip_mask == (Image *) NULL)
return(MagickFalse);
if (clip_mask->storage_class == PseudoClass)
{
(void) SyncImage(clip_mask,exception);
if (SetImageStorageClass(clip_mask,DirectClass,exception) == MagickFalse)
return(MagickFalse);
}
if (inside != MagickFalse)
(void) NegateImage(clip_mask,MagickFalse,exception);
(void) FormatLocaleString(clip_mask->magick_filename,MagickPathExtent,
"8BIM:1999,2998:%s\nPS",pathname);
(void) SetImageMask(image,WritePixelMask,clip_mask,exception);
image->mask_trait=UpdatePixelTrait;
clip_mask=DestroyImage(clip_mask);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImage() copies an image and returns the copy as a new image object.
%
% If the specified columns and rows is 0, an exact copy of the image is
% returned, otherwise the pixel data is undefined and must be initialized
% with the QueueAuthenticPixels() and SyncAuthenticPixels() methods. On
% failure, a NULL image is returned and exception describes the reason for the
% failure.
%
% The format of the CloneImage method is:
%
% Image *CloneImage(const Image *image,const size_t columns,
% const size_t rows,const MagickBooleanType orphan,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the cloned image.
%
% o rows: the number of rows in the cloned image.
%
% o detach: With a value other than 0, the cloned image is detached from
% its parent I/O stream.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CloneImage(const Image *image,const size_t columns,
const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception)
{
Image
*clone_image;
double
scale;
size_t
length;
/*
Clone the image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((image->columns == 0) || (image->rows == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"NegativeOrZeroImageSize","`%s'",image->filename);
return((Image *) NULL);
}
clone_image=(Image *) AcquireCriticalMemory(sizeof(*clone_image));
(void) memset(clone_image,0,sizeof(*clone_image));
clone_image->signature=MagickCoreSignature;
clone_image->storage_class=image->storage_class;
clone_image->number_channels=image->number_channels;
clone_image->number_meta_channels=image->number_meta_channels;
clone_image->metacontent_extent=image->metacontent_extent;
clone_image->colorspace=image->colorspace;
clone_image->alpha_trait=image->alpha_trait;
clone_image->channels=image->channels;
clone_image->mask_trait=image->mask_trait;
clone_image->columns=image->columns;
clone_image->rows=image->rows;
clone_image->dither=image->dither;
clone_image->image_info=CloneImageInfo(image->image_info);
(void) CloneImageProfiles(clone_image,image);
(void) CloneImageProperties(clone_image,image);
(void) CloneImageArtifacts(clone_image,image);
GetTimerInfo(&clone_image->timer);
if (image->ascii85 != (void *) NULL)
Ascii85Initialize(clone_image);
clone_image->extent=image->extent;
clone_image->magick_columns=image->magick_columns;
clone_image->magick_rows=image->magick_rows;
clone_image->type=image->type;
clone_image->channel_mask=image->channel_mask;
clone_image->channel_map=ClonePixelChannelMap(image->channel_map);
(void) CopyMagickString(clone_image->magick_filename,image->magick_filename,
MagickPathExtent);
(void) CopyMagickString(clone_image->magick,image->magick,MagickPathExtent);
(void) CopyMagickString(clone_image->filename,image->filename,
MagickPathExtent);
clone_image->progress_monitor=image->progress_monitor;
clone_image->client_data=image->client_data;
clone_image->reference_count=1;
clone_image->next=image->next;
clone_image->previous=image->previous;
clone_image->list=NewImageList();
if (detach == MagickFalse)
clone_image->blob=ReferenceBlob(image->blob);
else
{
clone_image->next=NewImageList();
clone_image->previous=NewImageList();
clone_image->blob=CloneBlobInfo((BlobInfo *) NULL);
}
clone_image->ping=image->ping;
clone_image->debug=IsEventLogging();
clone_image->semaphore=AcquireSemaphoreInfo();
if (image->colormap != (PixelInfo *) NULL)
{
/*
Allocate and copy the image colormap.
*/
clone_image->colors=image->colors;
length=(size_t) image->colors;
clone_image->colormap=(PixelInfo *) AcquireQuantumMemory(length+1,
sizeof(*clone_image->colormap));
if (clone_image->colormap == (PixelInfo *) NULL)
{
clone_image=DestroyImage(clone_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memcpy(clone_image->colormap,image->colormap,length*
sizeof(*clone_image->colormap));
}
if ((columns == 0) || (rows == 0))
{
if (image->montage != (char *) NULL)
(void) CloneString(&clone_image->montage,image->montage);
if (image->directory != (char *) NULL)
(void) CloneString(&clone_image->directory,image->directory);
clone_image->cache=ReferencePixelCache(image->cache);
return(clone_image);
}
scale=1.0;
if (image->columns != 0)
scale=(double) columns/(double) image->columns;
clone_image->page.width=(size_t) CastDoubleToLong(floor(scale*
image->page.width+0.5));
clone_image->page.x=CastDoubleToLong(ceil(scale*image->page.x-0.5));
clone_image->tile_offset.x=CastDoubleToLong(ceil(scale*
image->tile_offset.x-0.5));
scale=1.0;
if (image->rows != 0)
scale=(double) rows/(double) image->rows;
clone_image->page.height=(size_t) CastDoubleToLong(floor(scale*
image->page.height+0.5));
clone_image->page.y=CastDoubleToLong(ceil(scale*image->page.y-0.5));
clone_image->tile_offset.y=CastDoubleToLong(ceil(scale*
image->tile_offset.y-0.5));
clone_image->cache=ClonePixelCache(image->cache);
if (SetImageExtent(clone_image,columns,rows,exception) == MagickFalse)
clone_image=DestroyImage(clone_image);
return(clone_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneImageInfo() makes a copy of the given image info structure. If
% NULL is specified, a new image info structure is created initialized to
% default values.
%
% The format of the CloneImageInfo method is:
%
% ImageInfo *CloneImageInfo(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport ImageInfo *CloneImageInfo(const ImageInfo *image_info)
{
ImageInfo
*clone_info;
clone_info=AcquireImageInfo();
if (image_info == (ImageInfo *) NULL)
return(clone_info);
clone_info->compression=image_info->compression;
clone_info->temporary=image_info->temporary;
clone_info->adjoin=image_info->adjoin;
clone_info->antialias=image_info->antialias;
clone_info->scene=image_info->scene;
clone_info->number_scenes=image_info->number_scenes;
clone_info->depth=image_info->depth;
if (image_info->size != (char *) NULL)
(void) CloneString(&clone_info->size,image_info->size);
if (image_info->extract != (char *) NULL)
(void) CloneString(&clone_info->extract,image_info->extract);
if (image_info->scenes != (char *) NULL)
(void) CloneString(&clone_info->scenes,image_info->scenes);
if (image_info->page != (char *) NULL)
(void) CloneString(&clone_info->page,image_info->page);
clone_info->interlace=image_info->interlace;
clone_info->endian=image_info->endian;
clone_info->units=image_info->units;
clone_info->quality=image_info->quality;
if (image_info->sampling_factor != (char *) NULL)
(void) CloneString(&clone_info->sampling_factor,
image_info->sampling_factor);
if (image_info->server_name != (char *) NULL)
(void) CloneString(&clone_info->server_name,image_info->server_name);
if (image_info->font != (char *) NULL)
(void) CloneString(&clone_info->font,image_info->font);
if (image_info->texture != (char *) NULL)
(void) CloneString(&clone_info->texture,image_info->texture);
if (image_info->density != (char *) NULL)
(void) CloneString(&clone_info->density,image_info->density);
clone_info->pointsize=image_info->pointsize;
clone_info->fuzz=image_info->fuzz;
clone_info->matte_color=image_info->matte_color;
clone_info->background_color=image_info->background_color;
clone_info->border_color=image_info->border_color;
clone_info->transparent_color=image_info->transparent_color;
clone_info->dither=image_info->dither;
clone_info->monochrome=image_info->monochrome;
clone_info->colorspace=image_info->colorspace;
clone_info->type=image_info->type;
clone_info->orientation=image_info->orientation;
clone_info->ping=image_info->ping;
clone_info->verbose=image_info->verbose;
clone_info->progress_monitor=image_info->progress_monitor;
clone_info->client_data=image_info->client_data;
clone_info->cache=image_info->cache;
if (image_info->cache != (void *) NULL)
clone_info->cache=ReferencePixelCache(image_info->cache);
if (image_info->profile != (void *) NULL)
clone_info->profile=(void *) CloneStringInfo((StringInfo *)
image_info->profile);
SetImageInfoFile(clone_info,image_info->file);
SetImageInfoBlob(clone_info,image_info->blob,image_info->length);
clone_info->stream=image_info->stream;
clone_info->custom_stream=image_info->custom_stream;
(void) CopyMagickString(clone_info->magick,image_info->magick,
MagickPathExtent);
(void) CopyMagickString(clone_info->unique,image_info->unique,
MagickPathExtent);
(void) CopyMagickString(clone_info->filename,image_info->filename,
MagickPathExtent);
clone_info->channel=image_info->channel;
(void) CloneImageOptions(clone_info,image_info);
clone_info->debug=IsEventLogging();
clone_info->signature=image_info->signature;
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o p y I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CopyImagePixels() copies pixels from the source image as defined by the
% geometry the destination image at the specified offset.
%
% The format of the CopyImagePixels method is:
%
% MagickBooleanType CopyImagePixels(Image *image,const Image *source_image,
% const RectangleInfo *geometry,const OffsetInfo *offset,
% ExceptionInfo *exception);
%
% A description of each parameter follows:
%
% o image: the destination image.
%
% o source_image: the source image.
%
% o geometry: define the dimensions of the source pixel rectangle.
%
% o offset: define the offset in the destination image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType CopyImagePixels(Image *image,
const Image *source_image,const RectangleInfo *geometry,
const OffsetInfo *offset,ExceptionInfo *exception)
{
#define CopyImageTag "Copy/Image"
CacheView
*image_view,
*source_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(source_image != (Image *) NULL);
assert(geometry != (RectangleInfo *) NULL);
assert(offset != (OffsetInfo *) NULL);
if ((offset->x < 0) || (offset->y < 0) ||
((ssize_t) (offset->x+geometry->width) > (ssize_t) image->columns) ||
((ssize_t) (offset->y+geometry->height) > (ssize_t) image->rows))
ThrowBinaryException(OptionError,"GeometryDoesNotContainImage",
image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
/*
Copy image pixels.
*/
status=MagickTrue;
progress=0;
source_view=AcquireVirtualCacheView(source_image,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,source_image,geometry->height,1)
#endif
for (y=0; y < (ssize_t) geometry->height; y++)
{
MagickBooleanType
sync;
const Quantum
*magick_restrict p;
ssize_t
x;
Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,geometry->x,y+geometry->y,
geometry->width,1,exception);
q=QueueCacheViewAuthenticPixels(image_view,offset->x,y+offset->y,
geometry->width,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) geometry->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait source_traits=GetPixelChannelTraits(source_image,channel);
if ((traits == UndefinedPixelTrait) ||
((traits & UpdatePixelTrait) == 0) ||
(source_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(image,channel,p[i],q);
}
p+=GetPixelChannels(source_image);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,CopyImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImage() dereferences an image, deallocating memory associated with
% the image if the reference count becomes zero.
%
% The format of the DestroyImage method is:
%
% Image *DestroyImage(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *DestroyImage(Image *image)
{
MagickBooleanType
destroy;
/*
Dereference image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
destroy=MagickFalse;
LockSemaphoreInfo(image->semaphore);
image->reference_count--;
if (image->reference_count == 0)
destroy=MagickTrue;
UnlockSemaphoreInfo(image->semaphore);
if (destroy == MagickFalse)
return((Image *) NULL);
/*
Destroy image.
*/
DestroyImagePixels(image);
image->channel_map=DestroyPixelChannelMap(image->channel_map);
if (image->montage != (char *) NULL)
image->montage=DestroyString(image->montage);
if (image->directory != (char *) NULL)
image->directory=DestroyString(image->directory);
if (image->colormap != (PixelInfo *) NULL)
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
if (image->geometry != (char *) NULL)
image->geometry=DestroyString(image->geometry);
DestroyImageProfiles(image);
DestroyImageProperties(image);
DestroyImageArtifacts(image);
if (image->ascii85 != (Ascii85Info *) NULL)
image->ascii85=(Ascii85Info *) RelinquishMagickMemory(image->ascii85);
if (image->image_info != (ImageInfo *) NULL)
image->image_info=DestroyImageInfo(image->image_info);
DestroyBlob(image);
if (image->semaphore != (SemaphoreInfo *) NULL)
RelinquishSemaphoreInfo(&image->semaphore);
image->signature=(~MagickCoreSignature);
image=(Image *) RelinquishMagickMemory(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyImageInfo() deallocates memory associated with an ImageInfo
% structure.
%
% The format of the DestroyImageInfo method is:
%
% ImageInfo *DestroyImageInfo(ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport ImageInfo *DestroyImageInfo(ImageInfo *image_info)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
if (image_info->size != (char *) NULL)
image_info->size=DestroyString(image_info->size);
if (image_info->extract != (char *) NULL)
image_info->extract=DestroyString(image_info->extract);
if (image_info->scenes != (char *) NULL)
image_info->scenes=DestroyString(image_info->scenes);
if (image_info->page != (char *) NULL)
image_info->page=DestroyString(image_info->page);
if (image_info->sampling_factor != (char *) NULL)
image_info->sampling_factor=DestroyString(
image_info->sampling_factor);
if (image_info->server_name != (char *) NULL)
image_info->server_name=DestroyString(
image_info->server_name);
if (image_info->font != (char *) NULL)
image_info->font=DestroyString(image_info->font);
if (image_info->texture != (char *) NULL)
image_info->texture=DestroyString(image_info->texture);
if (image_info->density != (char *) NULL)
image_info->density=DestroyString(image_info->density);
if (image_info->cache != (void *) NULL)
image_info->cache=DestroyPixelCache(image_info->cache);
if (image_info->profile != (StringInfo *) NULL)
image_info->profile=(void *) DestroyStringInfo((StringInfo *)
image_info->profile);
DestroyImageOptions(image_info);
image_info->signature=(~MagickCoreSignature);
image_info=(ImageInfo *) RelinquishMagickMemory(image_info);
return(image_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i s a s s o c i a t e I m a g e S t r e a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DisassociateImageStream() disassociates the image stream. It checks if the
% blob of the specified image is referenced by other images. If the reference
% count is higher then 1 a new blob is assigned to the specified image.
%
% The format of the DisassociateImageStream method is:
%
% void DisassociateImageStream(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void DisassociateImageStream(Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
DisassociateBlob(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageInfo() initializes image_info to default values.
%
% The format of the GetImageInfo method is:
%
% void GetImageInfo(ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport void GetImageInfo(ImageInfo *image_info)
{
char
*synchronize;
ExceptionInfo
*exception;
/*
File and image dimension members.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image_info != (ImageInfo *) NULL);
(void) memset(image_info,0,sizeof(*image_info));
image_info->adjoin=MagickTrue;
image_info->interlace=NoInterlace;
image_info->channel=DefaultChannels;
image_info->quality=UndefinedCompressionQuality;
image_info->antialias=MagickTrue;
image_info->dither=MagickTrue;
synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE");
if (synchronize != (const char *) NULL)
{
image_info->synchronize=IsStringTrue(synchronize);
synchronize=DestroyString(synchronize);
}
exception=AcquireExceptionInfo();
(void) QueryColorCompliance(BackgroundColor,AllCompliance,
&image_info->background_color,exception);
(void) QueryColorCompliance(BorderColor,AllCompliance,
&image_info->border_color,exception);
(void) QueryColorCompliance(MatteColor,AllCompliance,&image_info->matte_color,
exception);
(void) QueryColorCompliance(TransparentColor,AllCompliance,
&image_info->transparent_color,exception);
exception=DestroyExceptionInfo(exception);
image_info->debug=IsEventLogging();
image_info->signature=MagickCoreSignature;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e I n f o F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageInfoFile() returns the image info file member.
%
% The format of the GetImageInfoFile method is:
%
% FILE *GetImageInfoFile(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport FILE *GetImageInfoFile(const ImageInfo *image_info)
{
return(image_info->file);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageMask() returns the mask associated with the image.
%
% The format of the GetImageMask method is:
%
% Image *GetImageMask(const Image *image,const PixelMask type,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the mask type, ReadPixelMask or WritePixelMask.
%
*/
MagickExport Image *GetImageMask(const Image *image,const PixelMask type,
ExceptionInfo *exception)
{
CacheView
*mask_view,
*image_view;
Image
*mask_image;
MagickBooleanType
status;
ssize_t
y;
/*
Get image mask.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
switch (type)
{
case ReadPixelMask:
{
if ((image->channels & ReadMaskChannel) == 0)
return((Image *) NULL);
break;
}
case WritePixelMask:
{
if ((image->channels & WriteMaskChannel) == 0)
return((Image *) NULL);
break;
}
default:
{
if ((image->channels & CompositeMaskChannel) == 0)
return((Image *) NULL);
break;
}
}
mask_image=AcquireImage((ImageInfo *) NULL,exception);
status=SetImageExtent(mask_image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImage(mask_image));
status=MagickTrue;
mask_image->alpha_trait=UndefinedPixelTrait;
(void) SetImageColorspace(mask_image,GRAYColorspace,exception);
image_view=AcquireVirtualCacheView(image,exception);
mask_view=AcquireAuthenticCacheView(mask_image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(mask_view,0,y,mask_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
switch (type)
{
case ReadPixelMask:
{
SetPixelGray(mask_image,GetPixelReadMask(image,p),q);
break;
}
case WritePixelMask:
{
SetPixelGray(mask_image,GetPixelWriteMask(image,p),q);
break;
}
default:
{
SetPixelGray(mask_image,GetPixelCompositeMask(image,p),q);
break;
}
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(mask_image);
}
if (SyncCacheViewAuthenticPixels(mask_view,exception) == MagickFalse)
status=MagickFalse;
}
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
mask_image=DestroyImage(mask_image);
return(mask_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e R e f e r e n c e C o u n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageReferenceCount() returns the image reference count.
%
% The format of the GetReferenceCount method is:
%
% ssize_t GetImageReferenceCount(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport ssize_t GetImageReferenceCount(Image *image)
{
ssize_t
reference_count;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
LockSemaphoreInfo(image->semaphore);
reference_count=image->reference_count;
UnlockSemaphoreInfo(image->semaphore);
return(reference_count);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageVirtualPixelMethod() gets the "virtual pixels" method for the
% image. A virtual pixel is any pixel access that is outside the boundaries
% of the image cache.
%
% The format of the GetImageVirtualPixelMethod() method is:
%
% VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport VirtualPixelMethod GetImageVirtualPixelMethod(const Image *image)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
return(GetPixelCacheVirtualMethod(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p r e t I m a g e F i l e n a m e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpretImageFilename() interprets embedded characters in an image filename.
% The filename length is returned.
%
% The format of the InterpretImageFilename method is:
%
% size_t InterpretImageFilename(const ImageInfo *image_info,Image *image,
% const char *format,int value,char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info..
%
% o image: the image.
%
% o format: A filename describing the format to use to write the numeric
% argument. Only the first numeric format identifier is replaced.
%
% o value: Numeric value to substitute into format filename.
%
% o filename: return the formatted filename in this character buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport size_t InterpretImageFilename(const ImageInfo *image_info,
Image *image,const char *format,int value,char *filename,
ExceptionInfo *exception)
{
char
*q;
const char
*p;
int
c;
MagickBooleanType
canonical;
ssize_t
field_width,
offset;
canonical=MagickFalse;
offset=0;
(void) CopyMagickString(filename,format,MagickPathExtent);
if (IsStringTrue(GetImageOption(image_info,"filename:literal")) != MagickFalse)
return(strlen(filename));
for (p=strchr(format,'%'); p != (char *) NULL; p=strchr(p+1,'%'))
{
q=(char *) p+1;
if (*q == '%')
{
p=q+1;
continue;
}
field_width=0;
if (*q == '0')
field_width=(ssize_t) strtol(q,&q,10);
switch (*q)
{
case 'd':
case 'o':
case 'x':
{
q++;
c=(*q);
*q='\0';
(void) FormatLocaleString(filename+(p-format-offset),(size_t)
(MagickPathExtent-(p-format-offset)),p,value);
offset+=(4-field_width);
*q=c;
(void) ConcatenateMagickString(filename,q,MagickPathExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
case '[':
{
char
pattern[MagickPathExtent];
const char
*option;
char
*r;
ssize_t
i;
ssize_t
depth;
/*
Image option.
*/
if (strchr(p,']') == (char *) NULL)
break;
depth=1;
r=q+1;
for (i=0; (i < (MagickPathExtent-1L)) && (*r != '\0'); i++)
{
if (*r == '[')
depth++;
if (*r == ']')
depth--;
if (depth <= 0)
break;
pattern[i]=(*r++);
}
pattern[i]='\0';
if (LocaleNCompare(pattern,"filename:",9) != 0)
break;
option=(const char *) NULL;
if (image != (Image *) NULL)
option=GetImageProperty(image,pattern,exception);
if ((option == (const char *) NULL) && (image != (Image *) NULL))
option=GetImageArtifact(image,pattern);
if ((option == (const char *) NULL) &&
(image_info != (ImageInfo *) NULL))
option=GetImageOption(image_info,pattern);
if (option == (const char *) NULL)
break;
q--;
c=(*q);
*q='\0';
(void) CopyMagickString(filename+(p-format-offset),option,(size_t)
(MagickPathExtent-(p-format-offset)));
offset+=strlen(pattern)-strlen(option)+3;
*q=c;
(void) ConcatenateMagickString(filename,r+1,MagickPathExtent);
canonical=MagickTrue;
if (*(q-1) != '%')
break;
p++;
break;
}
default:
break;
}
}
if (canonical == MagickFalse)
(void) CopyMagickString(filename,format,MagickPathExtent);
else
for (q=filename; *q != '\0'; q++)
if ((*q == '%') && (*(q+1) == '%'))
(void) CopyMagickString(q,q+1,(size_t) (MagickPathExtent-(q-filename)));
return(strlen(filename));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H i g h D y n a m i c R a n g e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHighDynamicRangeImage() returns MagickTrue if any pixel component is
% non-integer or exceeds the bounds of the quantum depth (e.g. for Q16
% 0..65535.
%
% The format of the IsHighDynamicRangeImage method is:
%
% MagickBooleanType IsHighDynamicRangeImage(const Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType IsHighDynamicRangeImage(const Image *image,
ExceptionInfo *exception)
{
#if !defined(MAGICKCORE_HDRI_SUPPORT)
(void) image;
(void) exception;
return(MagickFalse);
#else
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*p;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
pixel;
PixelTrait
traits;
traits=GetPixelChannelTraits(image,(PixelChannel) i);
if (traits == UndefinedPixelTrait)
continue;
pixel=(double) p[i];
if ((pixel < 0.0) || (pixel > QuantumRange) ||
(pixel != (double) ((QuantumAny) pixel)))
break;
}
p+=GetPixelChannels(image);
if (i < (ssize_t) GetPixelChannels(image))
status=MagickFalse;
}
if (x < (ssize_t) image->columns)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status != MagickFalse ? MagickFalse : MagickTrue);
#endif
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s I m a g e O b j e c t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsImageObject() returns MagickTrue if the image sequence contains a valid
% set of image objects.
%
% The format of the IsImageObject method is:
%
% MagickBooleanType IsImageObject(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsImageObject(const Image *image)
{
const Image
*p;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
if (p->signature != MagickCoreSignature)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTaintImage() returns MagickTrue any pixel in the image has been altered
% since it was first constituted.
%
% The format of the IsTaintImage method is:
%
% MagickBooleanType IsTaintImage(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport MagickBooleanType IsTaintImage(const Image *image)
{
char
magick[MagickPathExtent],
filename[MagickPathExtent];
const Image
*p;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
(void) CopyMagickString(magick,image->magick,MagickPathExtent);
(void) CopyMagickString(filename,image->filename,MagickPathExtent);
for (p=image; p != (Image *) NULL; p=GetNextImageInList(p))
{
if (p->taint != MagickFalse)
return(MagickTrue);
if (LocaleCompare(p->magick,magick) != 0)
return(MagickTrue);
if (LocaleCompare(p->filename,filename) != 0)
return(MagickTrue);
}
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M o d i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ModifyImage() ensures that there is only a single reference to the image
% to be modified, updating the provided image pointer to point to a clone of
% the original image if necessary.
%
% The format of the ModifyImage method is:
%
% MagickBooleanType ModifyImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ModifyImage(Image **image,
ExceptionInfo *exception)
{
Image
*clone_image;
assert(image != (Image **) NULL);
assert(*image != (Image *) NULL);
assert((*image)->signature == MagickCoreSignature);
if ((*image)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
if (GetImageReferenceCount(*image) <= 1)
return(MagickTrue);
clone_image=CloneImage(*image,0,0,MagickTrue,exception);
LockSemaphoreInfo((*image)->semaphore);
(*image)->reference_count--;
UnlockSemaphoreInfo((*image)->semaphore);
*image=clone_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e w M a g i c k I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NewMagickImage() creates a blank image canvas of the specified size and
% background color.
%
% The format of the NewMagickImage method is:
%
% Image *NewMagickImage(const ImageInfo *image_info,const size_t width,
% const size_t height,const PixelInfo *background,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the image width.
%
% o height: the image height.
%
% o background: the image color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *NewMagickImage(const ImageInfo *image_info,
const size_t width,const size_t height,const PixelInfo *background,
ExceptionInfo *exception)
{
CacheView
*image_view;
Image
*image;
MagickBooleanType
status;
ssize_t
y;
assert(image_info != (const ImageInfo *) NULL);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image_info->signature == MagickCoreSignature);
assert(background != (const PixelInfo *) NULL);
image=AcquireImage(image_info,exception);
image->columns=width;
image->rows=height;
image->colorspace=background->colorspace;
image->alpha_trait=background->alpha_trait;
image->fuzz=background->fuzz;
image->depth=background->depth;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,background,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e f e r e n c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReferenceImage() increments the reference count associated with an image
% returning a pointer to the image.
%
% The format of the ReferenceImage method is:
%
% Image *ReferenceImage(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport Image *ReferenceImage(Image *image)
{
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
LockSemaphoreInfo(image->semaphore);
image->reference_count++;
UnlockSemaphoreInfo(image->semaphore);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t I m a g e P a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImagePage() resets the image page canvas and position.
%
% The format of the ResetImagePage method is:
%
% MagickBooleanType ResetImagePage(Image *image,const char *page)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o page: the relative page specification.
%
*/
MagickExport MagickBooleanType ResetImagePage(Image *image,const char *page)
{
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
flags=ParseAbsoluteGeometry(page,&geometry);
if ((flags & WidthValue) != 0)
{
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
image->page.width=geometry.width;
image->page.height=geometry.height;
}
if ((flags & AspectValue) != 0)
{
if ((flags & XValue) != 0)
image->page.x+=geometry.x;
if ((flags & YValue) != 0)
image->page.y+=geometry.y;
}
else
{
if ((flags & XValue) != 0)
{
image->page.x=geometry.x;
if ((image->page.width == 0) && (geometry.x > 0))
image->page.width=image->columns+geometry.x;
}
if ((flags & YValue) != 0)
{
image->page.y=geometry.y;
if ((image->page.height == 0) && (geometry.y > 0))
image->page.height=image->rows+geometry.y;
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s e t I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResetImagePixels() reset the image pixels, that is, all the pixel components
% are zereod.
%
% The format of the SetImage method is:
%
% MagickBooleanType ResetImagePixels(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ResetImagePixels(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
size_t
length;
ssize_t
y;
void
*pixels;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
pixels=AcquirePixelCachePixels(image,&length,exception);
if (pixels != (void *) NULL)
{
/*
Reset in-core image pixels.
*/
(void) memset(pixels,0,length);
return(MagickTrue);
}
/*
Reset image pixels.
*/
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) memset(q,0,GetPixelChannels(image)*sizeof(Quantum));
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e A l p h a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageAlpha() sets the alpha levels of the image.
%
% The format of the SetImageAlpha method is:
%
% MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o alpha: the level of transparency: 0 is fully transparent and QuantumRange
% is fully opaque.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageAlpha(Image *image,const Quantum alpha,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) > (QuantumRange/2))
SetPixelAlpha(image,alpha,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e B a c k g r o u n d C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageBackgroundColor() initializes the image pixels to the image
% background color. The background color is defined by the background_color
% member of the image structure.
%
% The format of the SetImage method is:
%
% MagickBooleanType SetImageBackgroundColor(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageBackgroundColor(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
background;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if ((image->background_color.alpha_trait != UndefinedPixelTrait) &&
(image->alpha_trait == UndefinedPixelTrait))
(void) SetImageAlphaChannel(image,OnAlphaChannel,exception);
ConformPixelInfo(image,&image->background_color,&background,exception);
/*
Set image background color.
*/
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,&background,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C h a n n e l M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageChannelMask() sets the image channel mask from the specified channel
% mask.
%
% The format of the SetImageChannelMask method is:
%
% ChannelType SetImageChannelMask(Image *image,
% const ChannelType channel_mask)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel_mask: the channel mask.
%
*/
MagickExport ChannelType SetImageChannelMask(Image *image,
const ChannelType channel_mask)
{
return(SetPixelChannelMask(image,channel_mask));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColor() set the entire image canvas to the specified color.
%
% The format of the SetImageColor method is:
%
% MagickBooleanType SetImageColor(Image *image,const PixelInfo *color,
% ExeptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o background: the image color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageColor(Image *image,
const PixelInfo *color,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
assert(color != (const PixelInfo *) NULL);
image->colorspace=color->colorspace;
image->alpha_trait=color->alpha_trait;
image->fuzz=color->fuzz;
image->depth=color->depth;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(image,color,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e S t o r a g e C l a s s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageStorageClass() sets the image class: DirectClass for true color
% images or PseudoClass for colormapped images.
%
% The format of the SetImageStorageClass method is:
%
% MagickBooleanType SetImageStorageClass(Image *image,
% const ClassType storage_class,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o storage_class: The image class.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageStorageClass(Image *image,
const ClassType storage_class,ExceptionInfo *exception)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image->storage_class=storage_class;
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageExtent() sets the image size (i.e. columns & rows).
%
% The format of the SetImageExtent method is:
%
% MagickBooleanType SetImageExtent(Image *image,const size_t columns,
% const size_t rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: The image width in pixels.
%
% o rows: The image height in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageExtent(Image *image,const size_t columns,
const size_t rows,ExceptionInfo *exception)
{
if ((columns == 0) || (rows == 0))
ThrowBinaryException(ImageError,"NegativeOrZeroImageSize",image->filename);
image->columns=columns;
image->rows=rows;
if (image->depth == 0)
{
image->depth=8;
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageDepthNotSupported","`%s'",image->filename);
}
if (image->depth > (8*sizeof(MagickSizeType)))
{
image->depth=8*sizeof(MagickSizeType);
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageDepthNotSupported","`%s'",image->filename);
}
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t I m a g e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfo() initializes the 'magick' field of the ImageInfo structure.
% It is set to a type of image format based on the prefix or suffix of the
% filename. For example, 'ps:image' returns PS indicating a Postscript image.
% JPEG is returned for this filename: 'image.jpg'. The filename prefix has
% precendence over the suffix. Use an optional index enclosed in brackets
% after a file name to specify a desired scene of a multi-resolution image
% format like Photo CD (e.g. img0001.pcd[4]). A True (non-zero) return value
% indicates success.
%
% The format of the SetImageInfo method is:
%
% MagickBooleanType SetImageInfo(ImageInfo *image_info,
% const unsigned int frames,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o frames: the number of images you intend to write.
%
% o exception: return any errors or warnings in this structure.
%
*/
static const MagickInfo *SetImageInfoFromExtension(ImageInfo *image_info,
const char *component,char *magic,ExceptionInfo *exception)
{
const MagickInfo
*magick_info;
MagickFormatType
format_type;
ssize_t
i;
static const char
*format_type_formats[] =
{
"AUTOTRACE",
"BROWSE",
"DCRAW",
"EDIT",
"LAUNCH",
"MPEG:DECODE",
"MPEG:ENCODE",
"PRINT",
"PS:ALPHA",
"PS:CMYK",
"PS:COLOR",
"PS:GRAY",
"PS:MONO",
"SCAN",
"SHOW",
"WIN",
(char *) NULL
};
/*
User specified image format.
*/
(void) CopyMagickString(magic,component,MagickPathExtent);
LocaleUpper(magic);
/*
Look for explicit image formats.
*/
format_type=UndefinedFormatType;
magick_info=GetMagickInfo(magic,exception);
if ((magick_info != (const MagickInfo *) NULL) &&
(magick_info->format_type != UndefinedFormatType))
format_type=magick_info->format_type;
i=0;
while ((format_type == UndefinedFormatType) &&
(format_type_formats[i] != (char *) NULL))
{
if ((*magic == *format_type_formats[i]) &&
(LocaleCompare(magic,format_type_formats[i]) == 0))
format_type=ExplicitFormatType;
i++;
}
if (format_type == UndefinedFormatType)
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
else
if (format_type == ExplicitFormatType)
{
image_info->affirm=MagickTrue;
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
}
if (LocaleCompare(magic,"RGB") == 0)
image_info->affirm=MagickFalse; /* maybe SGI disguised as RGB */
return(magick_info);
}
MagickExport MagickBooleanType SetImageInfo(ImageInfo *image_info,
const unsigned int frames,ExceptionInfo *exception)
{
char
component[MagickPathExtent],
magic[MagickPathExtent],
path[MagickPathExtent],
*q;
const MagicInfo
*magic_info;
const MagickInfo
*magick_info;
ExceptionInfo
*sans_exception;
Image
*image;
MagickBooleanType
status;
const char
*p;
ssize_t
count;
/*
Look for 'image.format' in filename.
*/
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
*component='\0';
GetPathComponent(image_info->filename,SubimagePath,component);
if (*component != '\0')
{
/*
Look for scene specification (e.g. img0001.pcd[4]).
*/
if (IsSceneGeometry(component,MagickFalse) == MagickFalse)
{
if (IsGeometry(component) != MagickFalse)
(void) CloneString(&image_info->extract,component);
}
else
{
size_t
first,
last;
(void) CloneString(&image_info->scenes,component);
image_info->scene=StringToUnsignedLong(image_info->scenes);
image_info->number_scenes=image_info->scene;
p=image_info->scenes;
for (q=(char *) image_info->scenes; *q != '\0'; p++)
{
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
first=(size_t) strtol(p,&q,10);
last=first;
while (isspace((int) ((unsigned char) *q)) != 0)
q++;
if (*q == '-')
last=(size_t) strtol(q+1,&q,10);
if (first > last)
Swap(first,last);
if (first < image_info->scene)
image_info->scene=first;
if (last > image_info->number_scenes)
image_info->number_scenes=last;
p=q;
}
image_info->number_scenes-=image_info->scene-1;
}
}
*component='\0';
if (*image_info->magick == '\0')
GetPathComponent(image_info->filename,ExtensionPath,component);
if (*component != '\0')
{
/*
Base path sans any compression extension.
*/
GetPathComponent(image_info->filename,BasePathSansCompressExtension,path);
GetPathComponent(path,ExtensionPath,component);
}
image_info->affirm=MagickFalse;
sans_exception=AcquireExceptionInfo();
if ((*component != '\0') && (IsGlob(component) == MagickFalse))
magick_info=SetImageInfoFromExtension(image_info,component,magic,
sans_exception);
/*
Look for explicit 'format:image' in filename.
*/
*magic='\0';
GetPathComponent(image_info->filename,MagickPath,magic);
if (*magic == '\0')
{
(void) CopyMagickString(magic,image_info->magick,MagickPathExtent);
magick_info=GetMagickInfo(magic,sans_exception);
if (frames == 0)
GetPathComponent(image_info->filename,CanonicalPath,component);
else
GetPathComponent(image_info->filename,SubcanonicalPath,component);
(void) CopyMagickString(image_info->filename,component,MagickPathExtent);
}
else
{
const DelegateInfo
*delegate_info;
/*
User specified image format.
*/
LocaleUpper(magic);
magick_info=GetMagickInfo(magic,sans_exception);
delegate_info=(const DelegateInfo *) NULL;
if (magick_info == (const MagickInfo *) NULL)
{
delegate_info=GetDelegateInfo(magic,"*",sans_exception);
if (delegate_info == (const DelegateInfo *) NULL)
delegate_info=GetDelegateInfo("*",magic,sans_exception);
if ((delegate_info == (const DelegateInfo *) NULL) &&
((*component != '\0') && (IsGlob(component) == MagickFalse)))
{
/*
Retry in case GetMagickInfo loaded a custom module.
*/
magick_info=SetImageInfoFromExtension(image_info,component,magic,
sans_exception);
}
}
if (((magick_info != (const MagickInfo *) NULL) ||
(delegate_info != (const DelegateInfo *) NULL)) &&
(IsMagickConflict(magic) == MagickFalse))
{
image_info->affirm=MagickTrue;
(void) CopyMagickString(image_info->magick,magic,MagickPathExtent);
GetPathComponent(image_info->filename,CanonicalPath,component);
(void) CopyMagickString(image_info->filename,component,
MagickPathExtent);
}
}
sans_exception=DestroyExceptionInfo(sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
if ((image_info->adjoin != MagickFalse) && (frames > 1))
{
/*
Test for multiple image support (e.g. image%02d.png).
*/
(void) InterpretImageFilename(image_info,(Image *) NULL,
image_info->filename,(int) image_info->scene,component,exception);
if ((LocaleCompare(component,image_info->filename) != 0) &&
(strchr(component,'%') == (char *) NULL))
image_info->adjoin=MagickFalse;
}
if ((image_info->adjoin != MagickFalse) && (frames > 0))
{
/*
Some image formats do not support multiple frames per file.
*/
magick_info=GetMagickInfo(magic,exception);
if (magick_info != (const MagickInfo *) NULL)
if (GetMagickAdjoin(magick_info) == MagickFalse)
image_info->adjoin=MagickFalse;
}
if (image_info->affirm != MagickFalse)
return(MagickTrue);
if (frames == 0)
{
unsigned char
*magick;
size_t
magick_size;
/*
Determine the image format from the first few bytes of the file.
*/
magick_size=GetMagicPatternExtent(exception);
if (magick_size == 0)
return(MagickFalse);
image=AcquireImage(image_info,exception);
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImage(image);
return(MagickFalse);
}
if ((IsBlobSeekable(image) == MagickFalse) ||
(IsBlobExempt(image) != MagickFalse))
{
/*
Copy image to seekable temporary file.
*/
*component='\0';
status=ImageToFile(image,component,exception);
(void) CloseBlob(image);
if (status == MagickFalse)
{
(void) RelinquishUniqueFileResource(component);
image=DestroyImage(image);
return(MagickFalse);
}
SetImageInfoFile(image_info,(FILE *) NULL);
(void) CopyMagickString(image->filename,component,MagickPathExtent);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
(void) RelinquishUniqueFileResource(component);
image=DestroyImage(image);
return(MagickFalse);
}
(void) CopyMagickString(image_info->filename,component,
MagickPathExtent);
image_info->temporary=MagickTrue;
}
magick=(unsigned char *) AcquireQuantumMemory(1,magick_size);
if (magick == (unsigned char *) NULL)
{
(void) CloseBlob(image);
image=DestroyImage(image);
return(MagickFalse);
}
(void) memset(magick,0,magick_size);
count=ReadBlob(image,magick_size,magick);
(void) SeekBlob(image,-((MagickOffsetType) count),SEEK_CUR);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Check magic cache.
*/
sans_exception=AcquireExceptionInfo();
magic_info=GetMagicInfo(magick,(size_t) count,sans_exception);
magick=(unsigned char *) RelinquishMagickMemory(magick);
if ((magic_info != (const MagicInfo *) NULL) &&
(GetMagicName(magic_info) != (char *) NULL))
{
/*
Try to use magick_info that was determined earlier by the extension
*/
if ((magick_info != (const MagickInfo *) NULL) &&
(GetMagickUseExtension(magick_info) != MagickFalse) &&
(LocaleCompare(magick_info->magick_module,GetMagicName(
magic_info)) == 0))
(void) CopyMagickString(image_info->magick,magick_info->name,
MagickPathExtent);
else
{
(void) CopyMagickString(image_info->magick,GetMagicName(
magic_info),MagickPathExtent);
magick_info=GetMagickInfo(image_info->magick,sans_exception);
}
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
sans_exception=DestroyExceptionInfo(sans_exception);
return(MagickTrue);
}
magick_info=GetMagickInfo(image_info->magick,sans_exception);
if ((magick_info == (const MagickInfo *) NULL) ||
(GetMagickEndianSupport(magick_info) == MagickFalse))
image_info->endian=UndefinedEndian;
sans_exception=DestroyExceptionInfo(sans_exception);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o B l o b %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoBlob() sets the image info blob member.
%
% The format of the SetImageInfoBlob method is:
%
% void SetImageInfoBlob(ImageInfo *image_info,const void *blob,
% const size_t length)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o blob: the blob.
%
% o length: the blob length.
%
*/
MagickExport void SetImageInfoBlob(ImageInfo *image_info,const void *blob,
const size_t length)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->blob=(void *) blob;
image_info->length=length;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o C u s t o m S t r e a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoCustomStream() sets the image info custom stream handlers.
%
% The format of the SetImageInfoCustomStream method is:
%
% void SetImageInfoCustomStream(ImageInfo *image_info,
% CustomStreamInfo *custom_stream)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o custom_stream: your custom stream methods.
%
*/
MagickExport void SetImageInfoCustomStream(ImageInfo *image_info,
CustomStreamInfo *custom_stream)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->custom_stream=(CustomStreamInfo *) custom_stream;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e I n f o F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageInfoFile() sets the image info file member.
%
% The format of the SetImageInfoFile method is:
%
% void SetImageInfoFile(ImageInfo *image_info,FILE *file)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o file: the file.
%
*/
MagickExport void SetImageInfoFile(ImageInfo *image_info,FILE *file)
{
assert(image_info != (ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
image_info->file=file;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageMask() associates a mask with the image. The mask must be the same
% dimensions as the image.
%
% The format of the SetImageMask method is:
%
% MagickBooleanType SetImageMask(Image *image,const PixelMask type,
% const Image *mask,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the mask type, ReadPixelMask or WritePixelMask.
%
% o mask: the image mask.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageMask(Image *image,const PixelMask type,
const Image *mask,ExceptionInfo *exception)
{
CacheView
*mask_view,
*image_view;
MagickBooleanType
status;
ssize_t
y;
/*
Set image mask.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (mask == (const Image *) NULL)
{
switch (type)
{
case ReadPixelMask:
{
image->channels=(ChannelType) (image->channels & ~ReadMaskChannel);
break;
}
case WritePixelMask:
{
image->channels=(ChannelType) (image->channels & ~WriteMaskChannel);
}
default:
{
image->channels=(ChannelType) (image->channels & ~CompositeMaskChannel);
break;
}
}
return(SyncImagePixelCache(image,exception));
}
switch (type)
{
case ReadPixelMask:
{
image->channels=(ChannelType) (image->channels | ReadMaskChannel);
break;
}
case WritePixelMask:
{
image->channels=(ChannelType) (image->channels | WriteMaskChannel);
break;
}
default:
{
image->channels=(ChannelType) (image->channels | CompositeMaskChannel);
break;
}
}
if (SyncImagePixelCache(image,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
image->mask_trait=UpdatePixelTrait;
mask_view=AcquireVirtualCacheView(mask,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(mask,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(mask_view,0,y,mask->columns,1,exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
intensity;
intensity=0.0;
if ((x < (ssize_t) mask->columns) && (y < (ssize_t) mask->rows))
intensity=GetPixelIntensity(mask,p);
switch (type)
{
case ReadPixelMask:
{
SetPixelReadMask(image,ClampToQuantum(intensity),q);
break;
}
case WritePixelMask:
{
SetPixelWriteMask(image,ClampToQuantum(intensity),q);
break;
}
default:
{
SetPixelCompositeMask(image,ClampToQuantum(intensity),q);
break;
}
}
p+=GetPixelChannels(mask);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image->mask_trait=UndefinedPixelTrait;
mask_view=DestroyCacheView(mask_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e R e g i o n M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageRegionMask() associates a mask with the image as defined by the
% specified region.
%
% The format of the SetImageRegionMask method is:
%
% MagickBooleanType SetImageRegionMask(Image *image,const PixelMask type,
% const RectangleInfo *region,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the mask type, ReadPixelMask or WritePixelMask.
%
% o geometry: the mask region.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetImageRegionMask(Image *image,
const PixelMask type,const RectangleInfo *region,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
/*
Set image mask as defined by the region.
*/
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (region == (const RectangleInfo *) NULL)
{
switch (type)
{
case ReadPixelMask:
{
image->channels=(ChannelType) (image->channels & ~ReadMaskChannel);
break;
}
case WritePixelMask:
{
image->channels=(ChannelType) (image->channels & ~WriteMaskChannel);
break;
}
default:
{
image->channels=(ChannelType) (image->channels & ~CompositeMaskChannel);
break;
}
}
return(SyncImagePixelCache(image,exception));
}
switch (type)
{
case ReadPixelMask:
{
image->channels=(ChannelType) (image->channels | ReadMaskChannel);
break;
}
case WritePixelMask:
{
image->channels=(ChannelType) (image->channels | WriteMaskChannel);
break;
}
default:
{
image->channels=(ChannelType) (image->channels | CompositeMaskChannel);
break;
}
}
if (SyncImagePixelCache(image,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
image->mask_trait=UpdatePixelTrait;
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++)
{
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
Quantum
pixel;
pixel=QuantumRange;
if (((x >= region->x) && (x < (region->x+(ssize_t) region->width))) &&
((y >= region->y) && (y < (region->y+(ssize_t) region->height))))
pixel=(Quantum) 0;
switch (type)
{
case ReadPixelMask:
{
SetPixelReadMask(image,pixel,q);
break;
}
case WritePixelMask:
{
SetPixelWriteMask(image,pixel,q);
break;
}
default:
{
SetPixelCompositeMask(image,pixel,q);
break;
}
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image->mask_trait=UndefinedPixelTrait;
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t I m a g e V i r t u a l P i x e l M e t h o d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageVirtualPixelMethod() sets the "virtual pixels" method for the
% image and returns the previous setting. A virtual pixel is any pixel access
% that is outside the boundaries of the image cache.
%
% The format of the SetImageVirtualPixelMethod() method is:
%
% VirtualPixelMethod SetImageVirtualPixelMethod(Image *image,
% const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o virtual_pixel_method: choose the type of virtual pixel.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport VirtualPixelMethod SetImageVirtualPixelMethod(Image *image,
const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception)
{
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
return(SetPixelCacheVirtualMethod(image,virtual_pixel_method,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S m u s h I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SmushImages() takes all images from the current image pointer to the end
% of the image list and smushes them to each other top-to-bottom if the
% stack parameter is true, otherwise left-to-right.
%
% The current gravity setting now effects how the image is justified in the
% final image.
%
% The format of the SmushImages method is:
%
% Image *SmushImages(const Image *images,const MagickBooleanType stack,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o stack: A value other than 0 stacks the images top-to-bottom.
%
% o offset: minimum distance in pixels between images.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ssize_t SmushXGap(const Image *smush_image,const Image *images,
const ssize_t offset,ExceptionInfo *exception)
{
CacheView
*left_view,
*right_view;
const Image
*left_image,
*right_image;
RectangleInfo
left_geometry,
right_geometry;
const Quantum
*p;
ssize_t
i,
y;
size_t
gap;
ssize_t
x;
if (images->previous == (Image *) NULL)
return(0);
right_image=images;
SetGeometry(smush_image,&right_geometry);
GravityAdjustGeometry(right_image->columns,right_image->rows,
right_image->gravity,&right_geometry);
left_image=images->previous;
SetGeometry(smush_image,&left_geometry);
GravityAdjustGeometry(left_image->columns,left_image->rows,
left_image->gravity,&left_geometry);
gap=right_image->columns;
left_view=AcquireVirtualCacheView(left_image,exception);
right_view=AcquireVirtualCacheView(right_image,exception);
for (y=0; y < (ssize_t) smush_image->rows; y++)
{
for (x=(ssize_t) left_image->columns-1; x > 0; x--)
{
p=GetCacheViewVirtualPixels(left_view,x,left_geometry.y+y,1,1,exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(left_image,p) != TransparentAlpha) ||
((left_image->columns-x-1) >= gap))
break;
}
i=(ssize_t) left_image->columns-x-1;
for (x=0; x < (ssize_t) right_image->columns; x++)
{
p=GetCacheViewVirtualPixels(right_view,x,right_geometry.y+y,1,1,
exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(right_image,p) != TransparentAlpha) ||
((x+i) >= (ssize_t) gap))
break;
}
if ((x+i) < (ssize_t) gap)
gap=(size_t) (x+i);
}
right_view=DestroyCacheView(right_view);
left_view=DestroyCacheView(left_view);
if (y < (ssize_t) smush_image->rows)
return(offset);
return((ssize_t) gap-offset);
}
static ssize_t SmushYGap(const Image *smush_image,const Image *images,
const ssize_t offset,ExceptionInfo *exception)
{
CacheView
*bottom_view,
*top_view;
const Image
*bottom_image,
*top_image;
RectangleInfo
bottom_geometry,
top_geometry;
const Quantum
*p;
ssize_t
i,
x;
size_t
gap;
ssize_t
y;
if (images->previous == (Image *) NULL)
return(0);
bottom_image=images;
SetGeometry(smush_image,&bottom_geometry);
GravityAdjustGeometry(bottom_image->columns,bottom_image->rows,
bottom_image->gravity,&bottom_geometry);
top_image=images->previous;
SetGeometry(smush_image,&top_geometry);
GravityAdjustGeometry(top_image->columns,top_image->rows,top_image->gravity,
&top_geometry);
gap=bottom_image->rows;
top_view=AcquireVirtualCacheView(top_image,exception);
bottom_view=AcquireVirtualCacheView(bottom_image,exception);
for (x=0; x < (ssize_t) smush_image->columns; x++)
{
for (y=(ssize_t) top_image->rows-1; y > 0; y--)
{
p=GetCacheViewVirtualPixels(top_view,top_geometry.x+x,y,1,1,exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(top_image,p) != TransparentAlpha) ||
((top_image->rows-y-1) >= gap))
break;
}
i=(ssize_t) top_image->rows-y-1;
for (y=0; y < (ssize_t) bottom_image->rows; y++)
{
p=GetCacheViewVirtualPixels(bottom_view,bottom_geometry.x+x,y,1,1,
exception);
if ((p == (const Quantum *) NULL) ||
(GetPixelAlpha(bottom_image,p) != TransparentAlpha) ||
((y+i) >= (ssize_t) gap))
break;
}
if ((y+i) < (ssize_t) gap)
gap=(size_t) (y+i);
}
bottom_view=DestroyCacheView(bottom_view);
top_view=DestroyCacheView(top_view);
if (x < (ssize_t) smush_image->columns)
return(offset);
return((ssize_t) gap-offset);
}
MagickExport Image *SmushImages(const Image *images,
const MagickBooleanType stack,const ssize_t offset,ExceptionInfo *exception)
{
#define SmushImageTag "Smush/Image"
const Image
*image;
Image
*smush_image;
MagickBooleanType
proceed,
status;
MagickOffsetType
n;
PixelTrait
alpha_trait;
RectangleInfo
geometry;
const Image
*next;
size_t
height,
number_images,
width;
ssize_t
x_offset,
y_offset;
/*
Compute maximum area of smushed area.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=images;
alpha_trait=image->alpha_trait;
number_images=1;
width=image->columns;
height=image->rows;
next=GetNextImageInList(image);
for ( ; next != (Image *) NULL; next=GetNextImageInList(next))
{
if (next->alpha_trait != UndefinedPixelTrait)
alpha_trait=BlendPixelTrait;
number_images++;
if (stack != MagickFalse)
{
if (next->columns > width)
width=next->columns;
height+=next->rows;
if (next->previous != (Image *) NULL)
height+=offset;
continue;
}
width+=next->columns;
if (next->previous != (Image *) NULL)
width+=offset;
if (next->rows > height)
height=next->rows;
}
/*
Smush images.
*/
smush_image=CloneImage(image,width,height,MagickTrue,exception);
if (smush_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(smush_image,DirectClass,exception) == MagickFalse)
{
smush_image=DestroyImage(smush_image);
return((Image *) NULL);
}
smush_image->alpha_trait=alpha_trait;
(void) SetImageBackgroundColor(smush_image,exception);
status=MagickTrue;
x_offset=0;
y_offset=0;
for (n=0; n < (MagickOffsetType) number_images; n++)
{
SetGeometry(smush_image,&geometry);
GravityAdjustGeometry(image->columns,image->rows,image->gravity,&geometry);
if (stack != MagickFalse)
{
x_offset-=geometry.x;
y_offset-=SmushYGap(smush_image,image,offset,exception);
}
else
{
x_offset-=SmushXGap(smush_image,image,offset,exception);
y_offset-=geometry.y;
}
status=CompositeImage(smush_image,image,OverCompositeOp,MagickTrue,x_offset,
y_offset,exception);
proceed=SetImageProgress(image,SmushImageTag,n,number_images);
if (proceed == MagickFalse)
break;
if (stack == MagickFalse)
{
x_offset+=(ssize_t) image->columns;
y_offset=0;
}
else
{
x_offset=0;
y_offset+=(ssize_t) image->rows;
}
image=GetNextImageInList(image);
}
if (stack == MagickFalse)
smush_image->columns=(size_t) x_offset;
else
smush_image->rows=(size_t) y_offset;
if (status == MagickFalse)
smush_image=DestroyImage(smush_image);
return(smush_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S t r i p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% StripImage() strips an image of all profiles and comments.
%
% The format of the StripImage method is:
%
% MagickBooleanType StripImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType StripImage(Image *image,ExceptionInfo *exception)
{
MagickBooleanType
status;
magick_unreferenced(exception);
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
DestroyImageProfiles(image);
(void) DeleteImageProperty(image,"comment");
(void) DeleteImageProperty(image,"date:create");
(void) DeleteImageProperty(image,"date:modify");
status=SetImageArtifact(image,"png:exclude-chunk",
"bKGD,caNv,cHRM,eXIf,gAMA,iCCP,iTXt,pHYs,sRGB,tEXt,zCCP,zTXt,date");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S y n c I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImage() initializes the red, green, and blue intensities of each pixel
% as defined by the colormap index.
%
% The format of the SyncImage method is:
%
% MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PushColormapIndex(Image *image,const Quantum index,
MagickBooleanType *range_exception)
{
if ((size_t) index < image->colors)
return(index);
*range_exception=MagickTrue;
return((Quantum) 0);
}
MagickExport MagickBooleanType SyncImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
range_exception,
status,
taint;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickCoreSignature);
if (image->ping != MagickFalse)
return(MagickTrue);
if (image->storage_class != PseudoClass)
return(MagickFalse);
assert(image->colormap != (PixelInfo *) NULL);
range_exception=MagickFalse;
status=MagickTrue;
taint=image->taint;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(range_exception,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Quantum
index;
Quantum
*magick_restrict q;
ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
index=PushColormapIndex(image,GetPixelIndex(image,q),&range_exception);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
image->taint=taint;
if ((image->ping == MagickFalse) && (range_exception != MagickFalse))
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageWarning,"InvalidColormapIndex","`%s'",image->filename);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S y n c I m a g e S e t t i n g s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SyncImageSettings() syncs any image_info global options into per-image
% attributes.
%
% Note: in IMv6 free form 'options' were always mapped into 'artifacts', so
% that operations and coders can find such settings. In IMv7 if a desired
% per-image artifact is not set, then it will directly look for a global
% option as a fallback, as such this copy is no longer needed, only the
% link set up.
%
% The format of the SyncImageSettings method is:
%
% MagickBooleanType SyncImageSettings(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
% MagickBooleanType SyncImagesSettings(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SyncImagesSettings(ImageInfo *image_info,
Image *images,ExceptionInfo *exception)
{
Image
*image;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
image=images;
for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
(void) SyncImageSettings(image_info,image,exception);
(void) DeleteImageOption(image_info,"page");
return(MagickTrue);
}
MagickExport MagickBooleanType SyncImageSettings(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
const char
*option;
GeometryInfo
geometry_info;
MagickStatusType
flags;
ResolutionType
units;
/*
Sync image options.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
option=GetImageOption(image_info,"background");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->background_color,
exception);
option=GetImageOption(image_info,"black-point-compensation");
if (option != (const char *) NULL)
image->black_point_compensation=(MagickBooleanType) ParseCommandOption(
MagickBooleanOptions,MagickFalse,option);
option=GetImageOption(image_info,"blue-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=image->chromaticity.blue_primary.x;
}
option=GetImageOption(image_info,"bordercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->border_color,
exception);
/* FUTURE: do not sync compose to per-image compose setting here */
option=GetImageOption(image_info,"compose");
if (option != (const char *) NULL)
image->compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,
MagickFalse,option);
/* -- */
option=GetImageOption(image_info,"compress");
if (option != (const char *) NULL)
image->compression=(CompressionType) ParseCommandOption(
MagickCompressOptions,MagickFalse,option);
option=GetImageOption(image_info,"debug");
if (option != (const char *) NULL)
image->debug=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions,
MagickFalse,option);
option=GetImageOption(image_info,"density");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
option=GetImageOption(image_info,"depth");
if (option != (const char *) NULL)
image->depth=StringToUnsignedLong(option);
option=GetImageOption(image_info,"endian");
if (option != (const char *) NULL)
image->endian=(EndianType) ParseCommandOption(MagickEndianOptions,
MagickFalse,option);
option=GetImageOption(image_info,"filter");
if (option != (const char *) NULL)
image->filter=(FilterType) ParseCommandOption(MagickFilterOptions,
MagickFalse,option);
option=GetImageOption(image_info,"fuzz");
if (option != (const char *) NULL)
image->fuzz=StringToDoubleInterval(option,(double) QuantumRange+1.0);
option=GetImageOption(image_info,"gravity");
if (option != (const char *) NULL)
image->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(image_info,"green-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=image->chromaticity.green_primary.x;
}
option=GetImageOption(image_info,"intent");
if (option != (const char *) NULL)
image->rendering_intent=(RenderingIntent) ParseCommandOption(
MagickIntentOptions,MagickFalse,option);
option=GetImageOption(image_info,"intensity");
if (option != (const char *) NULL)
image->intensity=(PixelIntensityMethod) ParseCommandOption(
MagickPixelIntensityOptions,MagickFalse,option);
option=GetImageOption(image_info,"interlace");
if (option != (const char *) NULL)
image->interlace=(InterlaceType) ParseCommandOption(MagickInterlaceOptions,
MagickFalse,option);
option=GetImageOption(image_info,"interpolate");
if (option != (const char *) NULL)
image->interpolate=(PixelInterpolateMethod) ParseCommandOption(
MagickInterpolateOptions,MagickFalse,option);
option=GetImageOption(image_info,"loop");
if (option != (const char *) NULL)
image->iterations=StringToUnsignedLong(option);
option=GetImageOption(image_info,"mattecolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->matte_color,
exception);
option=GetImageOption(image_info,"orient");
if (option != (const char *) NULL)
image->orientation=(OrientationType) ParseCommandOption(
MagickOrientationOptions,MagickFalse,option);
option=GetImageOption(image_info,"page");
if (option != (const char *) NULL)
{
char
*geometry;
geometry=GetPageGeometry(option);
flags=ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
}
option=GetImageOption(image_info,"quality");
if (option != (const char *) NULL)
image->quality=StringToUnsignedLong(option);
option=GetImageOption(image_info,"red-primary");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
image->chromaticity.red_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.red_primary.y=image->chromaticity.red_primary.x;
}
if (image_info->quality != UndefinedCompressionQuality)
image->quality=image_info->quality;
option=GetImageOption(image_info,"scene");
if (option != (const char *) NULL)
image->scene=StringToUnsignedLong(option);
option=GetImageOption(image_info,"taint");
if (option != (const char *) NULL)
image->taint=(MagickBooleanType) ParseCommandOption(MagickBooleanOptions,
MagickFalse,option);
option=GetImageOption(image_info,"tile-offset");
if (option != (const char *) NULL)
{
char
*geometry;
geometry=GetPageGeometry(option);
flags=ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
option=GetImageOption(image_info,"transparent-color");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&image->transparent_color,
exception);
option=GetImageOption(image_info,"type");
if (option != (const char *) NULL)
image->type=(ImageType) ParseCommandOption(MagickTypeOptions,MagickFalse,
option);
option=GetImageOption(image_info,"units");
units=image_info->units;
if (option != (const char *) NULL)
units=(ResolutionType) ParseCommandOption(MagickResolutionOptions,
MagickFalse,option);
if (units != UndefinedResolution)
{
if (image->units != units)
switch (image->units)
{
case PixelsPerInchResolution:
{
if (units == PixelsPerCentimeterResolution)
{
image->resolution.x/=2.54;
image->resolution.y/=2.54;
}
break;
}
case PixelsPerCentimeterResolution:
{
if (units == PixelsPerInchResolution)
{
image->resolution.x=(double) ((size_t) (100.0*2.54*
image->resolution.x+0.5))/100.0;
image->resolution.y=(double) ((size_t) (100.0*2.54*
image->resolution.y+0.5))/100.0;
}
break;
}
default:
break;
}
image->units=units;
option=GetImageOption(image_info,"density");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->resolution.x=geometry_info.rho;
image->resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->resolution.y=image->resolution.x;
}
}
option=GetImageOption(image_info,"virtual-pixel");
if (option != (const char *) NULL)
(void) SetImageVirtualPixelMethod(image,(VirtualPixelMethod)
ParseCommandOption(MagickVirtualPixelOptions,MagickFalse,option),
exception);
option=GetImageOption(image_info,"white-point");
if (option != (const char *) NULL)
{
flags=ParseGeometry(option,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=image->chromaticity.white_point.x;
}
/*
Pointer to allow the lookup of pre-image artifact will fallback to a global
option setting/define. This saves a lot of duplication of global options
into per-image artifacts, while ensuring only specifically set per-image
artifacts are preserved when parenthesis ends.
*/
if (image->image_info != (ImageInfo *) NULL)
image->image_info=DestroyImageInfo(image->image_info);
image->image_info=CloneImageInfo(image_info);
return(MagickTrue);
}
|
residual_based_bdf_scheme.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_RESIDUAL_BASED_BDF_SCHEME )
#define KRATOS_RESIDUAL_BASED_BDF_SCHEME
/* System includes */
/* External includes */
/* Project includes */
#include "includes/checks.h"
#include "utilities/time_discretization.h"
#include "solving_strategies/schemes/residual_based_implicit_time_scheme.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class ResidualBasedBDFScheme
* @ingroup KratosCore
* @brief BDF integration scheme (for dynamic problems)
* @details The \f$ n \f$ order Backward Differentiation Formula (BDF) method is a two step \f$ n \f$ order accurate method.
* This scheme is designed to solve a system of the type:
*\f[
* \mathbf{M} \frac{d^2(u_{n0})}{dt^2} + \mathbf{D} \frac{d(un0)}{dt} + \mathbf{K} u_{n0} = \mathbf{f}_{ext}
* \f]
*
* If we call:
*
* - Second derivative:
* -# \f$ \ddot{u}_{ni} \f$ the second derivative at the step i
* - First derivative:
* -# \f$ \dot{u}_{ni} \f$ the first derivative at the step i
* - Third derivative:
* -# \f$ u_{ni} \f$ the variable at the step i
*
* Then we assume:
* \f[ \frac{d^2(u_{n0})}{dt^2} \|t_{n0} = \sum_i c_i \dot{u}_{ni} \f]
* \f[ \frac{d(u_{n0})}{dt} \|t_{n0} = \sum_i c_i u_{n0} \f]
* with for order 2 (BDF2):
* -# \f$ c_0 = \frac{1.5}{dt} \f$
* -# \f$ c_1 = \frac{-2.0}{dt} \f$
* -# \f$ c_2 = \frac{0.5}{dt} \f$
*
* The LHS and RHS can be defined as:
* \f[ RHS = \mathbf{f}_{ext} - \mathbf{M} \frac{d(\dot{u}_{n0})}{dt} - \mathbf{D} \frac{d(u_{n0})}{dt} - \mathbf{K} u_{n0} \f]
* and
* \f[ LHS = \frac{d(-RHS)}{d(u_{n0})} = c_0^2 \mathbf{M} + c_0 \mathbf{D} + K \f]
* @note This implies that elements are expected to be written in terms
* of a variable with two time derivatives
* <a href="https://mediatum.ub.tum.de/doc/1223319/80942.pdf">Main reference</a>
* @todo Create a BibTeX file https://www.stack.nl/~dimitri/doxygen/manual/commands.html#cmdcite
* @author Vicente Mataix Ferrandiz
*/
template<class TSparseSpace, class TDenseSpace>
class ResidualBasedBDFScheme
: public ResidualBasedImplicitTimeScheme<TSparseSpace, TDenseSpace>
{
public:
///@name Type Definitions
///@{
KRATOS_CLASS_POINTER_DEFINITION( ResidualBasedBDFScheme );
typedef Scheme<TSparseSpace,TDenseSpace> BaseType;
typedef typename BaseType::Pointer BaseTypePointer;
typedef ResidualBasedImplicitTimeScheme<TSparseSpace,TDenseSpace> ImplicitBaseType;
typedef typename ImplicitBaseType::TDataType TDataType;
typedef typename ImplicitBaseType::DofsArrayType DofsArrayType;
typedef typename Element::DofsVectorType DofsVectorType;
typedef typename ImplicitBaseType::TSystemMatrixType TSystemMatrixType;
typedef typename ImplicitBaseType::TSystemVectorType TSystemVectorType;
typedef typename ImplicitBaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename ImplicitBaseType::LocalSystemMatrixType LocalSystemMatrixType;
typedef ModelPart::NodesContainerType NodesArrayType;
/// Definition of epsilon
static constexpr double ZeroTolerance = std::numeric_limits<double>::epsilon();
///@}
///@name Life Cycle
///@{
/**
* @brief Constructor. The BDF method
* @param Order The integration order
* @todo The ideal would be to use directly the dof or the variable itself to identify the type of variable and is derivatives
*/
explicit ResidualBasedBDFScheme(const std::size_t Order = 2)
:ImplicitBaseType(),
mOrder(Order),
mpBDFUtility(Kratos::make_unique<TimeDiscretization::BDF>(Order))
{
// Allocate auxiliary memory
const std::size_t num_threads = OpenMPUtils::GetNumThreads();
mVector.dotun0.resize(num_threads);
mVector.dot2un0.resize(num_threads);
// Doing a minimal check
KRATOS_ERROR_IF(mOrder < 1) << "ERROR:: Not possible to compute a BDF of order less than 1" << std::endl;
// We resize the BDF coefficients
if (mBDF.size() != (mOrder + 1))
mBDF.resize(mOrder + 1);
}
/** Copy Constructor.
*/
explicit ResidualBasedBDFScheme(ResidualBasedBDFScheme& rOther)
:ImplicitBaseType(rOther)
,mOrder(rOther.mOrder)
,mBDF(rOther.mBDF)
,mVector(rOther.mVector)
,mpBDFUtility(nullptr)
{
Kratos::unique_ptr<TimeDiscretization::BDF> auxiliar_pointer = Kratos::make_unique<TimeDiscretization::BDF>(mOrder);
mpBDFUtility.swap(auxiliar_pointer);
}
/**
* Clone
*/
BaseTypePointer Clone() override
{
return BaseTypePointer( new ResidualBasedBDFScheme(*this) );
}
/** Destructor.
*/
~ResidualBasedBDFScheme
() override {}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief Performing the update of the solution
* @details Incremental update within newton iteration. It updates the state variables at the end of the time step
* \f[ u_{n+1}^{k+1}= u_{n+1}^{k}+ \Delta u\f]
* @param rModelPart The model of the problem to solve
* @param rDofSet Set of all primary variables
* @param rA LHS matrix
* @param rDx incremental update of primary variables
* @param rb RHS Vector
*/
void Update(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY;
// Update of displacement (by DOF)
mpDofUpdater->UpdateDofs(rDofSet, rDx);
UpdateDerivatives(rModelPart, rDofSet, rA, rDx, rb);
KRATOS_CATCH( "" );
}
/**
* @brief Performing the prediction of the solution
* @details It predicts the solution for the current step x = xold + vold * Dt
* @param rModelPart The model of the problem to solve
* @param rDofSet set of all primary variables
* @param rA LHS matrix
* @param rDx Incremental update of primary variables
* @param rb RHS Vector
*/
void Predict(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY;
KRATOS_ERROR << "Calling base BDF class" << std::endl;
KRATOS_CATCH( "" );
}
/**
* @brief It initializes time step solution. Only for reasons if the time step solution is restarted
* @param rModelPart The model of the problem to solve
* @param rA LHS matrix
* @param rDx Incremental update of primary variables
* @param rb RHS Vector
* @todo I cannot find the formula for the higher orders with variable time step. I tried to deduce by myself but the result was very unstable
*/
void InitializeSolutionStep(
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
) override
{
KRATOS_TRY;
ProcessInfo& r_current_process_info = rModelPart.GetProcessInfo();
ImplicitBaseType::InitializeSolutionStep(rModelPart, rA, rDx, rb);
mpBDFUtility->ComputeAndSaveBDFCoefficients(r_current_process_info);
mBDF = r_current_process_info[BDF_COEFFICIENTS];
KRATOS_WARNING_IF("ResidualBasedBDFScheme", mOrder > 2)
<< "For higher orders than 2 the time step is assumed to be constant.\n";
KRATOS_CATCH( "" );
}
/**
* @brief This function is designed to be called once to perform all the checks needed on the input provided.
* @details Checks can be "expensive" as the function is designed to catch user's errors.
* @param rModelPart The model of the problem to solve
* @return Zero means all ok
*/
int Check(ModelPart& rModelPart) override
{
KRATOS_TRY;
const int err = ImplicitBaseType::Check(rModelPart);
if(err!=0) return err;
// Check for minimum value of the buffer index
// Verify buffer size
KRATOS_ERROR_IF(rModelPart.GetBufferSize() < mOrder + 1) << "Insufficient buffer size. Buffer size should be greater than " << mOrder + 1 << ". Current size is " << rModelPart.GetBufferSize() << std::endl;
KRATOS_CATCH( "" );
return 0;
}
/// Free memory allocated by this class.
void Clear() override
{
this->mpDofUpdater->Clear();
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "ResidualBasedBDFScheme";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << Info();
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
rOStream << Info();
}
///@}
///@name Friends
///@{
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
struct GeneralVectors
{
std::vector< Vector > dotun0; /// First derivative
std::vector< Vector > dot2un0; /// Second derivative
};
const std::size_t mOrder; /// The integration order
Vector mBDF; /// The BDF coefficients
GeneralVectors mVector; /// The structure containing the derivatives
Kratos::unique_ptr<TimeDiscretization::BDF> mpBDFUtility; /// Utility to compute BDF coefficients
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
/**
* @brief Performing the update of the derivatives
* @param rModelPart The model of the problem to solve
* @param rDofSet Set of all primary variables
* @param rA LHS matrix
* @param rDx incremental update of primary variables
* @param rb RHS Vector
*/
inline void UpdateDerivatives(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb
)
{
// Updating time derivatives (nodally for efficiency)
const int num_nodes = static_cast<int>( rModelPart.Nodes().size() );
// Getting first node iterator
const auto it_node_begin = rModelPart.Nodes().begin();
#pragma omp parallel for
for(int i = 0; i< num_nodes; ++i) {
auto it_node = it_node_begin + i;
UpdateFirstDerivative(it_node);
UpdateSecondDerivative(it_node);
}
}
/**
* @brief Updating first time derivative (velocity)
* @param itNode the node interator
*/
virtual inline void UpdateFirstDerivative(NodesArrayType::iterator itNode)
{
KRATOS_ERROR << "Calling base BDF class" << std::endl;
}
/**
* @brief Updating second time derivative (acceleration)
* @param itNode the node interator
*/
virtual inline void UpdateSecondDerivative(NodesArrayType::iterator itNode)
{
KRATOS_ERROR << "Calling base BDF class" << std::endl;
}
/**
* @brief It adds the dynamic LHS contribution of the elements
* \f[ LHS = \frac{d(-RHS)}{d(u_{n0})} = c_0^2\mathbf{M} + c_0 \mathbf{D} + \mathbf{K} \f]
* @param rLHS_Contribution The dynamic contribution for the LHS
* @param rD The damping matrix
* @param rM The mass matrix
* @param rCurrentProcessInfo The current process info instance
*/
void AddDynamicsToLHS(
LocalSystemMatrixType& rLHS_Contribution,
LocalSystemMatrixType& rD,
LocalSystemMatrixType& rM,
ProcessInfo& rCurrentProcessInfo
) override
{
// Adding mass contribution to the dynamic stiffness
if (rM.size1() != 0) { // if M matrix declared
noalias(rLHS_Contribution) += rM * std::pow(mBDF[0], 2);
}
// Adding damping contribution
if (rD.size1() != 0) { // if D matrix declared
noalias(rLHS_Contribution) += rD * mBDF[0];
}
}
/**
* @brief It adds the dynamic RHS contribution of the objects
* \f[ \mathbf{b} - \mathbf{M} a - \mathbf{D} v \f]
* @param rObject The object to compute
* @param rRHS_Contribution The dynamic contribution for the RHS
* @param rD The damping matrix
* @param rM The mass matrix
* @param rCurrentProcessInfo The current process info instance
*/
template <typename TObjectType>
void TemplateAddDynamicsToRHS(
TObjectType rObject,
LocalSystemVectorType& rRHS_Contribution,
LocalSystemMatrixType& rD,
LocalSystemMatrixType& rM,
ProcessInfo& rCurrentProcessInfo
)
{
const std::size_t this_thread = OpenMPUtils::ThisThread();
// Adding inertia contribution
if (rM.size1() != 0) {
rObject->GetSecondDerivativesVector(mVector.dot2un0[this_thread], 0);
noalias(rRHS_Contribution) -= prod(rM, mVector.dot2un0[this_thread]);
}
// Adding damping contribution
if (rD.size1() != 0) {
rObject->GetFirstDerivativesVector(mVector.dotun0[this_thread], 0);
noalias(rRHS_Contribution) -= prod(rD, mVector.dotun0[this_thread]);
}
}
/**
* @brief It adds the dynamic RHS contribution of the elements
* \f[ \mathbf{b} - \mathbf{M} a - \mathbf{D} v \f]
* @param pElement The element to compute
* @param RHS_Contribution The dynamic contribution for the RHS
* @param D The damping matrix
* @param M The mass matrix
* @param rCurrentProcessInfo The current process info instance
*/
void AddDynamicsToRHS(
Element::Pointer pElement,
LocalSystemVectorType& rRHS_Contribution,
LocalSystemMatrixType& rD,
LocalSystemMatrixType& rM,
ProcessInfo& rCurrentProcessInfo
) override
{
TemplateAddDynamicsToRHS<Element::Pointer>(pElement, rRHS_Contribution, rD, rM, rCurrentProcessInfo);
}
/**
* @brief It adds the dynamic RHS contribution of the condition
* \f[ RHS = f_{ext} - \ddot{u}_{n0} \mathbf{M} + \dot{u}_{n0} \mathbf{D} + u_{n0} \mathbf{K} \f]
* @param pCondition The condition to compute
* @param RHS_Contribution The dynamic contribution for the RHS
* @param D The damping matrix
* @param M The mass matrix
* @param rCurrentProcessInfo The current process info instance
*/
void AddDynamicsToRHS(
Condition::Pointer pCondition,
LocalSystemVectorType& rRHS_Contribution,
LocalSystemMatrixType& rD,
LocalSystemMatrixType& rM,
ProcessInfo& rCurrentProcessInfo
) override
{
TemplateAddDynamicsToRHS<Condition::Pointer>(pCondition, rRHS_Contribution, rD, rM, rCurrentProcessInfo);
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@{
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
/// Utility class to perform the update after solving the system, will be different in MPI runs.
typename TSparseSpace::DofUpdaterPointerType mpDofUpdater = TSparseSpace::CreateDofUpdater();
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class ResidualBasedBDFScheme */
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
///@}
} /* namespace Kratos.*/
#endif /* KRATOS_RESIDUAL_BASED_BDF_SCHEME defined */
|
window.c | /* ~~~ Time Series Analysis -- Auxiliary ~~~
*
* Routines for calculating the spectral window
*
* Author: Jakob Rørsted Mosumgaard
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include "arrlib.h"
#define PI2micro 6.28318530717958647692528676655900576839433879875e-6
void windowalpbet(double time[], double datasin[], double datacos[], size_t N,\
double ny, double *alphasin, double *betasin,
double *alphacos, double *betacos);
void windowalpbetW(double time[], double weight[], double datasin[],\
double datacos[], size_t N, double ny, double wsum,\
double *alphasin, double *betasin, double *alphacos,\
double *betacos);
/* Calculate the window function of a time series
*
* Arguments:
* - `time` : Array of times. In seconds!
* - `freq` : Array of cyclic frequencies to sample.
* - `weight` : Array of statistical weights.
* - `N` : Length of the time series
* - `M` : Length of the sampling vector
* - `window` : OUTPUT -- Array with power of the window
* - `useweight`: Flag to signal whether to use weights or not (0 = no weights)
*/
void windowfunction(double time[], double freq[], double weight[], size_t N,\
size_t M, double f0, double window[], int useweight)
{
// Sample the time series using cos and sin at frequency f0
double* datsin = malloc(N * sizeof(double));
double* datcos = malloc(N * sizeof(double));
double omega0 = f0 * PI2micro;
for (size_t k = 0; k < N; ++k) {
datsin[k] = sin(omega0 * time[k]);
datcos[k] = cos(omega0 * time[k]);
}
// Initialise local variables
double alphasin = 0;
double betasin = 0;
double alphacos = 0;
double betacos = 0;
double ny = 0;
size_t i;
// Call functions with or without weights
if ( useweight == 0 ) {
// Make parallel loop over all test frequencies
#pragma omp parallel default(shared) private(alphasin, betasin, alphacos, betacos, ny)
{
#pragma omp for schedule(static)
for (i = 0; i < M; ++i) {
// Current frequency
ny = freq[i] * PI2micro;
// Calculate alpha and beta for cos and sin data
windowalpbet(time, datsin, datcos, N, ny, &alphasin, &betasin, \
&alphacos, &betacos);
// Store power
window[i] = 0.5 * ( (alphasin*alphasin + betasin*betasin) + \
(alphacos*alphacos + betacos*betacos) );
}
}
}
else {
// Sum of all weights
double sumweights = arr_sum(weight, N);
// Make parallel loop over all test frequencies
#pragma omp parallel default(shared) private(alphasin, betasin, alphacos, betacos, ny)
{
#pragma omp for schedule(static)
for (i = 0; i < M; ++i) {
// Current frequency
ny = freq[i] * PI2micro;
// Calculate alpha and beta for cos and sin data
windowalpbetW(time, weight, datsin, datcos, N, ny, sumweights, \
&alphasin, &betasin, &alphacos, &betacos);
// Store power
window[i] = 0.5 * ( (alphasin*alphasin + betasin*betasin) + \
(alphacos*alphacos + betacos*betacos) );
}
}
}
// Done
free(datsin);
free(datcos);
}
// Calculate alpha and beta coefficients
void windowalpbet(double time[], double datasin[], double datacos[], size_t N,\
double ny, double *alphasin, double *betasin, double *alphacos,\
double *betacos)
{
// Auxiliary
double sn, cn, D;
// Sums: Individual terms
double ssin = 0;
double csin = 0;
double scos = 0;
double ccos = 0;
// Sums: Common terms
double cc = 0;
double sc = 0;
double ss;
// Loop over the time series
for (size_t i = 0; i < N; ++i) {
// Pre-calculate sin, cos of point
sn = sin(ny * time[i]);
cn = cos(ny * time[i]);
// Calculate sin, cos terms for both data series
ssin += datasin[i] * sn;
csin += datasin[i] * cn;
scos += datacos[i] * sn;
ccos += datacos[i] * cn;
// Calculate common squared and cross terms
cc += cn * cn;
sc += sn * cn;
}
// Calculate ss from cc
ss = N - cc;
// Calculate alpha and beta for both
D = ss*cc - sc*sc;
*alphasin = (ssin * cc - csin * sc)/D;
*betasin = (csin * ss - ssin * sc)/D;
*alphacos = (scos * cc - ccos * sc)/D;
*betacos = (ccos * ss - scos * sc)/D;
}
// Calculate alpha and beta coefficients WITH WEIGHTS
void windowalpbetW(double time[], double weight[], double datasin[],\
double datacos[], size_t N, double ny, double wsum,\
double *alphasin, double *betasin, double *alphacos,\
double *betacos)
{
// Auxiliary
double sn, cn, D;
// Sums: Individual terms
double ssin = 0;
double csin = 0;
double scos = 0;
double ccos = 0;
// Sums: Common terms
double cc = 0;
double sc = 0;
double ss;
// Loop over the time series
for (size_t i = 0; i < N; ++i) {
// Pre-calculate sin, cos of point
sn = sin(ny * time[i]);
cn = cos(ny * time[i]);
// Calculate sin, cos terms for both data series
// NOTE: The weights are already taken into account in the data!
ssin += weight[i] * datasin[i] * sn;
csin += weight[i] * datasin[i] * cn;
scos += weight[i] * datacos[i] * sn;
ccos += weight[i] * datacos[i] * cn;
// Calculate common squared and cross terms
cc += weight[i] * cn * cn;
sc += weight[i] * sn * cn;
}
// Calculate ss from cc
ss = wsum - cc;
// Calculate alpha and beta for both
D = ss*cc - sc*sc;
*alphasin = (ssin * cc - csin * sc)/D;
*betasin = (csin * ss - ssin * sc)/D;
*alphacos = (scos * cc - ccos * sc)/D;
*betacos = (ccos * ss - scos * sc)/D;
}
/* Calculate the sum of the spectral window
*
* Arguments:
* - `f0` : Desired frequency of the window function
* - `low`, `high`: Sampling limits
* - `rate` : Frequency step of sampling
* - `time` : Array of times (from the time series). In seconds!
* - `weight` : Statistical weights per data point (pass NULL if no weights).
* - `N` : Length of the time series
* - `useweight` : If != 0 weights will be used.
* - `quiet` : If != 0 no output will be displayed to console
*/
double windowsum(double f0, double low, double high, double rate, double time[],
double weight[], size_t N, int useweight, int quiet)
{
// Init
double result = 0;
// Calculate length of sampling vector
size_t M = arr_util_getstep(low, high, rate);
if ( quiet == 0 )
printf(" -- INFO: Number of frequencies in the window = %li\n", M);
// Initialise arrays and generate sampling frequencies
double* freq = malloc(M * sizeof(double));
double* window = malloc(M * sizeof(double));
arr_init_linspace(freq, low, rate, M);
// Calculate spectral window with or without weights
windowfunction(time, freq, weight, N, M, f0, window, useweight);
// Calculate the sum
result = arr_sum(window, M);
// Done
free(freq);
free(window);
return result;
}
|
GB_apply_op.c | //------------------------------------------------------------------------------
// GB_apply_op: typecast and apply a unary operator to an array
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// Cx = op ((xtype) Ax)
// Cx and Ax may be aliased.
// Compare with GB_transpose_op.c
#include "GB_apply.h"
#include "GB_binop.h"
#include "GB_unused.h"
#ifndef GBCOMPACT
#include "GB_unop__include.h"
#include "GB_binop__include.h"
#endif
void GB_apply_op // apply a unary operator, Cx = op ((xtype) Ax)
(
GB_void *Cx, // output array, of type op->ztype
const GrB_UnaryOp op1, // unary operator to apply
const GrB_BinaryOp op2, // binary operator to apply
const GxB_Scalar scalar, // scalar to bind to binary operator
bool binop_bind1st, // if true, binop(x,Ax) else binop(Ax,y)
const GB_void *Ax, // input array, of type Atype
const GrB_Type Atype, // type of Ax
const int64_t anz, // size of Ax and Cx
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
ASSERT (Cx != NULL) ;
ASSERT (Ax != NULL) ;
ASSERT (anz >= 0) ;
ASSERT (Atype != NULL) ;
ASSERT (op1 != NULL || op2 != NULL) ;
//--------------------------------------------------------------------------
// determine the number of threads to use
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
int nthreads = GB_nthreads (anz, chunk, nthreads_max) ;
//--------------------------------------------------------------------------
// apply the operator
//--------------------------------------------------------------------------
if (op1 != NULL)
{
//----------------------------------------------------------------------
// built-in unary operator
//----------------------------------------------------------------------
GrB_UnaryOp op = op1 ;
#ifndef GBCOMPACT
bool no_typecasting = (Atype == op->xtype)
|| (op->opcode == GB_IDENTITY_opcode)
|| (op->opcode == GB_ONE_opcode) ;
if (no_typecasting)
{
// only two workers are allowed to do their own typecasting from
// the Atype to the xtype of the operator: IDENTITY and ONE. For
// all others, the input type Atype must match the op->xtype of the
// operator. If this check isn't done, abs.fp32 with fc32 input
// will map to abs.fc32, based on the type of the input Ax, which is
// the wrong operator.
//------------------------------------------------------------------
// define the worker for the switch factory
//------------------------------------------------------------------
#define GB_unop_apply(op,zname,aname) \
GB_unop_apply_ ## op ## zname ## aname
#define GB_WORKER(op,zname,ztype,aname,atype) \
{ \
GrB_Info info = GB_unop_apply (op,zname,aname) \
((ztype *) Cx, (const atype *) Ax, anz, nthreads) ; \
if (info == GrB_SUCCESS) return ; \
} \
break ;
//------------------------------------------------------------------
// launch the switch factory
//------------------------------------------------------------------
#include "GB_unop_factory.c"
}
#endif
//----------------------------------------------------------------------
// generic worker: typecast and apply a unary operator
//----------------------------------------------------------------------
GB_BURBLE_N (anz, "generic ") ;
size_t asize = Atype->size ;
size_t zsize = op->ztype->size ;
size_t xsize = op->xtype->size ;
GB_cast_function
cast_A_to_X = GB_cast_factory (op->xtype->code, Atype->code) ;
GxB_unary_function fop = op->function ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
// xwork = (xtype) Ax [p]
GB_void xwork [GB_VLA(xsize)] ;
cast_A_to_X (xwork, Ax +(p*asize), asize) ;
// Cx [p] = fop (xwork)
fop (Cx +(p*zsize), xwork) ;
}
}
else
{
//----------------------------------------------------------------------
// built-in binary operator
//----------------------------------------------------------------------
GB_Opcode opcode = op2->opcode ;
GB_Type_code xcode, ycode, zcode ;
bool op_is_first = opcode == GB_FIRST_opcode ;
bool op_is_second = opcode == GB_SECOND_opcode ;
bool op_is_pair = opcode == GB_PAIR_opcode ;
size_t asize = Atype->size ;
size_t ssize = scalar->type->size ;
size_t zsize = op2->ztype->size ;
size_t xsize = op2->xtype->size ;
size_t ysize = op2->ytype->size ;
GB_Type_code scode = scalar->type->code ;
xcode = op2->xtype->code ;
ycode = op2->ytype->code ;
// typecast the scalar to the operator input
bool ignore_scalar = false ;
size_t ssize_cast ;
GB_Type_code scode_cast ;
if (binop_bind1st)
{
ssize_cast = xsize ;
scode_cast = xcode ;
ignore_scalar = op_is_second || op_is_pair ;
}
else
{
ssize_cast = ysize ;
scode_cast = ycode ;
ignore_scalar = op_is_first || op_is_pair ;
}
GB_void swork [GB_VLA(ssize_cast)] ;
GB_void *scalarx = (GB_void *) scalar->x ;
if (scode_cast != scode && !ignore_scalar)
{
// typecast the scalar to the operator input, in swork
GB_cast_function cast_s = GB_cast_factory (scode_cast, scode) ;
cast_s (swork, scalar->x, ssize) ;
scalarx = swork ;
}
#ifndef GBCOMPACT
if (binop_bind1st)
{
//------------------------------------------------------------------
// z = op(scalar,Ax)
//------------------------------------------------------------------
if (GB_binop_builtin (
op2->xtype, ignore_scalar,
Atype, op_is_first || op_is_pair,
op2, false, &opcode, &xcode, &ycode, &zcode))
{
//--------------------------------------------------------------
// define the worker for the switch factory
//--------------------------------------------------------------
#define GB_bind1st(op,xname) GB_bind1st_ ## op ## xname
#define GB_BINOP_WORKER(op,xname) \
{ \
if (GB_bind1st (op, xname) (Cx, scalarx, Ax, \
anz, nthreads) == GrB_SUCCESS) return ; \
} \
break ;
//--------------------------------------------------------------
// launch the switch factory
//--------------------------------------------------------------
#define GB_NO_SECOND
#define GB_NO_PAIR
#include "GB_binop_factory.c"
}
}
else
{
//------------------------------------------------------------------
// z = op(Ax,scalar)
//------------------------------------------------------------------
if (GB_binop_builtin (
Atype, op_is_second || op_is_pair,
op2->ytype, ignore_scalar,
op2, false, &opcode, &xcode, &ycode, &zcode))
{
//--------------------------------------------------------------
// define the worker for the switch factory
//--------------------------------------------------------------
#define GB_bind2nd(op,xname) GB_bind2nd_ ## op ## xname
#undef GB_BINOP_WORKER
#define GB_BINOP_WORKER(op,xname) \
{ \
if (GB_bind2nd (op, xname) (Cx, Ax, scalarx, \
anz, nthreads) == GrB_SUCCESS) return ; \
} \
break ;
//--------------------------------------------------------------
// launch the switch factory
//--------------------------------------------------------------
#define GB_NO_FIRST
#define GB_NO_PAIR
#include "GB_binop_factory.c"
}
}
#endif
//----------------------------------------------------------------------
// generic worker: typecast and apply a binary operator
//----------------------------------------------------------------------
GB_BURBLE_N (anz, "generic ") ;
GB_Type_code acode = Atype->code ;
GxB_binary_function fop = op2->function ;
if (binop_bind1st)
{
// Cx = op (scalar,Ax)
GB_cast_function cast_A_to_Y = GB_cast_factory (ycode, acode) ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
// ywork = (ytype) Ax [p]
GB_void ywork [GB_VLA(ysize)] ;
cast_A_to_Y (ywork, Ax +(p*asize), asize) ;
// Cx [p] = fop (xwork, ywork)
fop (Cx +(p*zsize), scalarx, ywork) ;
}
}
else
{
// Cx = op (Ax,scalar)
GB_cast_function cast_A_to_X = GB_cast_factory (xcode, acode) ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
// xwork = (xtype) Ax [p]
GB_void xwork [GB_VLA(xsize)] ;
cast_A_to_X (xwork, Ax +(p*asize), asize) ;
// Cx [p] = fop (xwork, ywork)
fop (Cx +(p*zsize), xwork, scalarx) ;
}
}
}
}
|
md5_bmark.c | /*
* MD5 Benchmark
* -------------
* File: md5_bmark.c
*
* This is the main file for the md5 benchmark kernel. This benchmark was
* written as part of the StarBENCH benchmark suite at TU Berlin. It performs
* MD5 computation on a number of self-generated input buffers in parallel,
* automatically measuring execution time.
*
* Copyright (C) 2011 Michael Andersch
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
#include <omp.h>
#include "md5.h"
#include "md5_bmark.h"
typedef struct timeval timer;
#define TIME(x) gettimeofday(&x, NULL)
/* Function declarations */
int initialize(md5bench_t* args);
int finalize(md5bench_t* args);
void run(md5bench_t* args);
void process(uint8_t* in, uint8_t* out, int bufsize);
void listInputs();
long timediff(timer* starttime, timer* finishtime);
// Input configurations
static data_t datasets[] = {
{64, 512, 0},
{64, 1024, 0},
{64, 2048, 0},
{64, 4096, 0},
{128, 1024*512, 1},
{128, 1024*1024, 1},
{128, 1024*2048, 1},
{128, 1024*4096, 1},
};
/*
* Function: initialize
* --------------------
* To initialize the benchmark parameters. Generates the input buffers from random data.
*/
int initialize(md5bench_t* args) {
int index = args->input_set;
if(index < 0 || index >= sizeof(datasets)/sizeof(datasets[0])) {
fprintf(stderr, "Invalid input set specified! Clamping to set 0\n");
index = 0;
}
args->numinputs = datasets[index].numbufs;
args->size = datasets[index].bufsize;
args->inputs = (uint8_t**)calloc(args->numinputs, sizeof(uint8_t*));
args->out = (uint8_t*)calloc(args->numinputs, DIGEST_SIZE);
if(args->inputs == NULL || args->out == NULL) {
fprintf(stderr, "Memory Allocation Error\n");
return -1;
}
//fprintf(stderr, "Reading input set: %d buffers, %d bytes per buffer\n", datasets[index].numbufs, datasets[index].bufsize);
// Now the input buffers need to be generated, for replicability, use same seed
srand(datasets[index].rseed);
for(int i = 0; i < args->numinputs; i++) {
args->inputs[i] = (uint8_t*)malloc(sizeof(uint8_t)*datasets[index].bufsize);
uint8_t* p = args->inputs[i];
if(p == NULL) {
fprintf(stderr, "Memory Allocation Error\n");
return -1;
}
for(int j = 0; j < datasets[index].bufsize; j++)
*p++ = rand() % 255;
}
return 0;
}
/*
* Function: process
* -----------------
* Processes one input buffer, delivering the digest into out.
*/
void process(uint8_t* in, uint8_t* out, int bufsize) {
MD5_CTX context;
uint8_t digest[16];
MD5_Init(&context);
MD5_Update(&context, in, bufsize);
MD5_Final(digest, &context);
memcpy(out, digest, DIGEST_SIZE);
}
/*
* Function: run
* --------------------
* Main benchmarking function. If called, processes buffers with MD5
* until no more buffers available. The resulting message digests
* are written into consecutive locations in the preallocated output
* buffer.
*/
void run(md5bench_t* args) {
for(int i = 0; i < args->iterations; i++) {
#pragma omp master
{
int buffers_to_process = args->numinputs;
int next = 0;
uint8_t** in = args->inputs;
uint8_t* out = args->out;
for (next = 0; next < buffers_to_process; next++) {
#pragma omp task
{
process(in[next], out+next*DIGEST_SIZE, args->size);
}
}
}
}
}
/*
* Function: finalize
* ------------------
* Cleans up memory used by the benchmark for input and output buffers.
*/
int finalize(md5bench_t* args) {
char buffer[64];
int offset = 0;
for(int i = 0; i < args->numinputs; i++) {
#ifdef DEBUG
sprintf(buffer, "Buffer %d has checksum ", i);
fwrite(buffer, sizeof(char), strlen(buffer)+1, stdout);
#endif
for(int j = 0; j < DIGEST_SIZE*2; j+=2) {
sprintf(buffer+j, "%x", args->out[DIGEST_SIZE*i+j/2] & 0xf);
sprintf(buffer+j+1, "%x", args->out[DIGEST_SIZE*i+j/2] & 0xf0);
}
buffer[32] = '\0';
#ifdef DEBUG
fwrite(buffer, sizeof(char), 32, stdout);
fputc('\n', stdout);
#else
printf("%s ", buffer);
#endif
}
#ifndef DEBUG
printf("\n");
#endif
if(args->inputs) {
for(int i = 0; i < args->numinputs; i++) {
if(args->inputs[i])
free(args->inputs[i]);
}
free(args->inputs);
}
if(args->out)
free(args->out);
return 0;
}
/*
* Function: timediff
* ------------------
* Compute the difference between timers starttime and finishtime in msecs.
*/
long timediff(timer* starttime, timer* finishtime)
{
long msec;
msec=(finishtime->tv_sec-starttime->tv_sec)*1000;
msec+=(finishtime->tv_usec-starttime->tv_usec)/1000;
return msec;
}
/** MAIN **/
int main(int argc, char** argv) {
timer b_start, b_end;
md5bench_t args;
//nt = number of threads
int nt;
//Receber parâmetros
scanf("%d", &nt);
scanf("%d", &args.input_set);
scanf("%d", &args.iterations);
args.outflag = 1;
// Parameter initialization
if(initialize(&args)) {
fprintf(stderr, "Initialization Error\n");
exit(EXIT_FAILURE);
}
TIME(b_start);
#pragma omp parallel num_threads(nt)
run(&args);
TIME(b_end);
// Free memory
if(finalize(&args)) {
fprintf(stderr, "Finalization Error\n");
exit(EXIT_FAILURE);
}
double b_time = (double)timediff(&b_start, &b_end)/1000;
printf("%.3f\n", b_time);
return 0;
}
|
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] = 16;
tile_size[1] = 16;
tile_size[2] = 8;
tile_size[3] = 32;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// 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<=floord(Nt-1,2);t1++) {
lbp=max(ceild(t1,2),ceild(4*t1-Nt+2,4));
ubp=min(floord(4*Nt+Nz-9,16),floord(8*t1+Nz+2,16));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(max(0,ceild(16*t2-Nz+5,8)),t1),2*t1-2*t2+1);t3<=min(min(min(floord(4*Nt+Ny-9,8),floord(8*t1+Ny+7,8)),floord(16*t2+Ny+3,8)),floord(16*t1-16*t2+Nz+Ny+5,8));t3++) {
for (t4=max(max(max(0,ceild(t1-3,4)),ceild(16*t2-Nz-19,32)),ceild(8*t3-Ny-19,32));t4<=min(min(min(min(floord(4*Nt+Nx-9,32),floord(8*t1+Nx+7,32)),floord(16*t2+Nx+3,32)),floord(8*t3+Nx-5,32)),floord(16*t1-16*t2+Nz+Nx+5,32));t4++) {
for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(32*t4-Nx+5,4)),2*t1),4*t1-4*t2+1);t5<=min(min(min(min(min(floord(16*t1-16*t2+Nz+10,4),2*t3),Nt-1),2*t1+3),4*t2+2),8*t4+6);t5++) {
for (t6=max(max(16*t2,4*t5+4),-16*t1+16*t2+8*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+8*t5),4*t5+Nz-5);t6++) {
for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) {
lbv=max(32*t4,4*t5+4);
ubv=min(32*t4+31,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;
}
|
test.c |
#include <stdio.h>
#include <omp.h>
#include "../utilities/check.h"
#include "../utilities/utilities.h"
#define TRIALS (1)
#define N (992)
#define INIT() INIT_LOOP(N, {C[i] = 1; D[i] = i; E[i] = -i;})
#define ZERO(X) ZERO_ARRAY(N, X)
int check_results(double* A){
for (int i = 0 ; i < N ; i++){
if (A[i] != TRIALS){
printf("Error at %d, h = %lf, d = %lf\n", i, (double) TRIALS, A[i]);
return 0;
}
}
return 1;
}
int check_results_priv(double *A, double *B){
for(int i = 0 ; i < N ; i++) {
if (A[i] != TRIALS*3) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) TRIALS*2, A[i]);
return 0;
}
if (B[i] != TRIALS*7) {
printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) TRIALS*3, B[i]);
return 0;
}
}
return 1;
}
#define CODE() \
ZERO(A); \
success = 0; \
for (int t = 0 ; t < TRIALS ; t++) { \
_Pragma("omp target") \
_Pragma("omp teams distribute simd CLAUSES") \
for (int i = 0 ; i < N ; i++){ \
A[i] += C[i]; \
} \
} \
success += check_results(A); \
if (success == expected) \
printf("Succeeded\n");
#define CODE_PRIV() \
ZERO(A); \
ZERO(B); \
p = 2.0; \
q = 4.0; \
success = 0; \
for (int t = 0 ; t < TRIALS ; t++) { \
_Pragma("omp target") \
_Pragma("omp teams distribute simd CLAUSES") \
for (int i = 0 ; i < N ; i++){ \
p = 3; \
q = 7; \
A[i] += p; \
B[i] += q; \
} \
} \
success += check_results_priv(A, B); \
if (success == expected) \
printf("Succeeded\n");
int main(void) {
check_offloading();
double A[N], B[N], C[N], D[N], E[N];
int fail = 0;
int expected = 1;
int success = 0;
int chunkSize;
double p = 2.0, q = 4.0;
int nte, tl, blockSize;
INIT();
// **************************
// Series 1: no dist_schedule
// **************************
//
// Test: #iterations == #teams
//
printf("iterations = teams\n");
#define CLAUSES num_teams(992)
CODE()
#undef CLAUSES
printf("iterations > teams\n");
#define CLAUSES num_teams(256)
CODE()
#undef CLAUSES
printf("iterations < teams\n");
#define CLAUSES num_teams(1024)
CODE()
#undef CLAUSES
printf("num_teams(512) dist_schedule(static,1)\n");
#define CLAUSES num_teams(512) dist_schedule(static, 1)
CODE()
#undef CLAUSES
printf("num_teams(512) dist_schedule(static,512)\n");
#define CLAUSES num_teams(512) dist_schedule(static, 512)
CODE()
#undef CLAUSES
printf("num_teams(512) dist_schedule(static, chunkSize)\n");
chunkSize = N / 10;
#define CLAUSES num_teams(512) dist_schedule(static, chunkSize)
CODE()
#undef CLAUSES
printf("num_teams(1024) dist_schedule(static, chunkSize)\n");
chunkSize = N / 10;
#define CLAUSES num_teams(1024) dist_schedule(static, chunkSize)
CODE()
#undef CLAUSES
printf("num_teams(1024) dist_schedule(static, 1)\n");
#define CLAUSES num_teams(1024) dist_schedule(static, 1)
CODE()
#undef CLAUSES
printf("num_teams(3) dist_schedule(static, 1)\n");
#define CLAUSES num_teams(3) dist_schedule(static, 1)
CODE()
#undef CLAUSES
printf("num_teams(3) dist_schedule(static, 3)\n");
#define CLAUSES num_teams(3) dist_schedule(static, 3)
CODE()
#undef CLAUSES
printf("num_teams(10) dist_schedule(static, 99)\n");
#define CLAUSES num_teams(10) dist_schedule(static, 99)
CODE()
#undef CLAUSES
printf("num_teams(256) dist_schedule(static, 992)\n");
#define CLAUSES num_teams(256) dist_schedule(static, 992)
CODE()
#undef CLAUSES
#if 0
printf("num_teams(256) private(p,q)\n");
#define CLAUSES num_teams(256) private(p,q)
CODE_PRIV()
#undef CLAUSES
#endif
//
// Test: firstprivate
//
#if 0
printf("num_teams(64) firstprivate(p, q)\n");
ZERO(A); ZERO(B);
p = 2.0, q = 4.0;
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target // implicit firstprivate for p and q, their initial values being 2 and 4 for each target invocation
#pragma omp teams distribute simd num_teams(64) firstprivate(p, q)
for(int i = 0 ; i < 128 ; i++) { // 2 iterations for each team
p += 3.0; // p and q are firstprivate to the team, and as such incremented twice (2 iterations per team)
q += 7.0;
A[i] += p;
B[i] += q;
}
}
for(int i = 0 ; i < 128 ; i++) {
if (i % 2 == 0) {
if (A[i] != (2.0+3.0)*TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]);
fail = 1;
}
if (B[i] != (4.0+7.0)*TRIALS) {
printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) (4.0+7.0)*TRIALS, B[i]);
fail = 1;
}
} else {
if (A[i] != (2.0+3.0*2)*TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0*2)*TRIALS, A[i]);
fail = 1;
}
if (B[i] != (4.0+7.0*2)*TRIALS) {
printf("Error at B[%d], h = %lf, d = %lf\n", i, (double) (4.0+7.0*2)*TRIALS, B[i]);
fail = 1;
}
}
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
#endif
//
// Test: lastprivate
//
#if 0
printf("num_teams(10) lastprivate(lastpriv)\n");
success = 0;
int lastpriv = -1;
#pragma omp target map(tofrom:lastpriv)
#pragma omp teams distribute simd num_teams(10) lastprivate(lastpriv)
for(int i = 0 ; i < omp_get_num_teams() ; i++)
lastpriv = omp_get_team_num();
if(lastpriv != 9) {
printf("lastpriv value is %d and should have been %d\n", lastpriv, 9);
fail = 1;
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
#endif
// // ***************************
// // Series 4: with parallel for
// // ***************************
//
// Test: simple blocking loop
//
printf("num_teams(nte) thread_limit(tl) with parallel for innermost\n");
success = 0;
ZERO(A); ZERO(B);
nte = 32;
tl = 64;
blockSize = tl;
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target
#pragma omp teams distribute simd num_teams(nte) thread_limit(tl)
for(int j = 0 ; j < 256 ; j += blockSize) {
for(int i = j ; i < j+blockSize; i++) {
A[i] += B[i] + C[i];
}
}
}
for(int i = 0 ; i < 256 ; i++) {
if (A[i] != TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]);
fail = 1;
}
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
//
// Test: blocking loop where upper bound is not a multiple of tl*nte
//
printf("num_teams(nte) thread_limit(tl) with parallel for innermost\n");
success = 0;
ZERO(A); ZERO(B);
nte = 32;
tl = 64;
blockSize = tl;
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target
#pragma omp teams distribute simd num_teams(nte) thread_limit(tl)
for(int j = 0 ; j < 510 ; j += blockSize) {
int ub = (j+blockSize < 510) ? (j+blockSize) : 512;
for(int i = j ; i < ub; i++) {
A[i] += B[i] + C[i];
}
}
}
for(int i = 0 ; i < 256 ; i++) {
if (A[i] != TRIALS) {
printf("Error at A[%d], h = %lf, d = %lf\n", i, (double) (2.0+3.0)*TRIALS, A[i]);
fail = 1;
}
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
// **************************
// Series 5: collapse
// **************************
//
// Test: 2 loops
//
printf("num_teams(512) collapse(2)\n");
success = 0;
double * S = (double *) malloc(N*N*sizeof(double));
double * T = (double *) malloc(N*N*sizeof(double));
double * U = (double *) malloc(N*N*sizeof(double));
for (int i = 0 ; i < N ; i++)
for (int j = 0 ; j < N ; j++)
{
S[i*N+j] = 0.0;
T[i*N+j] = 1.0;
U[i*N+j] = 2.0;
}
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target map(tofrom:S[:N*N]), map(to:T[:N*N],U[:N*N])
#pragma omp teams distribute simd num_teams(512) collapse(2)
for (int i = 0 ; i < N ; i++)
for (int j = 0 ; j < N ; j++)
S[i*N+j] += T[i*N+j] + U[i*N+j]; // += 3 at each t
}
for (int i = 0 ; i < N ; i++)
for (int j = 0 ; j < N ; j++)
if (S[i*N+j] != TRIALS*3.0) {
printf("Error at (%d,%d), h = %lf, d = %lf\n", i, j, (double) TRIALS*3.0, S[i*N+j]);
fail = 1;
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
//
// Test: 3 loops
//
printf("num_teams(512) collapse(3)\n");
success = 0;
int M = N/8;
double * V = (double *) malloc(M*M*M*sizeof(double));
double * Z = (double *) malloc(M*M*M*sizeof(double));
for (int i = 0 ; i < M ; i++)
for (int j = 0 ; j < M ; j++)
for (int k = 0 ; k < M ; k++)
{
V[i*M*M+j*M+k] = 2.0;
Z[i*M*M+j*M+k] = 3.0;
}
for (int t = 0 ; t < TRIALS ; t++) {
#pragma omp target map(tofrom:V[:M*M*M]), map(to:Z[:M*M*M])
#pragma omp teams distribute simd num_teams(512) collapse(3)
for (int i = 0 ; i < M ; i++)
for (int j = 0 ; j < M ; j++)
for (int k = 0 ; k < M ; k++)
V[i*M*M+j*M+k] += Z[i*M*M+j*M+k]; // += 3 at each t
}
for (int i = 0 ; i < M ; i++)
for (int j = 0 ; j < M ; j++)
for (int k = 0 ; k < M ; k++)
if (V[i*M*M+j*M+k] != 2.0+TRIALS*3.0) {
printf("Error at (%d,%d), h = %lf, d = %lf\n", i, j, (double) TRIALS*3.0, V[i*M*M+j*M+k]);
fail = 1;
}
if(fail) printf("Failed\n");
else printf("Succeeded\n");
return 0;
}
|
GemmNeon.h | // Copyright 2019 MAI. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <arm_neon.h>
namespace MAI {
namespace Op {
namespace CPU {
namespace NEON {
#define MAI_VFMAQ_LANEQ_F32_4(OValue, AValue) \
OValue = vfmaq_laneq_f32(OValue, b0Value, AValue, 0); \
OValue = vfmaq_laneq_f32(OValue, b1Value, AValue, 1); \
OValue = vfmaq_laneq_f32(OValue, b2Value, AValue, 2); \
OValue = vfmaq_laneq_f32(OValue, b3Value, AValue, 3); \
#define MAI_VFMAQ_LANEQ_F32_8(OValue, A0Value, A1Value) \
OValue = vfmaq_laneq_f32(OValue, b0Value, A0Value, 0); \
OValue = vfmaq_laneq_f32(OValue, b1Value, A0Value, 1); \
OValue = vfmaq_laneq_f32(OValue, b2Value, A0Value, 2); \
OValue = vfmaq_laneq_f32(OValue, b3Value, A0Value, 3); \
OValue = vfmaq_laneq_f32(OValue, b4Value, A1Value, 0); \
OValue = vfmaq_laneq_f32(OValue, b5Value, A1Value, 1); \
OValue = vfmaq_laneq_f32(OValue, b6Value, A1Value, 2); \
OValue = vfmaq_laneq_f32(OValue, b7Value, A1Value, 3); \
template<typename T, bool transpose_a, bool transpose_b>
struct Gemm;
template<>
struct Gemm<float, false, false> {
static void gemm_tile_444(const float* aPtr, const float* bPtr, float* oPtr, int M, int N, int K) {
float32x4_t o0Value = vld1q_f32(oPtr);
float32x4_t o1Value = vld1q_f32(oPtr + N);
float32x4_t o2Value = vld1q_f32(oPtr + N * 2);
float32x4_t o3Value = vld1q_f32(oPtr + N * 3);
float32x4_t a0Value = vld1q_f32(aPtr);
float32x4_t a1Value = vld1q_f32(aPtr + K);
float32x4_t a2Value = vld1q_f32(aPtr + K * 2);
float32x4_t a3Value = vld1q_f32(aPtr + K * 3);
float32x4_t b0Value = vld1q_f32(bPtr);
float32x4_t b1Value = vld1q_f32(bPtr + N);
float32x4_t b2Value = vld1q_f32(bPtr + N * 2);
float32x4_t b3Value = vld1q_f32(bPtr + N * 3);
o0Value = vfmaq_laneq_f32(o0Value, b0Value, a0Value, 0);
o0Value = vfmaq_laneq_f32(o0Value, b1Value, a0Value, 1);
o0Value = vfmaq_laneq_f32(o0Value, b2Value, a0Value, 2);
o0Value = vfmaq_laneq_f32(o0Value, b3Value, a0Value, 3);
o1Value = vfmaq_laneq_f32(o1Value, b0Value, a1Value, 0);
o1Value = vfmaq_laneq_f32(o1Value, b1Value, a1Value, 1);
o1Value = vfmaq_laneq_f32(o1Value, b2Value, a1Value, 2);
o1Value = vfmaq_laneq_f32(o1Value, b3Value, a1Value, 3);
o2Value = vfmaq_laneq_f32(o2Value, b0Value, a2Value, 0);
o2Value = vfmaq_laneq_f32(o2Value, b1Value, a2Value, 1);
o2Value = vfmaq_laneq_f32(o2Value, b2Value, a2Value, 2);
o2Value = vfmaq_laneq_f32(o2Value, b3Value, a2Value, 3);
o3Value = vfmaq_laneq_f32(o3Value, b0Value, a3Value, 0);
o3Value = vfmaq_laneq_f32(o3Value, b1Value, a3Value, 1);
o3Value = vfmaq_laneq_f32(o3Value, b2Value, a3Value, 2);
o3Value = vfmaq_laneq_f32(o3Value, b3Value, a3Value, 3);
vst1q_f32(oPtr, o0Value);
vst1q_f32(oPtr + N, o1Value);
vst1q_f32(oPtr + N * 2, o2Value);
vst1q_f32(oPtr + N * 3, o3Value);
}
// (M, K, N) ==> (8, 8, 4)
static void gemm_tile_884(const float* aPtr, const float* bPtr, float* oPtr, int M, int N, int K) {
float32x4_t o0Value = vld1q_f32(oPtr);
float32x4_t o1Value = vld1q_f32(oPtr + N);
float32x4_t o2Value = vld1q_f32(oPtr + N * 2);
float32x4_t o3Value = vld1q_f32(oPtr + N * 3);
float32x4_t o4Value = vld1q_f32(oPtr + N * 4);
float32x4_t o5Value = vld1q_f32(oPtr + N * 5);
float32x4_t o6Value = vld1q_f32(oPtr + N * 6);
float32x4_t o7Value = vld1q_f32(oPtr + N * 7);
float32x4_t a0Value = vld1q_f32(aPtr);
float32x4_t a1Value = vld1q_f32(aPtr + 4);
float32x4_t a2Value = vld1q_f32(aPtr + K);
float32x4_t a3Value = vld1q_f32(aPtr + K + 4);
float32x4_t a4Value = vld1q_f32(aPtr + K * 2);
float32x4_t a5Value = vld1q_f32(aPtr + K * 2 + 4);
float32x4_t a6Value = vld1q_f32(aPtr + K * 3);
float32x4_t a7Value = vld1q_f32(aPtr + K * 3 + 4);
float32x4_t a8Value = vld1q_f32(aPtr + K * 4);
float32x4_t a9Value = vld1q_f32(aPtr + K * 4 + 4);
float32x4_t a10Value = vld1q_f32(aPtr + K * 5);
float32x4_t a11Value = vld1q_f32(aPtr + K * 5 + 4);
float32x4_t a12Value = vld1q_f32(aPtr + K * 6);
float32x4_t a13Value = vld1q_f32(aPtr + K * 6 + 4);
float32x4_t a14Value = vld1q_f32(aPtr + K * 7);
float32x4_t a15Value = vld1q_f32(aPtr + K * 7 + 4);
float32x4_t b0Value = vld1q_f32(bPtr);
float32x4_t b1Value = vld1q_f32(bPtr + N);
float32x4_t b2Value = vld1q_f32(bPtr + N * 2);
float32x4_t b3Value = vld1q_f32(bPtr + N * 3);
float32x4_t b4Value = vld1q_f32(bPtr + N * 4);
float32x4_t b5Value = vld1q_f32(bPtr + N * 5);
float32x4_t b6Value = vld1q_f32(bPtr + N * 6);
float32x4_t b7Value = vld1q_f32(bPtr + N * 7);
MAI_VFMAQ_LANEQ_F32_8(o0Value, a0Value, a1Value);
MAI_VFMAQ_LANEQ_F32_8(o1Value, a2Value, a3Value);
MAI_VFMAQ_LANEQ_F32_8(o2Value, a4Value, a5Value);
MAI_VFMAQ_LANEQ_F32_8(o3Value, a6Value, a7Value);
MAI_VFMAQ_LANEQ_F32_8(o4Value, a8Value, a9Value);
MAI_VFMAQ_LANEQ_F32_8(o5Value, a10Value, a11Value);
MAI_VFMAQ_LANEQ_F32_8(o6Value, a12Value, a13Value);
MAI_VFMAQ_LANEQ_F32_8(o7Value, a14Value, a15Value);
vst1q_f32(oPtr, o0Value);
vst1q_f32(oPtr + N, o1Value);
vst1q_f32(oPtr + N * 2, o2Value);
vst1q_f32(oPtr + N * 3, o3Value);
vst1q_f32(oPtr + N * 4, o4Value);
vst1q_f32(oPtr + N * 5, o5Value);
vst1q_f32(oPtr + N * 6, o6Value);
vst1q_f32(oPtr + N * 7, o7Value);
}
static void gemm_random_block(const float* aPtr, const float* bPtr, float* oPtr,
int blockM, int blockN, int blockK, int M, int N, int K) {
for (int m = 0; m < blockM; ++m) {
for (int k = 0; k < blockK; ++k) {
for (int n = 0; n < blockN; ++n) {
oPtr[m * N + n] += aPtr[m * K + k] * bPtr[k * N + n];
}
}
}
}
static void pack(const float* bPtr, float* packedBPtr, int blockM, int blockN, int stride, int tile) {
for(int i = 0; i < blockN; i += tile) {
for (int j = 0; j < blockM; ++j) {
memcpy(packedBPtr + i * blockM + j * tile, bPtr + j * stride + i, sizeof(float) * tile);
}
}
}
template<int MAX_BLOCKM, int MAX_BLOCKK, int MAX_BLOCKN>
static void gemm_tile(const float* aPtr, const float* bPtr, float* oPtr,
const int blockM, const int blockN, const int blockK, int M, int N, int K) {
const int tileMSize = 8;
const int tileKSize = 8;
const int tileNSize = 4;
#if !defined(MAI_GEMM_NO_CACHE)
float packedB[MAX_BLOCKK * MAX_BLOCKN];
#endif
#if !defined(MAI_GEMM_NO_CACHE) && !defined(MAI_GEMM_CACHE_B)
float packedA[8 * 8];
#endif
#ifdef MAI_GEMM_CACHE_ABO
float packedO[8 * MAX_BLOCKN] = {0};
#endif
int bM, bK, bN;
for (bM = 0; bM < blockM - tileMSize + 1; bM += tileMSize) {
for (bK = 0; bK < blockK - tileKSize + 1; bK += tileKSize) {
#if !defined(MAI_GEMM_NO_CACHE) && !defined(MAI_GEMM_CACHE_B)
pack(aPtr + bM * K + bK, packedA, tileMSize, tileKSize, K, tileKSize);
#endif
#if !defined(MAI_GEMM_NO_CACHE)
if (bM == 0) {
pack(bPtr + bK * N, packedB + bK * blockN, tileKSize, blockN, N, tileNSize);
}
#endif
for (bN = 0; bN < blockN - tileNSize + 1; bN += tileNSize) {
#if defined(MAI_GEMM_NO_CACHE)
gemm_tile_884(aPtr + bM * K + bK,
bPtr + bK * N + bN,
oPtr + bM * N + bN, M, N, K);
#elif defined(MAI_GEMM_CACHE_B)
gemm_tile_884_b_morden_84(aPtr + bM * K + bK,
packedB + bK * blockN + bN * tileKSize,
oPtr + bM * N + bN, M, N, K);
#elif defined(MAI_GEMM_CACHE_ABO)
gemm_tile_884_a_morden_88_b_morden_84_o_sequential(packedA,
packedB + bK * blockN + bN * tileKSize,
packedO + bN * tileMSize, M, N, K);
#else
gemm_tile_884_a_morden_88_b_morden_84(packedA,
packedB + bK * blockN + bN * tileKSize,
oPtr + bM * N + bN, M, N, K);
#endif
}
if (bN < blockN) {
gemm_random_block(aPtr + bM * K + bK, bPtr + bK * N + bN, oPtr + bM * N + bN,
tileMSize, blockN - bN, tileKSize, M, N, K);
}
}
#if defined(MAI_GEMM_CACHE_ABO)
//write output cache into oPtr
for (int i = 0; i < blockN - tileNSize + 1; i += tileNSize) {
for (int j = 0; j < tileMSize; ++j) {
float32x4_t oValue = vld1q_f32(oPtr + bM * N + j * N + i);
float32x4_t packedValue = vld1q_f32(packedO + i * tileMSize + j * tileNSize);
oValue = vaddq_f32(oValue, packedValue);
vst1q_f32(oPtr + bM * N + j * N + i, oValue);
}
}
memset(packedO, 0, sizeof(float) * 8 * MAX_BLOCKN);
#endif
if (bK < blockK) {
gemm_random_block(aPtr + bM * K + bK, bPtr + bK * N, oPtr + bM * N,
tileMSize, blockN, blockK - bK, M, N, K);
}
}
if (bM < blockM) {//remaining
gemm_random_block(aPtr + bM * K, bPtr, oPtr + bM * N,
blockM - bM, blockN, blockK, M, N, K);
}
}
static void gemm(const float* aPtr, const float* bPtr, const float* cPtr, float* oPtr,
const int M, const int N, const int K) {
//ALOGI("Neon float Gemm2");
const int tileSize = 64;
const int mBlockSize = M / tileSize + (M % tileSize == 0 ? 0 : 1);
const int nBlockSize = N / tileSize + (N % tileSize == 0 ? 0 : 1);
const int kBlockSize = K / tileSize + (K % tileSize == 0 ? 0 : 1);
int remainSize[3] = {M % tileSize, N % tileSize, K % tileSize};
memset(oPtr, 0, M * N * sizeof(float));
#pragma omp parallel for schedule(dynamic) collapse(2)
for (int m = 0; m < mBlockSize; m++) {
for (int n = 0; n < nBlockSize; n++) {
for (int k = 0; k < kBlockSize; k++) {
int mTileSize = (m == mBlockSize - 1 && remainSize[0] > 0) ? remainSize[0] : tileSize;
int nTileSize = (n == nBlockSize - 1 && remainSize[1] > 0) ? remainSize[1] : tileSize;
int kTileSize = (k == kBlockSize - 1 && remainSize[2] > 0) ? remainSize[2] : tileSize;
gemm_tile<tileSize, tileSize, tileSize>(aPtr + m * tileSize * K + k * tileSize,
bPtr + k * tileSize * N + n * tileSize,
oPtr + m * tileSize * N + n * tileSize,
mTileSize, nTileSize, kTileSize, M, N, K);
}
}
}
}
static void gemm_tile_884_a_morden_88_b_morden_84(const float* aPtr, const float* bPtr, float* oPtr, int M, int N, int K) {
float32x4_t o0Value = vld1q_f32(oPtr);
float32x4_t o1Value = vld1q_f32(oPtr + N);
float32x4_t o2Value = vld1q_f32(oPtr + N * 2);
float32x4_t o3Value = vld1q_f32(oPtr + N * 3);
float32x4_t o4Value = vld1q_f32(oPtr + N * 4);
float32x4_t o5Value = vld1q_f32(oPtr + N * 5);
float32x4_t o6Value = vld1q_f32(oPtr + N * 6);
float32x4_t o7Value = vld1q_f32(oPtr + N * 7);
float32x4_t a0Value = vld1q_f32(aPtr);
float32x4_t a1Value = vld1q_f32(aPtr + 4);
float32x4_t a2Value = vld1q_f32(aPtr + 4 * 2);
float32x4_t a3Value = vld1q_f32(aPtr + 4 * 3);
float32x4_t a4Value = vld1q_f32(aPtr + 4 * 4);
float32x4_t a5Value = vld1q_f32(aPtr + 4 * 5);
float32x4_t a6Value = vld1q_f32(aPtr + 4 * 6);
float32x4_t a7Value = vld1q_f32(aPtr + 4 * 7);
float32x4_t a8Value = vld1q_f32(aPtr + 4 * 8);
float32x4_t a9Value = vld1q_f32(aPtr + 4 * 9);
float32x4_t a10Value = vld1q_f32(aPtr + 4 * 10);
float32x4_t a11Value = vld1q_f32(aPtr + 4 * 11);
float32x4_t a12Value = vld1q_f32(aPtr + 4 * 12);
float32x4_t a13Value = vld1q_f32(aPtr + 4 * 13);
float32x4_t a14Value = vld1q_f32(aPtr + 4 * 14);
float32x4_t a15Value = vld1q_f32(aPtr + 4 * 15);
float32x4_t b0Value = vld1q_f32(bPtr);
float32x4_t b1Value = vld1q_f32(bPtr + 4);
float32x4_t b2Value = vld1q_f32(bPtr + 4 * 2);
float32x4_t b3Value = vld1q_f32(bPtr + 4 * 3);
float32x4_t b4Value = vld1q_f32(bPtr + 4 * 4);
float32x4_t b5Value = vld1q_f32(bPtr + 4 * 5);
float32x4_t b6Value = vld1q_f32(bPtr + 4 * 6);
float32x4_t b7Value = vld1q_f32(bPtr + 4 * 7);
MAI_VFMAQ_LANEQ_F32_8(o0Value, a0Value, a1Value);
MAI_VFMAQ_LANEQ_F32_8(o1Value, a2Value, a3Value);
MAI_VFMAQ_LANEQ_F32_8(o2Value, a4Value, a5Value);
MAI_VFMAQ_LANEQ_F32_8(o3Value, a6Value, a7Value);
MAI_VFMAQ_LANEQ_F32_8(o4Value, a8Value, a9Value);
MAI_VFMAQ_LANEQ_F32_8(o5Value, a10Value, a11Value);
MAI_VFMAQ_LANEQ_F32_8(o6Value, a12Value, a13Value);
MAI_VFMAQ_LANEQ_F32_8(o7Value, a14Value, a15Value);
vst1q_f32(oPtr, o0Value);
vst1q_f32(oPtr + N, o1Value);
vst1q_f32(oPtr + N * 2, o2Value);
vst1q_f32(oPtr + N * 3, o3Value);
vst1q_f32(oPtr + N * 4, o4Value);
vst1q_f32(oPtr + N * 5, o5Value);
vst1q_f32(oPtr + N * 6, o6Value);
vst1q_f32(oPtr + N * 7, o7Value);
}
static void gemm_tile_884_a_morden_88_b_morden_84_o_sequential(const float* aPtr, const float* bPtr, float* oPtr, int M, int N, int K) {
float32x4_t o0Value = vld1q_f32(oPtr);
float32x4_t o1Value = vld1q_f32(oPtr + 4);
float32x4_t o2Value = vld1q_f32(oPtr + 4 * 2);
float32x4_t o3Value = vld1q_f32(oPtr + 4 * 3);
float32x4_t o4Value = vld1q_f32(oPtr + 4 * 4);
float32x4_t o5Value = vld1q_f32(oPtr + 4 * 5);
float32x4_t o6Value = vld1q_f32(oPtr + 4 * 6);
float32x4_t o7Value = vld1q_f32(oPtr + 4 * 7);
float32x4_t a0Value = vld1q_f32(aPtr);
float32x4_t a1Value = vld1q_f32(aPtr + 4);
float32x4_t a2Value = vld1q_f32(aPtr + 4 * 2);
float32x4_t a3Value = vld1q_f32(aPtr + 4 * 3);
float32x4_t a4Value = vld1q_f32(aPtr + 4 * 4);
float32x4_t a5Value = vld1q_f32(aPtr + 4 * 5);
float32x4_t a6Value = vld1q_f32(aPtr + 4 * 6);
float32x4_t a7Value = vld1q_f32(aPtr + 4 * 7);
float32x4_t a8Value = vld1q_f32(aPtr + 4 * 8);
float32x4_t a9Value = vld1q_f32(aPtr + 4 * 9);
float32x4_t a10Value = vld1q_f32(aPtr + 4 * 10);
float32x4_t a11Value = vld1q_f32(aPtr + 4 * 11);
float32x4_t a12Value = vld1q_f32(aPtr + 4 * 12);
float32x4_t a13Value = vld1q_f32(aPtr + 4 * 13);
float32x4_t a14Value = vld1q_f32(aPtr + 4 * 14);
float32x4_t a15Value = vld1q_f32(aPtr + 4 * 15);
float32x4_t b0Value = vld1q_f32(bPtr);
float32x4_t b1Value = vld1q_f32(bPtr + 4);
float32x4_t b2Value = vld1q_f32(bPtr + 4 * 2);
float32x4_t b3Value = vld1q_f32(bPtr + 4 * 3);
float32x4_t b4Value = vld1q_f32(bPtr + 4 * 4);
float32x4_t b5Value = vld1q_f32(bPtr + 4 * 5);
float32x4_t b6Value = vld1q_f32(bPtr + 4 * 6);
float32x4_t b7Value = vld1q_f32(bPtr + 4 * 7);
MAI_VFMAQ_LANEQ_F32_8(o0Value, a0Value, a1Value);
MAI_VFMAQ_LANEQ_F32_8(o1Value, a2Value, a3Value);
MAI_VFMAQ_LANEQ_F32_8(o2Value, a4Value, a5Value);
MAI_VFMAQ_LANEQ_F32_8(o3Value, a6Value, a7Value);
MAI_VFMAQ_LANEQ_F32_8(o4Value, a8Value, a9Value);
MAI_VFMAQ_LANEQ_F32_8(o5Value, a10Value, a11Value);
MAI_VFMAQ_LANEQ_F32_8(o6Value, a12Value, a13Value);
MAI_VFMAQ_LANEQ_F32_8(o7Value, a14Value, a15Value);
vst1q_f32(oPtr, o0Value);
vst1q_f32(oPtr + 4, o1Value);
vst1q_f32(oPtr + 4 * 2, o2Value);
vst1q_f32(oPtr + 4 * 3, o3Value);
vst1q_f32(oPtr + 4 * 4, o4Value);
vst1q_f32(oPtr + 4 * 5, o5Value);
vst1q_f32(oPtr + 4 * 6, o6Value);
vst1q_f32(oPtr + 4 * 7, o7Value);
}
static void gemm_tile_884_b_morden_84(const float* aPtr, const float* bPtr, float* oPtr, int M, int N, int K) {
float32x4_t o0Value = vld1q_f32(oPtr);
float32x4_t o1Value = vld1q_f32(oPtr + N);
float32x4_t o2Value = vld1q_f32(oPtr + N * 2);
float32x4_t o3Value = vld1q_f32(oPtr + N * 3);
float32x4_t o4Value = vld1q_f32(oPtr + N * 4);
float32x4_t o5Value = vld1q_f32(oPtr + N * 5);
float32x4_t o6Value = vld1q_f32(oPtr + N * 6);
float32x4_t o7Value = vld1q_f32(oPtr + N * 7);
float32x4_t a0Value = vld1q_f32(aPtr);
float32x4_t a1Value = vld1q_f32(aPtr + 4);
float32x4_t a2Value = vld1q_f32(aPtr + K);
float32x4_t a3Value = vld1q_f32(aPtr + K + 4);
float32x4_t a4Value = vld1q_f32(aPtr + K * 2);
float32x4_t a5Value = vld1q_f32(aPtr + K * 2 + 4);
float32x4_t a6Value = vld1q_f32(aPtr + K * 3);
float32x4_t a7Value = vld1q_f32(aPtr + K * 3 + 4);
float32x4_t a8Value = vld1q_f32(aPtr + K * 4);
float32x4_t a9Value = vld1q_f32(aPtr + K * 4 + 4);
float32x4_t a10Value = vld1q_f32(aPtr + K * 5);
float32x4_t a11Value = vld1q_f32(aPtr + K * 5 + 4);
float32x4_t a12Value = vld1q_f32(aPtr + K * 6);
float32x4_t a13Value = vld1q_f32(aPtr + K * 6 + 4);
float32x4_t a14Value = vld1q_f32(aPtr + K * 7);
float32x4_t a15Value = vld1q_f32(aPtr + K * 7 + 4);
float32x4_t b0Value = vld1q_f32(bPtr);
float32x4_t b1Value = vld1q_f32(bPtr + 4);
float32x4_t b2Value = vld1q_f32(bPtr + 4 * 2);
float32x4_t b3Value = vld1q_f32(bPtr + 4 * 3);
float32x4_t b4Value = vld1q_f32(bPtr + 4 * 4);
float32x4_t b5Value = vld1q_f32(bPtr + 4 * 5);
float32x4_t b6Value = vld1q_f32(bPtr + 4 * 6);
float32x4_t b7Value = vld1q_f32(bPtr + 4 * 7);
MAI_VFMAQ_LANEQ_F32_8(o0Value, a0Value, a1Value);
MAI_VFMAQ_LANEQ_F32_8(o1Value, a2Value, a3Value);
MAI_VFMAQ_LANEQ_F32_8(o2Value, a4Value, a5Value);
MAI_VFMAQ_LANEQ_F32_8(o3Value, a6Value, a7Value);
MAI_VFMAQ_LANEQ_F32_8(o4Value, a8Value, a9Value);
MAI_VFMAQ_LANEQ_F32_8(o5Value, a10Value, a11Value);
MAI_VFMAQ_LANEQ_F32_8(o6Value, a12Value, a13Value);
MAI_VFMAQ_LANEQ_F32_8(o7Value, a14Value, a15Value);
vst1q_f32(oPtr, o0Value);
vst1q_f32(oPtr + N, o1Value);
vst1q_f32(oPtr + N * 2, o2Value);
vst1q_f32(oPtr + N * 3, o3Value);
vst1q_f32(oPtr + N * 4, o4Value);
vst1q_f32(oPtr + N * 5, o5Value);
vst1q_f32(oPtr + N * 6, o6Value);
vst1q_f32(oPtr + N * 7, o7Value);
}
static void gemm_tile_b_morden(const float* aPtr, const float* bPtr, float* oPtr,
int blockM, int blockN, int blockK, int M, int N, int K) {
const int tileMSize = 8;
const int tileKSize = 8;
const int tileNSize = 4;
//#pragma omp parallel for schedule(dynamic)
for (int bM = 0; bM < blockM; bM += tileMSize) {
for (int bK = 0; bK < blockK; bK += tileKSize) {
for (int bN = 0; bN < blockN; bN += tileNSize) {
ALOGI("bM=%d, bK=%d, bN=%d, aPtr Offset=%d, bPtr offset=%d", bM, bK, bN, bM * K + bK, bK * N + bN * tileKSize);
gemm_tile_884_b_morden_84(aPtr + bM * K + bK,
bPtr + bK * N + bN * tileKSize,
oPtr + bM * N + bN,
M, N, K);
}
}
}
}
static void gemm_b_morden(const float* aPtr, const float* bPtr, const float* cPtr, float* oPtr, int M, int N, int K) {
ALOGI("Neon float Gemm morden");
const int tileSize = 64;
const int mBlockSize = M / tileSize + (M % tileSize == 0 ? 0 : 1);
const int nBlockSize = N / tileSize + (N % tileSize == 0 ? 0 : 1);
const int kBlockSize = K / tileSize + (K % tileSize == 0 ? 0 : 1);
//ALOGI("mBlockSize=%d, nBlockSize=%d, kBlockSize=%d", mBlockSize, nBlockSize, kBlockSize);
int remainSize[3] = {M % tileSize, N % tileSize, K % tileSize};
memset(oPtr, 0, M * N * sizeof(float));
//#pragma omp parallel for schedule(dynamic)
#pragma omp parallel for schedule(dynamic) collapse(2)
for (int m = 0; m < mBlockSize; m++) {
//memcpy(oPtr + m * N, cPtr, N * sizeof(float));
//memcpy(oPtr + (m + 1) * N, cPtr, N * sizeof(float));
//memcpy(oPtr + (m + 2) * N, cPtr, N * sizeof(float));
//memcpy(oPtr + (m + 3) * N, cPtr, N * sizeof(float));
for (int n = 0; n < nBlockSize; n++) {
for (int k = 0; k < kBlockSize; k++) {
int mTileSize = (m == mBlockSize - 1 && remainSize[0] > 0) ? remainSize[0] : tileSize;
int nTileSize = (n == nBlockSize - 1 && remainSize[1] > 0) ? remainSize[1] : tileSize;
int kTileSize = (k == kBlockSize - 1 && remainSize[2] > 0) ? remainSize[2] : tileSize;
ALOGI("m=%d, n=%d, k=%d, mTileSize=%d, nTileSize=%d, kTileSize=%d", m, n, k, mTileSize, nTileSize, kTileSize);
gemm_tile_b_morden(aPtr + m * tileSize * K + k * tileSize,
bPtr + k * tileSize * N + n * tileSize * 8,
oPtr + m * tileSize * N + n * tileSize,
mTileSize, nTileSize, kTileSize, M, N, K);
}
}
}
}
};
} // namespace NEON
} // namespace CPU
} // namespace Op
} // namespace MAI
|
gbdt.h | #ifndef LIGHTGBM_BOOSTING_GBDT_H_
#define LIGHTGBM_BOOSTING_GBDT_H_
#include <LightGBM/boosting.h>
#include <LightGBM/objective_function.h>
#include <LightGBM/prediction_early_stop.h>
#include <LightGBM/json11.hpp>
#include "score_updater.hpp"
#include <cstdio>
#include <vector>
#include <string>
#include <fstream>
#include <memory>
#include <mutex>
#include <map>
using namespace json11;
namespace LightGBM {
/*!
* \brief GBDT algorithm implementation. including Training, prediction, bagging.
*/
class GBDT : public GBDTBase {
public:
/*!
* \brief Constructor
*/
GBDT();
/*!
* \brief Destructor
*/
~GBDT();
/*!
* \brief Initialization logic
* \param gbdt_config Config for boosting
* \param train_data Training data
* \param objective_function Training objective function
* \param training_metrics Training metrics
*/
void Init(const Config* gbdt_config, const Dataset* train_data,
const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override;
/*!
* \brief Merge model from other boosting object. Will insert to the front of current boosting object
* \param other
*/
void MergeFrom(const Boosting* other) override {
auto other_gbdt = reinterpret_cast<const GBDT*>(other);
// tmp move to other vector
auto original_models = std::move(models_);
models_ = std::vector<std::unique_ptr<Tree>>();
// push model from other first
for (const auto& tree : other_gbdt->models_) {
auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get())));
models_.push_back(std::move(new_tree));
}
num_init_iteration_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
// push model in current object
for (const auto& tree : original_models) {
auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get())));
models_.push_back(std::move(new_tree));
}
num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
}
/*!
* \brief Reset the training data
* \param train_data New Training data
* \param objective_function Training objective function
* \param training_metrics Training metrics
*/
void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override;
/*!
* \brief Reset Boosting Config
* \param gbdt_config Config for boosting
*/
void ResetConfig(const Config* gbdt_config) override;
/*!
* \brief Adding a validation dataset
* \param valid_data Validation dataset
* \param valid_metrics Metrics for validation dataset
*/
void AddValidDataset(const Dataset* valid_data,
const std::vector<const Metric*>& valid_metrics) override;
/*!
* \brief Perform a full training procedure
* \param snapshot_freq frequence of snapshot
* \param model_output_path path of model file
*/
void Train(int snapshot_freq, const std::string& model_output_path) override;
void RefitTree(const std::vector<std::vector<int>>& tree_leaf_prediction) override;
/*!
* \brief Training logic
* \param gradients nullptr for using default objective, otherwise use self-defined boosting
* \param hessians nullptr for using default objective, otherwise use self-defined boosting
* \return True if cannot train any more
*/
virtual bool TrainOneIter(const score_t* gradients, const score_t* hessians) override;
/*!
* \brief Rollback one iteration
*/
void RollbackOneIter() override;
/*!
* \brief Get current iteration
*/
int GetCurrentIteration() const override { return static_cast<int>(models_.size()) / num_tree_per_iteration_; }
/*!
* \brief Can use early stopping for prediction or not
* \return True if cannot use early stopping for prediction
*/
bool NeedAccuratePrediction() const override {
if (objective_function_ == nullptr) {
return true;
} else {
return objective_function_->NeedAccuratePrediction();
}
}
/*!
* \brief Get evaluation result at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \return evaluation result
*/
std::vector<double> GetEvalAt(int data_idx) const override;
/*!
* \brief Get current training score
* \param out_len length of returned score
* \return training score
*/
virtual const double* GetTrainingScore(int64_t* out_len) override;
/*!
* \brief Get size of prediction at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \return The size of prediction
*/
virtual int64_t GetNumPredictAt(int data_idx) const override {
CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size()));
data_size_t num_data = train_data_->num_data();
if (data_idx > 0) {
num_data = valid_score_updater_[data_idx - 1]->num_data();
}
return num_data * num_class_;
}
/*!
* \brief Get prediction result at data_idx data
* \param data_idx 0: training data, 1: 1st validation data
* \param result used to store prediction result, should allocate memory before call this function
* \param out_len length of returned score
*/
void GetPredictAt(int data_idx, double* out_result, int64_t* out_len) override;
/*!
* \brief Get number of prediction for one data
* \param num_iteration number of used iterations
* \param is_pred_leaf True if predicting leaf index
* \param is_pred_contrib True if predicting feature contribution
* \return number of prediction
*/
inline int NumPredictOneRow(int num_iteration, bool is_pred_leaf, bool is_pred_contrib) const override {
int num_preb_in_one_row = num_class_;
if (is_pred_leaf) {
int max_iteration = GetCurrentIteration();
if (num_iteration > 0) {
num_preb_in_one_row *= static_cast<int>(std::min(max_iteration, num_iteration));
} else {
num_preb_in_one_row *= max_iteration;
}
} else if (is_pred_contrib) {
num_preb_in_one_row = num_tree_per_iteration_ * (max_feature_idx_ + 2); // +1 for 0-based indexing, +1 for baseline
}
return num_preb_in_one_row;
}
void PredictRaw(const double* features, double* output,
const PredictionEarlyStopInstance* earlyStop) const override;
void PredictRawByMap(const std::unordered_map<int, double>& features, double* output,
const PredictionEarlyStopInstance* early_stop) const override;
void Predict(const double* features, double* output,
const PredictionEarlyStopInstance* earlyStop) const override;
void PredictByMap(const std::unordered_map<int, double>& features, double* output,
const PredictionEarlyStopInstance* early_stop) const override;
void PredictLeafIndex(const double* features, double* output) const override;
void PredictLeafIndexByMap(const std::unordered_map<int, double>& features, double* output) const override;
void PredictContrib(const double* features, double* output,
const PredictionEarlyStopInstance* earlyStop) const override;
/*!
* \brief Dump model to json format string
* \param num_iteration Number of iterations that want to dump, -1 means dump all
* \return Json format string of model
*/
std::string DumpModel(int num_iteration) const override;
/*!
* \brief Translate model to if-else statement
* \param num_iteration Number of iterations that want to translate, -1 means translate all
* \return if-else format codes of model
*/
std::string ModelToIfElse(int num_iteration) const override;
/*!
* \brief Translate model to if-else statement
* \param num_iteration Number of iterations that want to translate, -1 means translate all
* \param filename Filename that want to save to
* \return is_finish Is training finished or not
*/
bool SaveModelToIfElse(int num_iteration, const char* filename) const override;
/*!
* \brief Save model to file
* \param num_iterations Number of model that want to save, -1 means save all
* \param filename Filename that want to save to
* \return is_finish Is training finished or not
*/
virtual bool SaveModelToFile(int num_iterations, const char* filename) const override;
/*!
* \brief Save model to string
* \param num_iterations Number of model that want to save, -1 means save all
* \return Non-empty string if succeeded
*/
virtual std::string SaveModelToString(int num_iterations) const override;
/*!
* \brief Restore from a serialized buffer
*/
bool LoadModelFromString(const char* buffer, size_t len) override;
/*!
* \brief Calculate feature importances
* \param num_iteration Number of model that want to use for feature importance, -1 means use all
* \param importance_type: 0 for split, 1 for gain
* \return vector of feature_importance
*/
std::vector<double> FeatureImportance(int num_iteration, int importance_type) const override;
/*!
* \brief Get max feature index of this model
* \return Max feature index of this model
*/
inline int MaxFeatureIdx() const override { return max_feature_idx_; }
/*!
* \brief Get feature names of this model
* \return Feature names of this model
*/
inline std::vector<std::string> FeatureNames() const override { return feature_names_; }
/*!
* \brief Get index of label column
* \return index of label column
*/
inline int LabelIdx() const override { return label_idx_; }
/*!
* \brief Get number of weak sub-models
* \return Number of weak sub-models
*/
inline int NumberOfTotalModel() const override { return static_cast<int>(models_.size()); }
/*!
* \brief Get number of tree per iteration
* \return number of tree per iteration
*/
inline int NumModelPerIteration() const override { return num_tree_per_iteration_; }
/*!
* \brief Get number of classes
* \return Number of classes
*/
inline int NumberOfClasses() const override { return num_class_; }
inline void InitPredict(int num_iteration, bool is_pred_contrib) override {
num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_;
if (num_iteration > 0) {
num_iteration_for_pred_ = std::min(num_iteration, num_iteration_for_pred_);
}
if (is_pred_contrib) {
#pragma omp parallel for schedule(static)
for (int i = 0; i < static_cast<int>(models_.size()); ++i) {
models_[i]->RecomputeMaxDepth();
}
}
}
inline double GetLeafValue(int tree_idx, int leaf_idx) const override {
CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size());
CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves());
return models_[tree_idx]->LeafOutput(leaf_idx);
}
inline void SetLeafValue(int tree_idx, int leaf_idx, double val) override {
CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size());
CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves());
models_[tree_idx]->SetLeafOutput(leaf_idx, val);
}
/*!
* \brief Get Type name of this boosting object
*/
virtual const char* SubModelName() const override { return "tree"; }
protected:
/*!
* \brief Print eval result and check early stopping
*/
bool EvalAndCheckEarlyStopping();
/*!
* \brief reset config for bagging
*/
void ResetBaggingConfig(const Config* config, bool is_change_dataset);
/*!
* \brief Implement bagging logic
* \param iter Current interation
*/
virtual void Bagging(int iter);
/*!
* \brief Helper function for bagging, used for multi-threading optimization
* \param start start indice of bagging
* \param cnt count
* \param buffer output buffer
* \return count of left size
*/
data_size_t BaggingHelper(Random& cur_rand, data_size_t start, data_size_t cnt, data_size_t* buffer);
/*!
* \brief calculate the object function
*/
virtual void Boosting();
/*!
* \brief updating score after tree was trained
* \param tree Trained tree of this iteration
* \param cur_tree_id Current tree for multiclass training
*/
virtual void UpdateScore(const Tree* tree, const int cur_tree_id);
/*!
* \brief eval results for one metric
*/
virtual std::vector<double> EvalOneMetric(const Metric* metric, const double* score) const;
/*!
* \brief Print metric result of current iteration
* \param iter Current interation
* \return best_msg if met early_stopping
*/
std::string OutputMetric(int iter);
double BoostFromAverage();
/*! \brief current iteration */
int iter_;
/*! \brief Pointer to training data */
const Dataset* train_data_;
/*! \brief Config of gbdt */
std::unique_ptr<Config> config_;
/*! \brief Tree learner, will use this class to learn trees */
std::unique_ptr<TreeLearner> tree_learner_;
/*! \brief Objective function */
const ObjectiveFunction* objective_function_;
/*! \brief Store and update training data's score */
std::unique_ptr<ScoreUpdater> train_score_updater_;
/*! \brief Metrics for training data */
std::vector<const Metric*> training_metrics_;
/*! \brief Store and update validation data's scores */
std::vector<std::unique_ptr<ScoreUpdater>> valid_score_updater_;
/*! \brief Metric for validation data */
std::vector<std::vector<const Metric*>> valid_metrics_;
/*! \brief Number of rounds for early stopping */
int early_stopping_round_;
/*! \brief Best iteration(s) for early stopping */
std::vector<std::vector<int>> best_iter_;
/*! \brief Best score(s) for early stopping */
std::vector<std::vector<double>> best_score_;
/*! \brief output message of best iteration */
std::vector<std::vector<std::string>> best_msg_;
/*! \brief Trained models(trees) */
std::vector<std::unique_ptr<Tree>> models_;
/*! \brief Max feature index of training data*/
int max_feature_idx_;
/*! \brief First order derivative of training data */
std::vector<score_t> gradients_;
/*! \brief Secend order derivative of training data */
std::vector<score_t> hessians_;
/*! \brief Store the indices of in-bag data */
std::vector<data_size_t> bag_data_indices_;
/*! \brief Number of in-bag data */
data_size_t bag_data_cnt_;
/*! \brief Store the indices of in-bag data */
std::vector<data_size_t> tmp_indices_;
/*! \brief Number of training data */
data_size_t num_data_;
/*! \brief Number of trees per iterations */
int num_tree_per_iteration_;
/*! \brief Number of class */
int num_class_;
/*! \brief Index of label column */
data_size_t label_idx_;
/*! \brief number of used model */
int num_iteration_for_pred_;
/*! \brief Shrinkage rate for one iteration */
double shrinkage_rate_;
/*! \brief Number of loaded initial models */
int num_init_iteration_;
/*! \brief Feature names */
std::vector<std::string> feature_names_;
std::vector<std::string> feature_infos_;
/*! \brief number of threads */
int num_threads_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> offsets_buf_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> left_cnts_buf_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> right_cnts_buf_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> left_write_pos_buf_;
/*! \brief Buffer for multi-threading bagging */
std::vector<data_size_t> right_write_pos_buf_;
std::unique_ptr<Dataset> tmp_subset_;
bool is_use_subset_;
std::vector<bool> class_need_train_;
std::vector<double> class_default_output_;
bool is_constant_hessian_;
std::unique_ptr<ObjectiveFunction> loaded_objective_;
bool average_output_;
bool need_re_bagging_;
std::string loaded_parameter_;
Json forced_splits_json_;
};
} // namespace LightGBM
#endif // LightGBM_BOOSTING_GBDT_H_
|
parallel.h | // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <algorithm>
#ifdef PADDLE_WITH_MKLML
#include <omp.h>
#include "lite/backends/x86/mklml.h"
#endif
namespace paddle {
namespace lite {
namespace x86 {
static void SetNumThreads(int num_threads) {
#ifdef PADDLE_WITH_MKLML
int real_num_threads = std::max(num_threads, 1);
x86::MKL_Set_Num_Threads(real_num_threads);
omp_set_num_threads(real_num_threads);
#endif
}
static inline int64_t GetMaxThreads() {
int64_t num_threads = 1;
#ifdef PADDLE_WITH_MKLML
// Do not support nested omp parallem.
num_threads = omp_in_parallel() ? 1 : omp_get_max_threads();
#endif
return std::max<int>(num_threads, 1L);
}
using ThreadHandler =
std::function<void(const int64_t begin, const int64_t end)>;
static inline void RunParallelFor(const int64_t begin,
const int64_t end,
const ThreadHandler& f) {
if (begin >= end) {
return;
}
#ifdef PADDLE_WITH_MKLML
int64_t num_threads = std::min(GetMaxThreads(), end - begin);
if (num_threads > 1) {
#pragma omp parallel num_threads(num_threads)
{
int64_t tid = omp_get_thread_num();
int64_t chunk_size = (end - begin + num_threads - 1) / num_threads;
int64_t begin_tid = begin + tid * chunk_size;
f(begin_tid, std::min(end, chunk_size + begin_tid));
}
return;
}
#endif
f(begin, end);
}
} // namespace x86
} // namespace lite
} // namespace paddle
|
3d7pt.c | /*
* Order-1, 3D 7 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 32;
tile_size[1] = 32;
tile_size[2] = 32;
tile_size[3] = 64;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
const double alpha = 0.0876;
const double beta = 0.0765;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt-1; t++) {
for (i = 1; i < Nz-1; i++) {
for (j = 1; j < Ny-1; j++) {
for (k = 1; k < Nx-1; k++) {
A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k])
+ beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] +
A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]);
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays (Causing performance degradation
/* for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
*/
return 0;
}
|
decorate.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD EEEEE CCCC OOO RRRR AAA TTTTT EEEEE %
% D D E C O O R R A A T E %
% D D EEE C O O RRRR AAAAA T EEE %
% D D E C O O R R A A T E %
% DDDD EEEEE CCCC OOO R R A A T EEEEE %
% %
% %
% MagickCore Image Decoration Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/decorate.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/transform.h"
/*
Define declarations.
*/
#define AccentuateModulate ScaleCharToQuantum(80)
#define HighlightModulate ScaleCharToQuantum(125)
#define ShadowModulate ScaleCharToQuantum(135)
#define DepthModulate ScaleCharToQuantum(185)
#define TroughModulate ScaleCharToQuantum(110)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B o r d e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BorderImage() surrounds the image with a border of the color defined by
% the bordercolor member of the image structure. The width and height
% of the border are defined by the corresponding members of the border_info
% structure.
%
% The format of the BorderImage method is:
%
% Image *BorderImage(const Image *image,const RectangleInfo *border_info,
% const CompositeOperator compose,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o border_info: define the width and height of the border.
%
% o compose: the composite operator.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *BorderImage(const Image *image,
const RectangleInfo *border_info,const CompositeOperator compose,
ExceptionInfo *exception)
{
Image
*border_image,
*clone_image;
FrameInfo
frame_info;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(border_info != (RectangleInfo *) NULL);
frame_info.width=image->columns+(border_info->width << 1);
frame_info.height=image->rows+(border_info->height << 1);
frame_info.x=(ssize_t) border_info->width;
frame_info.y=(ssize_t) border_info->height;
frame_info.inner_bevel=0;
frame_info.outer_bevel=0;
clone_image=CloneImage(image,0,0,MagickTrue,exception);
if (clone_image == (Image *) NULL)
return((Image *) NULL);
clone_image->matte_color=image->border_color;
border_image=FrameImage(clone_image,&frame_info,compose,exception);
clone_image=DestroyImage(clone_image);
if (border_image != (Image *) NULL)
border_image->matte_color=image->matte_color;
return(border_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F r a m e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FrameImage() adds a simulated three-dimensional border around the image.
% The color of the border is defined by the matte_color member of image.
% Members width and height of frame_info specify the border width of the
% vertical and horizontal sides of the frame. Members inner and outer
% indicate the width of the inner and outer shadows of the frame.
%
% The format of the FrameImage method is:
%
% Image *FrameImage(const Image *image,const FrameInfo *frame_info,
% const CompositeOperator compose,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o frame_info: Define the width and height of the frame and its bevels.
%
% o compose: the composite operator.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *FrameImage(const Image *image,const FrameInfo *frame_info,
const CompositeOperator compose,ExceptionInfo *exception)
{
#define FrameImageTag "Frame/Image"
CacheView
*image_view,
*frame_view;
Image
*frame_image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
accentuate,
highlight,
matte,
shadow,
trough;
register ssize_t
x;
size_t
bevel_width,
height,
width;
ssize_t
y;
/*
Check frame geometry.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(frame_info != (FrameInfo *) NULL);
if ((frame_info->outer_bevel < 0) || (frame_info->inner_bevel < 0))
ThrowImageException(OptionError,"FrameIsLessThanImageSize");
bevel_width=(size_t) (frame_info->outer_bevel+frame_info->inner_bevel);
x=(ssize_t) frame_info->width-frame_info->x-bevel_width;
y=(ssize_t) frame_info->height-frame_info->y-bevel_width;
if ((x < (ssize_t) image->columns) | (y < (ssize_t) image->rows))
ThrowImageException(OptionError,"FrameIsLessThanImageSize");
/*
Initialize framed image attributes.
*/
frame_image=CloneImage(image,frame_info->width,frame_info->height,MagickTrue,
exception);
if (frame_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(frame_image,DirectClass,exception) == MagickFalse)
{
frame_image=DestroyImage(frame_image);
return((Image *) NULL);
}
if ((IsPixelInfoGray(&frame_image->border_color) == MagickFalse) &&
(IsGrayColorspace(frame_image->colorspace) != MagickFalse))
(void) SetImageColorspace(frame_image,sRGBColorspace,exception);
if ((frame_image->matte_color.alpha_trait != UndefinedPixelTrait) &&
(frame_image->alpha_trait == UndefinedPixelTrait))
(void) SetImageAlpha(frame_image,OpaqueAlpha,exception);
frame_image->page=image->page;
if ((image->page.width != 0) && (image->page.height != 0))
{
frame_image->page.width+=frame_image->columns-image->columns;
frame_image->page.height+=frame_image->rows-image->rows;
}
/*
Initialize 3D effects color.
*/
matte=image->matte_color;
accentuate=matte;
accentuate.red=(double) (QuantumScale*((QuantumRange-
AccentuateModulate)*matte.red+(QuantumRange*AccentuateModulate)));
accentuate.green=(double) (QuantumScale*((QuantumRange-
AccentuateModulate)*matte.green+(QuantumRange*AccentuateModulate)));
accentuate.blue=(double) (QuantumScale*((QuantumRange-
AccentuateModulate)*matte.blue+(QuantumRange*AccentuateModulate)));
accentuate.black=(double) (QuantumScale*((QuantumRange-
AccentuateModulate)*matte.black+(QuantumRange*AccentuateModulate)));
accentuate.alpha=matte.alpha;
highlight=matte;
highlight.red=(double) (QuantumScale*((QuantumRange-
HighlightModulate)*matte.red+(QuantumRange*HighlightModulate)));
highlight.green=(double) (QuantumScale*((QuantumRange-
HighlightModulate)*matte.green+(QuantumRange*HighlightModulate)));
highlight.blue=(double) (QuantumScale*((QuantumRange-
HighlightModulate)*matte.blue+(QuantumRange*HighlightModulate)));
highlight.black=(double) (QuantumScale*((QuantumRange-
HighlightModulate)*matte.black+(QuantumRange*HighlightModulate)));
highlight.alpha=matte.alpha;
shadow=matte;
shadow.red=QuantumScale*matte.red*ShadowModulate;
shadow.green=QuantumScale*matte.green*ShadowModulate;
shadow.blue=QuantumScale*matte.blue*ShadowModulate;
shadow.black=QuantumScale*matte.black*ShadowModulate;
shadow.alpha=matte.alpha;
trough=matte;
trough.red=QuantumScale*matte.red*TroughModulate;
trough.green=QuantumScale*matte.green*TroughModulate;
trough.blue=QuantumScale*matte.blue*TroughModulate;
trough.black=QuantumScale*matte.black*TroughModulate;
trough.alpha=matte.alpha;
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
frame_view=AcquireAuthenticCacheView(frame_image,exception);
height=(size_t) (frame_info->outer_bevel+(frame_info->y-bevel_width)+
frame_info->inner_bevel);
if (height != 0)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
/*
Draw top of ornamental border.
*/
q=QueueCacheViewAuthenticPixels(frame_view,0,0,frame_image->columns,
height,exception);
if (q != (Quantum *) NULL)
{
/*
Draw top of ornamental border.
*/
for (y=0; y < (ssize_t) frame_info->outer_bevel; y++)
{
for (x=0; x < (ssize_t) (frame_image->columns-y); x++)
{
if (x < y)
SetPixelViaPixelInfo(frame_image,&highlight,q);
else
SetPixelViaPixelInfo(frame_image,&accentuate,q);
q+=GetPixelChannels(frame_image);
}
for ( ; x < (ssize_t) frame_image->columns; x++)
{
SetPixelViaPixelInfo(frame_image,&shadow,q);
q+=GetPixelChannels(frame_image);
}
}
for (y=0; y < (ssize_t) (frame_info->y-bevel_width); y++)
{
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&highlight,q);
q+=GetPixelChannels(frame_image);
}
width=frame_image->columns-2*frame_info->outer_bevel;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelViaPixelInfo(frame_image,&matte,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&shadow,q);
q+=GetPixelChannels(frame_image);
}
}
for (y=0; y < (ssize_t) frame_info->inner_bevel; y++)
{
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&highlight,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++)
{
SetPixelViaPixelInfo(frame_image,&matte,q);
q+=GetPixelChannels(frame_image);
}
width=image->columns+((size_t) frame_info->inner_bevel << 1)-
y;
for (x=0; x < (ssize_t) width; x++)
{
if (x < y)
SetPixelViaPixelInfo(frame_image,&shadow,q);
else
SetPixelViaPixelInfo(frame_image,&trough,q);
q+=GetPixelChannels(frame_image);
}
for ( ; x < (ssize_t) (image->columns+2*frame_info->inner_bevel); x++)
{
SetPixelViaPixelInfo(frame_image,&highlight,q);
q+=GetPixelChannels(frame_image);
}
width=frame_info->width-frame_info->x-image->columns-bevel_width;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelViaPixelInfo(frame_image,&matte,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&shadow,q);
q+=GetPixelChannels(frame_image);
}
}
(void) SyncCacheViewAuthenticPixels(frame_view,exception);
}
}
/*
Draw sides of ornamental border.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,frame_image,1,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
size_t
width;
/*
Initialize scanline with matte color.
*/
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(frame_view,0,frame_info->y+y,
frame_image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&highlight,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++)
{
SetPixelViaPixelInfo(frame_image,&matte,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) frame_info->inner_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&shadow,q);
q+=GetPixelChannels(frame_image);
}
/*
Set frame interior pixels.
*/
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelViaPixelInfo(frame_image,&frame_image->border_color,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) frame_info->inner_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&highlight,q);
q+=GetPixelChannels(frame_image);
}
width=frame_info->width-frame_info->x-image->columns-bevel_width;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelViaPixelInfo(frame_image,&matte,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&shadow,q);
q+=GetPixelChannels(frame_image);
}
if (SyncCacheViewAuthenticPixels(frame_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FrameImage)
#endif
proceed=SetImageProgress(image,FrameImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
height=(size_t) (frame_info->inner_bevel+frame_info->height-
frame_info->y-image->rows-bevel_width+frame_info->outer_bevel);
if (height != 0)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
/*
Draw bottom of ornamental border.
*/
q=QueueCacheViewAuthenticPixels(frame_view,0,(ssize_t) (frame_image->rows-
height),frame_image->columns,height,exception);
if (q != (Quantum *) NULL)
{
/*
Draw bottom of ornamental border.
*/
for (y=frame_info->inner_bevel-1; y >= 0; y--)
{
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&highlight,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) (frame_info->x-bevel_width); x++)
{
SetPixelViaPixelInfo(frame_image,&matte,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < y; x++)
{
SetPixelViaPixelInfo(frame_image,&shadow,q);
q+=GetPixelChannels(frame_image);
}
for ( ; x < (ssize_t) (image->columns+2*frame_info->inner_bevel); x++)
{
if (x >= (ssize_t) (image->columns+2*frame_info->inner_bevel-y))
SetPixelViaPixelInfo(frame_image,&highlight,q);
else
SetPixelViaPixelInfo(frame_image,&accentuate,q);
q+=GetPixelChannels(frame_image);
}
width=frame_info->width-frame_info->x-image->columns-bevel_width;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelViaPixelInfo(frame_image,&matte,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&shadow,q);
q+=GetPixelChannels(frame_image);
}
}
height=frame_info->height-frame_info->y-image->rows-bevel_width;
for (y=0; y < (ssize_t) height; y++)
{
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&highlight,q);
q+=GetPixelChannels(frame_image);
}
width=frame_image->columns-2*frame_info->outer_bevel;
for (x=0; x < (ssize_t) width; x++)
{
SetPixelViaPixelInfo(frame_image,&matte,q);
q+=GetPixelChannels(frame_image);
}
for (x=0; x < (ssize_t) frame_info->outer_bevel; x++)
{
SetPixelViaPixelInfo(frame_image,&shadow,q);
q+=GetPixelChannels(frame_image);
}
}
for (y=frame_info->outer_bevel-1; y >= 0; y--)
{
for (x=0; x < y; x++)
{
SetPixelViaPixelInfo(frame_image,&highlight,q);
q+=GetPixelChannels(frame_image);
}
for ( ; x < (ssize_t) frame_image->columns; x++)
{
if (x >= (ssize_t) (frame_image->columns-y))
SetPixelViaPixelInfo(frame_image,&shadow,q);
else
SetPixelViaPixelInfo(frame_image,&trough,q);
q+=GetPixelChannels(frame_image);
}
}
(void) SyncCacheViewAuthenticPixels(frame_view,exception);
}
}
frame_view=DestroyCacheView(frame_view);
image_view=DestroyCacheView(image_view);
x=(ssize_t) (frame_info->outer_bevel+(frame_info->x-bevel_width)+
frame_info->inner_bevel);
y=(ssize_t) (frame_info->outer_bevel+(frame_info->y-bevel_width)+
frame_info->inner_bevel);
if (status != MagickFalse)
status=CompositeImage(frame_image,image,compose,MagickTrue,x,y,
exception);
if (status == MagickFalse)
frame_image=DestroyImage(frame_image);
return(frame_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a i s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RaiseImage() creates a simulated three-dimensional button-like effect
% by lightening and darkening the edges of the image. Members width and
% height of raise_info define the width of the vertical and horizontal
% edge of the effect.
%
% The format of the RaiseImage method is:
%
% MagickBooleanType RaiseImage(const Image *image,
% const RectangleInfo *raise_info,const MagickBooleanType raise,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o raise_info: Define the width and height of the raise area.
%
% o raise: A value other than zero creates a 3-D raise effect,
% otherwise it has a lowered effect.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RaiseImage(Image *image,
const RectangleInfo *raise_info,const MagickBooleanType raise,
ExceptionInfo *exception)
{
#define AccentuateFactor ScaleCharToQuantum(135)
#define HighlightFactor ScaleCharToQuantum(190)
#define ShadowFactor ScaleCharToQuantum(190)
#define RaiseImageTag "Raise/Image"
#define TroughFactor ScaleCharToQuantum(135)
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
Quantum
foreground,
background;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(raise_info != (RectangleInfo *) NULL);
if ((image->columns <= (raise_info->width << 1)) ||
(image->rows <= (raise_info->height << 1)))
ThrowBinaryException(OptionError,"ImageSizeMustExceedBevelWidth",
image->filename);
foreground=QuantumRange;
background=(Quantum) 0;
if (raise == MagickFalse)
{
foreground=(Quantum) 0;
background=QuantumRange;
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
/*
Raise image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,1,1)
#endif
for (y=0; y < (ssize_t) raise_info->height; y++)
{
register ssize_t
i,
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < y; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumScale*((double) q[i]*HighlightFactor+(double)
foreground*(QuantumRange-HighlightFactor)));
}
q+=GetPixelChannels(image);
}
for ( ; x < (ssize_t) (image->columns-y); x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumScale*((double) q[i]*AccentuateFactor+
(double) foreground*(QuantumRange-AccentuateFactor)));
}
q+=GetPixelChannels(image);
}
for ( ; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumScale*((double) q[i]*ShadowFactor+(double)
background*(QuantumRange-ShadowFactor)));
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_RaiseImage)
#endif
proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,1,1)
#endif
for (y=(ssize_t) raise_info->height; y < (ssize_t) (image->rows-raise_info->height); y++)
{
register ssize_t
i,
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) raise_info->width; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumScale*((double) q[i]*HighlightFactor+(double)
foreground*(QuantumRange-HighlightFactor)));
}
q+=GetPixelChannels(image);
}
for ( ; x < (ssize_t) (image->columns-raise_info->width); x++)
q+=GetPixelChannels(image);
for ( ; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumScale*((double) q[i]*ShadowFactor+(double)
background*(QuantumRange-ShadowFactor)));
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_RaiseImage)
#endif
proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,1,1)
#endif
for (y=(ssize_t) (image->rows-raise_info->height); y < (ssize_t) image->rows; y++)
{
register ssize_t
i,
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) (image->rows-y); x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumScale*((double) q[i]*HighlightFactor+(double)
foreground*(QuantumRange-HighlightFactor)));
}
q+=GetPixelChannels(image);
}
for ( ; x < (ssize_t) (image->columns-(image->rows-y)); x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumScale*((double) q[i]*TroughFactor+
(double) background*(QuantumRange-TroughFactor)));
}
q+=GetPixelChannels(image);
}
for ( ; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampToQuantum(QuantumScale*((double) q[i]*ShadowFactor+(double)
background*(QuantumRange-ShadowFactor)));
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_RaiseImage)
#endif
proceed=SetImageProgress(image,RaiseImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
|
target_data_array_extension_at_exit.c | // --------------------------------------------------
// Check extends before
// --------------------------------------------------
// RUN: %libomptarget-compile-aarch64-unknown-linux-gnu \
// RUN: -fopenmp-version=51 -DEXTENDS=BEFORE
// RUN: %libomptarget-run-aarch64-unknown-linux-gnu 2>&1 \
// RUN: | %fcheck-aarch64-unknown-linux-gnu
// RUN: %libomptarget-compile-powerpc64-ibm-linux-gnu \
// RUN: -fopenmp-version=51 -DEXTENDS=BEFORE
// RUN: %libomptarget-run-powerpc64-ibm-linux-gnu 2>&1 \
// RUN: | %fcheck-powerpc64-ibm-linux-gnu
// RUN: %libomptarget-compile-powerpc64le-ibm-linux-gnu \
// RUN: -fopenmp-version=51 -DEXTENDS=BEFORE
// RUN: %libomptarget-run-powerpc64le-ibm-linux-gnu 2>&1 \
// RUN: | %fcheck-powerpc64le-ibm-linux-gnu
// RUN: %libomptarget-compile-x86_64-pc-linux-gnu \
// RUN: -fopenmp-version=51 -DEXTENDS=BEFORE
// XUN: %libomptarget-run-x86_64-pc-linux-gnu 2>&1 \
// XUN: | %fcheck-x86_64-pc-linux-gnu
// --------------------------------------------------
// Check extends after
// --------------------------------------------------
// RUN: %libomptarget-compile-aarch64-unknown-linux-gnu \
// RUN: -fopenmp-version=51 -DEXTENDS=AFTER
// RUN: %libomptarget-run-aarch64-unknown-linux-gnu 2>&1 \
// RUN: | %fcheck-aarch64-unknown-linux-gnu
// RUN: %libomptarget-compile-powerpc64-ibm-linux-gnu \
// RUN: -fopenmp-version=51 -DEXTENDS=AFTER
// RUN: %libomptarget-run-powerpc64-ibm-linux-gnu 2>&1 \
// RUN: | %fcheck-powerpc64-ibm-linux-gnu
// RUN: %libomptarget-compile-powerpc64le-ibm-linux-gnu \
// RUN: -fopenmp-version=51 -DEXTENDS=AFTER
// RUN: %libomptarget-run-powerpc64le-ibm-linux-gnu 2>&1 \
// RUN: | %fcheck-powerpc64le-ibm-linux-gnu
// RUN: %libomptarget-compile-x86_64-pc-linux-gnu \
// RUN: -fopenmp-version=51 -DEXTENDS=AFTER
// RUN: %libomptarget-run-x86_64-pc-linux-gnu 2>&1 \
// RUN: | %fcheck-x86_64-pc-linux-gnu
// END.
#include <stdio.h>
#define BEFORE 0
#define AFTER 1
#define SIZE 100
#if EXTENDS == BEFORE
# define SMALL_BEG (SIZE-2)
# define SMALL_END SIZE
# define LARGE_BEG 0
# define LARGE_END SIZE
#elif EXTENDS == AFTER
# define SMALL_BEG 0
# define SMALL_END 2
# define LARGE_BEG 0
# define LARGE_END SIZE
#else
# error EXTENDS undefined
#endif
#define SMALL SMALL_BEG:(SMALL_END-SMALL_BEG)
#define LARGE LARGE_BEG:(LARGE_END-LARGE_BEG)
void check_not_present() {
int arr[SIZE];
for (int i = 0; i < SIZE; ++i)
arr[i] = 99;
// CHECK-LABEL: checking not present
fprintf(stderr, "checking not present\n");
// arr[LARGE] isn't (fully) present at the end of the target data region, so
// the device-to-host transfer should not be performed, or it might fail.
#pragma omp target data map(tofrom: arr[LARGE])
{
#pragma omp target exit data map(delete: arr[LARGE])
#pragma omp target enter data map(alloc: arr[SMALL])
#pragma omp target map(alloc: arr[SMALL])
for (int i = SMALL_BEG; i < SMALL_END; ++i)
arr[i] = 88;
}
// CHECK-NOT: Libomptarget
// CHECK-NOT: error
for (int i = 0; i < SIZE; ++i) {
if (arr[i] != 99)
fprintf(stderr, "error: arr[%d]=%d\n", i, arr[i]);
}
}
void check_is_present() {
int arr[SIZE];
for (int i = 0; i < SIZE; ++i)
arr[i] = 99;
// CHECK-LABEL: checking is present
fprintf(stderr, "checking is present\n");
// arr[SMALL] is (fully) present at the end of the target data region, and the
// device-to-host transfer should be performed only for it even though more
// of the array is then present.
#pragma omp target data map(tofrom: arr[SMALL])
{
#pragma omp target exit data map(delete: arr[SMALL])
#pragma omp target enter data map(alloc: arr[LARGE])
#pragma omp target map(alloc: arr[LARGE])
for (int i = LARGE_BEG; i < LARGE_END; ++i)
arr[i] = 88;
}
// CHECK-NOT: Libomptarget
// CHECK-NOT: error
for (int i = 0; i < SIZE; ++i) {
if (SMALL_BEG <= i && i < SMALL_END) {
if (arr[i] != 88)
fprintf(stderr, "error: arr[%d]=%d\n", i, arr[i]);
} else if (arr[i] != 99) {
fprintf(stderr, "error: arr[%d]=%d\n", i, arr[i]);
}
}
}
int main() {
check_not_present();
check_is_present();
return 0;
}
|
coordinate_common.h | /*!
* Copyright 2018 by Contributors
* \author Rory Mitchell
*/
#pragma once
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include <limits>
#include "../common/random.h"
namespace xgboost {
namespace linear {
/**
* \brief Calculate change in weight for a given feature. Applies l1/l2 penalty normalised by the
* number of training instances.
*
* \param sum_grad The sum gradient.
* \param sum_hess The sum hess.
* \param w The weight.
* \param reg_alpha Unnormalised L1 penalty.
* \param reg_lambda Unnormalised L2 penalty.
*
* \return The weight update.
*/
inline double CoordinateDelta(double sum_grad, double sum_hess, double w,
double reg_alpha, double reg_lambda) {
if (sum_hess < 1e-5f) return 0.0f;
const double sum_grad_l2 = sum_grad + reg_lambda * w;
const double sum_hess_l2 = sum_hess + reg_lambda;
const double tmp = w - sum_grad_l2 / sum_hess_l2;
if (tmp >= 0) {
return std::max(-(sum_grad_l2 + reg_alpha) / sum_hess_l2, -w);
} else {
return std::min(-(sum_grad_l2 - reg_alpha) / sum_hess_l2, -w);
}
}
/**
* \brief Calculate update to bias.
*
* \param sum_grad The sum gradient.
* \param sum_hess The sum hess.
*
* \return The weight update.
*/
inline double CoordinateDeltaBias(double sum_grad, double sum_hess) {
return -sum_grad / sum_hess;
}
/**
* \brief Get the gradient with respect to a single feature.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param fidx The target feature.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for a given feature.
*/
inline std::pair<double, double> GetGradient(int group_idx, int num_group, int fidx,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat) {
double sum_grad = 0.0, sum_hess = 0.0;
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
auto col = batch[fidx];
const auto ndata = static_cast<bst_omp_uint>(col.length);
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
sum_grad += p.GetGrad() * v;
sum_hess += p.GetHess() * v * v;
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Get the gradient with respect to a single feature. Row-wise multithreaded.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param fidx The target feature.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for a given feature.
*/
inline std::pair<double, double> GetGradientParallel(int group_idx, int num_group, int fidx,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat) {
double sum_grad = 0.0, sum_hess = 0.0;
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
auto col = batch[fidx];
const auto ndata = static_cast<bst_omp_uint>(col.length);
#pragma omp parallel for schedule(static) reduction(+ : sum_grad, sum_hess)
for (bst_omp_uint j = 0; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
sum_grad += p.GetGrad() * v;
sum_hess += p.GetHess() * v * v;
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Get the gradient with respect to the bias. Row-wise multithreaded.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param gpair Gradients.
* \param p_fmat The feature matrix.
*
* \return The gradient and diagonal Hessian entry for the bias.
*/
inline std::pair<double, double> GetBiasGradientParallel(int group_idx, int num_group,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat) {
const RowSet &rowset = p_fmat->BufferedRowset();
double sum_grad = 0.0, sum_hess = 0.0;
const auto ndata = static_cast<bst_omp_uint>(rowset.Size());
#pragma omp parallel for schedule(static) reduction(+ : sum_grad, sum_hess)
for (bst_omp_uint i = 0; i < ndata; ++i) {
auto &p = gpair[rowset[i] * num_group + group_idx];
if (p.GetHess() >= 0.0f) {
sum_grad += p.GetGrad();
sum_hess += p.GetHess();
}
}
return std::make_pair(sum_grad, sum_hess);
}
/**
* \brief Updates the gradient vector with respect to a change in weight.
*
* \param fidx The feature index.
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param dw The change in weight.
* \param in_gpair The gradient vector to be updated.
* \param p_fmat The input feature matrix.
*/
inline void UpdateResidualParallel(int fidx, int group_idx, int num_group,
float dw, std::vector<GradientPair> *in_gpair,
DMatrix *p_fmat) {
if (dw == 0.0f) return;
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
auto col = batch[fidx];
// update grad value
const auto num_row = static_cast<bst_omp_uint>(col.length);
#pragma omp parallel for schedule(static)
for (bst_omp_uint j = 0; j < num_row; ++j) {
GradientPair &p = (*in_gpair)[col[j].index * num_group + group_idx];
if (p.GetHess() < 0.0f) continue;
p += GradientPair(p.GetHess() * col[j].fvalue * dw, 0);
}
}
}
/**
* \brief Updates the gradient vector based on a change in the bias.
*
* \param group_idx Zero-based index of the group.
* \param num_group Number of groups.
* \param dbias The change in bias.
* \param in_gpair The gradient vector to be updated.
* \param p_fmat The input feature matrix.
*/
inline void UpdateBiasResidualParallel(int group_idx, int num_group, float dbias,
std::vector<GradientPair> *in_gpair,
DMatrix *p_fmat) {
if (dbias == 0.0f) return;
const RowSet &rowset = p_fmat->BufferedRowset();
const auto ndata = static_cast<bst_omp_uint>(p_fmat->Info().num_row_);
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < ndata; ++i) {
GradientPair &g = (*in_gpair)[rowset[i] * num_group + group_idx];
if (g.GetHess() < 0.0f) continue;
g += GradientPair(g.GetHess() * dbias, 0);
}
}
/**
* \brief Abstract class for stateful feature selection or ordering
* in coordinate descent algorithms.
*/
class FeatureSelector {
public:
/*! \brief factory method */
static FeatureSelector *Create(int choice);
/*! \brief virtual destructor */
virtual ~FeatureSelector() = default;
/**
* \brief Setting up the selector state prior to looping through features.
*
* \param model The model.
* \param gpair The gpair.
* \param p_fmat The feature matrix.
* \param alpha Regularisation alpha.
* \param lambda Regularisation lambda.
* \param param A parameter with algorithm-dependent use.
*/
virtual void Setup(const gbm::GBLinearModel &model,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat,
float alpha, float lambda, int param) {}
/**
* \brief Select next coordinate to update.
*
* \param iteration The iteration in a loop through features
* \param model The model.
* \param group_idx Zero-based index of the group.
* \param gpair The gpair.
* \param p_fmat The feature matrix.
* \param alpha Regularisation alpha.
* \param lambda Regularisation lambda.
*
* \return The index of the selected feature. -1 indicates none selected.
*/
virtual int NextFeature(int iteration,
const gbm::GBLinearModel &model,
int group_idx,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) = 0;
};
/**
* \brief Deterministic selection by cycling through features one at a time.
*/
class CyclicFeatureSelector : public FeatureSelector {
public:
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
return iteration % model.param.num_feature;
}
};
/**
* \brief Similar to Cyclyc but with random feature shuffling prior to each update.
* \note Its randomness is controllable by setting a random seed.
*/
class ShuffleFeatureSelector : public FeatureSelector {
public:
void Setup(const gbm::GBLinearModel &model,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda, int param) override {
if (feat_index_.size() == 0) {
feat_index_.resize(model.param.num_feature);
std::iota(feat_index_.begin(), feat_index_.end(), 0);
}
std::shuffle(feat_index_.begin(), feat_index_.end(), common::GlobalRandom());
}
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
return feat_index_[iteration % model.param.num_feature];
}
protected:
std::vector<bst_uint> feat_index_;
};
/**
* \brief A random (with replacement) coordinate selector.
* \note Its randomness is controllable by setting a random seed.
*/
class RandomFeatureSelector : public FeatureSelector {
public:
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
return common::GlobalRandom()() % model.param.num_feature;
}
};
/**
* \brief Select coordinate with the greatest gradient magnitude.
* \note It has O(num_feature^2) complexity. It is fully deterministic.
*
* \note It allows restricting the selection to top_k features per group with
* the largest magnitude of univariate weight change, by passing the top_k value
* through the `param` argument of Setup(). That would reduce the complexity to
* O(num_feature*top_k).
*/
class GreedyFeatureSelector : public FeatureSelector {
public:
void Setup(const gbm::GBLinearModel &model,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda, int param) override {
top_k_ = static_cast<bst_uint>(param);
const bst_uint ngroup = model.param.num_output_group;
if (param <= 0) top_k_ = std::numeric_limits<bst_uint>::max();
if (counter_.size() == 0) {
counter_.resize(ngroup);
gpair_sums_.resize(model.param.num_feature * ngroup);
}
for (bst_uint gid = 0u; gid < ngroup; ++gid) {
counter_[gid] = 0u;
}
}
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
// k-th selected feature for a group
auto k = counter_[group_idx]++;
// stop after either reaching top-K or going through all the features in a group
if (k >= top_k_ || counter_[group_idx] == model.param.num_feature) return -1;
const int ngroup = model.param.num_output_group;
const bst_omp_uint nfeat = model.param.num_feature;
// Calculate univariate gradient sums
std::fill(gpair_sums_.begin(), gpair_sums_.end(), std::make_pair(0., 0.));
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < nfeat; ++i) {
const auto col = batch[i];
const bst_uint ndata = col.length;
auto &sums = gpair_sums_[group_idx * nfeat + i];
for (bst_uint j = 0u; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * ngroup + group_idx];
if (p.GetHess() < 0.f) continue;
sums.first += p.GetGrad() * v;
sums.second += p.GetHess() * v * v;
}
}
}
// Find a feature with the largest magnitude of weight change
int best_fidx = 0;
double best_weight_update = 0.0f;
for (bst_omp_uint fidx = 0; fidx < nfeat; ++fidx) {
auto &s = gpair_sums_[group_idx * nfeat + fidx];
float dw = std::abs(static_cast<bst_float>(
CoordinateDelta(s.first, s.second, model[fidx][group_idx], alpha, lambda)));
if (dw > best_weight_update) {
best_weight_update = dw;
best_fidx = fidx;
}
}
return best_fidx;
}
protected:
bst_uint top_k_;
std::vector<bst_uint> counter_;
std::vector<std::pair<double, double>> gpair_sums_;
};
/**
* \brief Thrifty, approximately-greedy feature selector.
*
* \note Prior to cyclic updates, reorders features in descending magnitude of
* their univariate weight changes. This operation is multithreaded and is a
* linear complexity approximation of the quadratic greedy selection.
*
* \note It allows restricting the selection to top_k features per group with
* the largest magnitude of univariate weight change, by passing the top_k value
* through the `param` argument of Setup().
*/
class ThriftyFeatureSelector : public FeatureSelector {
public:
void Setup(const gbm::GBLinearModel &model,
const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda, int param) override {
top_k_ = static_cast<bst_uint>(param);
if (param <= 0) top_k_ = std::numeric_limits<bst_uint>::max();
const bst_uint ngroup = model.param.num_output_group;
const bst_omp_uint nfeat = model.param.num_feature;
if (deltaw_.size() == 0) {
deltaw_.resize(nfeat * ngroup);
sorted_idx_.resize(nfeat * ngroup);
counter_.resize(ngroup);
gpair_sums_.resize(nfeat * ngroup);
}
// Calculate univariate gradient sums
std::fill(gpair_sums_.begin(), gpair_sums_.end(), std::make_pair(0., 0.));
auto iter = p_fmat->ColIterator();
while (iter->Next()) {
auto batch = iter->Value();
// column-parallel is usually faster than row-parallel
#pragma omp parallel for schedule(static)
for (bst_omp_uint i = 0; i < nfeat; ++i) {
const auto col = batch[i];
const bst_uint ndata = col.length;
for (bst_uint gid = 0u; gid < ngroup; ++gid) {
auto &sums = gpair_sums_[gid * nfeat + i];
for (bst_uint j = 0u; j < ndata; ++j) {
const bst_float v = col[j].fvalue;
auto &p = gpair[col[j].index * ngroup + gid];
if (p.GetHess() < 0.f) continue;
sums.first += p.GetGrad() * v;
sums.second += p.GetHess() * v * v;
}
}
}
}
// rank by descending weight magnitude within the groups
std::fill(deltaw_.begin(), deltaw_.end(), 0.f);
std::iota(sorted_idx_.begin(), sorted_idx_.end(), 0);
bst_float *pdeltaw = &deltaw_[0];
for (bst_uint gid = 0u; gid < ngroup; ++gid) {
// Calculate univariate weight changes
for (bst_omp_uint i = 0; i < nfeat; ++i) {
auto ii = gid * nfeat + i;
auto &s = gpair_sums_[ii];
deltaw_[ii] = static_cast<bst_float>(CoordinateDelta(
s.first, s.second, model[i][gid], alpha, lambda));
}
// sort in descending order of deltaw abs values
auto start = sorted_idx_.begin() + gid * nfeat;
std::sort(start, start + nfeat,
[pdeltaw](size_t i, size_t j) {
return std::abs(*(pdeltaw + i)) > std::abs(*(pdeltaw + j));
});
counter_[gid] = 0u;
}
}
int NextFeature(int iteration, const gbm::GBLinearModel &model,
int group_idx, const std::vector<GradientPair> &gpair,
DMatrix *p_fmat, float alpha, float lambda) override {
// k-th selected feature for a group
auto k = counter_[group_idx]++;
// stop after either reaching top-N or going through all the features in a group
if (k >= top_k_ || counter_[group_idx] == model.param.num_feature) return -1;
// note that sorted_idx stores the "long" indices
const size_t grp_offset = group_idx * model.param.num_feature;
return static_cast<int>(sorted_idx_[grp_offset + k] - grp_offset);
}
protected:
bst_uint top_k_;
std::vector<bst_float> deltaw_;
std::vector<size_t> sorted_idx_;
std::vector<bst_uint> counter_;
std::vector<std::pair<double, double>> gpair_sums_;
};
/**
* \brief A set of available FeatureSelector's
*/
enum FeatureSelectorEnum {
kCyclic = 0,
kShuffle,
kThrifty,
kGreedy,
kRandom
};
inline FeatureSelector *FeatureSelector::Create(int choice) {
switch (choice) {
case kCyclic:
return new CyclicFeatureSelector();
case kShuffle:
return new ShuffleFeatureSelector();
case kThrifty:
return new ThriftyFeatureSelector();
case kGreedy:
return new GreedyFeatureSelector();
case kRandom:
return new RandomFeatureSelector();
default:
LOG(FATAL) << "unknown coordinate selector: " << choice;
}
return nullptr;
}
} // namespace linear
} // namespace xgboost
|
analyze.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% AAA N N AAA L Y Y ZZZZZ EEEEE %
% A A NN N A A L Y Y ZZ E %
% AAAAA N N N AAAAA L Y ZZZ EEE %
% A A N NN A A L Y ZZ E %
% A A N N A A LLLLL Y ZZZZZ EEEEE %
% %
% Analyze An Image %
% %
% Software Design %
% Bill Corbis %
% December 1998 %
% %
% %
% Copyright 1999-2016 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <math.h>
#include "MagickCore/MagickCore.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% a n a l y z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% analyzeImage() computes the brightness and saturation mean, standard
% deviation, kurtosis and skewness and stores these values as attributes
% of the image.
%
% The format of the analyzeImage method is:
%
% size_t analyzeImage(Image *images,const int argc,
% char **argv,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the address of a structure of type Image.
%
% o argc: Specifies a pointer to an integer describing the number of
% elements in the argument vector.
%
% o argv: Specifies a pointer to a text array containing the command line
% arguments.
%
% o exception: return any errors or warnings in this structure.
%
*/
ModuleExport size_t analyzeImage(Image **images,const int argc,
const char **argv,ExceptionInfo *exception)
{
char
text[MagickPathExtent];
double
area,
brightness,
brightness_mean,
brightness_standard_deviation,
brightness_kurtosis,
brightness_skewness,
brightness_sum_x,
brightness_sum_x2,
brightness_sum_x3,
brightness_sum_x4,
hue,
saturation,
saturation_mean,
saturation_standard_deviation,
saturation_kurtosis,
saturation_skewness,
saturation_sum_x,
saturation_sum_x2,
saturation_sum_x3,
saturation_sum_x4;
Image
*image;
assert(images != (Image **) NULL);
assert(*images != (Image *) NULL);
assert((*images)->signature == MagickCoreSignature);
(void) argc;
(void) argv;
image=(*images);
for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
{
CacheView
*image_view;
ssize_t
y;
MagickBooleanType
status;
brightness_sum_x=0.0;
brightness_sum_x2=0.0;
brightness_sum_x3=0.0;
brightness_sum_x4=0.0;
brightness_mean=0.0;
brightness_standard_deviation=0.0;
brightness_kurtosis=0.0;
brightness_skewness=0.0;
saturation_sum_x=0.0;
saturation_sum_x2=0.0;
saturation_sum_x3=0.0;
saturation_sum_x4=0.0;
saturation_mean=0.0;
saturation_standard_deviation=0.0;
saturation_kurtosis=0.0;
saturation_skewness=0.0;
area=0.0;
status=MagickTrue;
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*p;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
ConvertRGBToHSL(GetPixelRed(image,p),GetPixelGreen(image,p),
GetPixelBlue(image,p),&hue,&saturation,&brightness);
brightness*=QuantumRange;
brightness_sum_x+=brightness;
brightness_sum_x2+=brightness*brightness;
brightness_sum_x3+=brightness*brightness*brightness;
brightness_sum_x4+=brightness*brightness*brightness*brightness;
saturation*=QuantumRange;
saturation_sum_x+=saturation;
saturation_sum_x2+=saturation*saturation;
saturation_sum_x3+=saturation*saturation*saturation;
saturation_sum_x4+=saturation*saturation*saturation*saturation;
area++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
if (area <= 0.0)
break;
brightness_mean=brightness_sum_x/area;
(void) FormatLocaleString(text,MagickPathExtent,"%g",brightness_mean);
(void) SetImageProperty(image,"filter:brightness:mean",text,
exception);
brightness_standard_deviation=sqrt(brightness_sum_x2/area-(brightness_sum_x/
area*brightness_sum_x/area));
(void) FormatLocaleString(text,MagickPathExtent,"%g",
brightness_standard_deviation);
(void) SetImageProperty(image,"filter:brightness:standard-deviation",text,
exception);
if (fabs(brightness_standard_deviation) >= MagickEpsilon)
brightness_kurtosis=(brightness_sum_x4/area-4.0*brightness_mean*
brightness_sum_x3/area+6.0*brightness_mean*brightness_mean*
brightness_sum_x2/area-3.0*brightness_mean*brightness_mean*
brightness_mean*brightness_mean)/(brightness_standard_deviation*
brightness_standard_deviation*brightness_standard_deviation*
brightness_standard_deviation)-3.0;
(void) FormatLocaleString(text,MagickPathExtent,"%g",brightness_kurtosis);
(void) SetImageProperty(image,"filter:brightness:kurtosis",text,
exception);
if (brightness_standard_deviation != 0)
brightness_skewness=(brightness_sum_x3/area-3.0*brightness_mean*
brightness_sum_x2/area+2.0*brightness_mean*brightness_mean*
brightness_mean)/(brightness_standard_deviation*
brightness_standard_deviation*brightness_standard_deviation);
(void) FormatLocaleString(text,MagickPathExtent,"%g",brightness_skewness);
(void) SetImageProperty(image,"filter:brightness:skewness",text,
exception);
saturation_mean=saturation_sum_x/area;
(void) FormatLocaleString(text,MagickPathExtent,"%g",saturation_mean);
(void) SetImageProperty(image,"filter:saturation:mean",text,
exception);
saturation_standard_deviation=sqrt(saturation_sum_x2/area-(saturation_sum_x/
area*saturation_sum_x/area));
(void) FormatLocaleString(text,MagickPathExtent,"%g",
saturation_standard_deviation);
(void) SetImageProperty(image,"filter:saturation:standard-deviation",text,
exception);
if (fabs(saturation_standard_deviation) >= MagickEpsilon)
saturation_kurtosis=(saturation_sum_x4/area-4.0*saturation_mean*
saturation_sum_x3/area+6.0*saturation_mean*saturation_mean*
saturation_sum_x2/area-3.0*saturation_mean*saturation_mean*
saturation_mean*saturation_mean)/(saturation_standard_deviation*
saturation_standard_deviation*saturation_standard_deviation*
saturation_standard_deviation)-3.0;
(void) FormatLocaleString(text,MagickPathExtent,"%g",saturation_kurtosis);
(void) SetImageProperty(image,"filter:saturation:kurtosis",text,
exception);
if (fabs(saturation_standard_deviation) >= MagickEpsilon)
saturation_skewness=(saturation_sum_x3/area-3.0*saturation_mean*
saturation_sum_x2/area+2.0*saturation_mean*saturation_mean*
saturation_mean)/(saturation_standard_deviation*
saturation_standard_deviation*saturation_standard_deviation);
(void) FormatLocaleString(text,MagickPathExtent,"%g",saturation_skewness);
(void) SetImageProperty(image,"filter:saturation:skewness",text,
exception);
}
return(MagickImageFilterSignature);
}
|
DRB114-if-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.
*/
/*
When if() evalutes to true, this program has data races due to true dependence within the loop at 65.
Data race pair: a[i+1]@66:5 vs. a[i]@66:12
*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void task(int * a, int i)
{
a[i+1]=(a[i]+1);
return ;
}
int main(int argc, char * argv[])
{
int i;
int len = 100;
int a[100];
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 ++ )
{
a[i]=i;
}
srand(time((void * )0));
#pragma cetus private(i)
#pragma loop name main#1
for (i=0; i<(len-1); i ++ )
{
task( & a[0], i);
}
printf("a[50]=%d\n", a[50]);
_ret_val_0=0;
return _ret_val_0;
}
|
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-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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% 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"
#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)
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
/*
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 enum
{
LayerTypeStandard = 0, // Normal layer with pixels
LayerTypeFolderStartOpen = 1, // Start of a folder, expanded in the UI
LayerTypeFolderStartClosed = 2, // Start of a folder, closed in the UI
LayerTypeFolderEnd = 3, // End of a folder
} PSDLayerType;
typedef enum
{
MaskParametersNone = 0,
MaskParameterUserDensity = 1,
MaskParameterUserFeather = 2,
MaskParameterVectorMask = 4,
} MaskParameters;
/*
Typedef declaractions.
*/
typedef struct _ChannelInfo
{
short
type;
size_t
size;
} ChannelInfo;
typedef struct _MaskInfo
{
Image
*image;
RectangleInfo
page;
unsigned char
background,
flags,
parameters;
unsigned char maskDensity;
MagickDoubleType maskFeather;
} 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;
int layer_type;
MagickBooleanType solid_color_found;
PixelInfo solid_color;
} 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++)
{
register Quantum
*magick_restrict q;
register 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;
register 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++)
{
register Quantum
*magick_restrict q;
register 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;
color.green=(MagickRealType)background;
color.blue=(MagickRealType)background;
color.alpha = (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); // The mask offset is already relative to the base image
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++)
{
register Quantum
*magick_restrict q;
register Quantum
*p;
register 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;
register 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,ExceptionInfo *exception)
{
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:
{
char
value[MagickPathExtent];
unsigned short
resolution;
/*
Resolution info.
*/
if (offset < 16)
break;
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",
image->resolution.x);
(void) SetImageProperty(image,"tiff:XResolution",value,exception);
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) FormatLocaleString(value,MagickPathExtent,"%g",
image->resolution.y);
(void) SetImageProperty(image,"tiff:YResolution",value,exception);
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 void ReversePSDString(Image *image,char *p,size_t length)
{
char
*q;
if (image->endian == MSBEndian)
return;
q=p+length;
for(--q; p < q; ++p, --q)
{
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
}
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;
register const unsigned char
*p;
register Quantum
*q;
register 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)
{
status=MagickFalse;
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 MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels,
const ssize_t type,const PSDCompressionType compression,
const size_t compact_size,ExceptionInfo *exception)
{
MagickBooleanType
status;
register unsigned char
*p;
size_t
count,
length,
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)
{
p=pixels;
while (count > 0)
{
length=image->columns;
while (--length)
{
if (packet_size == 2)
{
p[2]+=p[0]+((p[1]+p[3]) >> 8);
p[3]+=p[1];
}
/*
else if (packet_size == 4)
{
TODO: Figure out what to do there.
}
*/
else
*(p+1)+=*p;
p+=packet_size;
}
p+=packet_size;
count-=row_size;
}
}
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);
if (layer_info->solid_color_found == MagickFalse || layer_info->channel_info[channel].type <= -1)
{
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;
}
}
else
{
status = MagickTrue;
}
(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;
}
if (status != MagickFalse && layer_info->solid_color_found != MagickFalse)
{
if (layer_info->channel_info[channel].type >= -1)
{
Quantum p;
if (layer_info->channel_info[channel].type >= 0)
{
p = (Quantum) * ((&layer_info->solid_color.red) + layer_info->channel_info[channel].type);
}
else
{
p = ScaleCharToQuantum(255);
}
Quantum * q = GetAuthenticPixels(channel_image, 0, 0, channel_image->columns, channel_image->rows, exception);
ssize_t pixel_count = channel_image->columns * channel_image->rows;
ssize_t packet_size = GetPSDPacketSize(image);
for (ssize_t i = 0; i < pixel_count; ++i)
{
SetPSDPixel(channel_image, psd_info->channels, layer_info->channel_info[channel].type, packet_size, p, q, exception);
q += GetPixelChannels(image);
}
SyncAuthenticPixels(channel_image, exception);
}
}
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);
if (layer_info->mask.parameters & MaskParameterUserDensity)
{
(void)FormatLocaleString(message, MagickPathExtent, "%u", layer_info->mask.maskDensity);
(void)SetImageArtifact(layer_info->image, "psd:layer.mask.density", message);
}
if (layer_info->mask.parameters & MaskParameterUserFeather)
{
(void)FormatLocaleString(message, MagickPathExtent, "%.20g", layer_info->mask.maskFeather);
(void)SetImageArtifact(layer_info->image, "psd:layer.mask.feather", message);
}
if (layer_info->mask.parameters & MaskParameterVectorMask)
{
(void)SetImageArtifact(layer_info->image, "psd:layer.mask.vector_mask", "1");
}
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);
/* TODO: Remove this when we figure out how to support this */
if ((compression == ZipWithPrediction) && (image->depth == 32))
{
(void) ThrowMagickException(exception,GetMagickModule(),
TypeError,"CompressionNotSupported","ZipWithPrediction(32 bit)");
return(MagickFalse);
}
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;
register 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)
{
register 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 > 2)) ||
((psd_info->mode == RGBMode) && (psd_info->channels > 3)) ||
((psd_info->mode == CMYKMode) && (psd_info->channels > 4)))
image->alpha_trait=BlendPixelTrait;
}
static inline double ReadDoubleFromDescriptor(char* key, unsigned int keyLength, unsigned char* pos, unsigned int descriptorLength)
{
double invalidResult = -1.0;
unsigned char* end = pos + descriptorLength;
unsigned char* test = pos;
while ((test + keyLength) <= end)
{
if (LocaleNCompare((char*)test, key, keyLength) == 0)
{
test += keyLength;
while ((test + 4) <= end)
{
if (LocaleNCompare((char*)test, "doub", 4) == 0)
{
test += 4;
if ((test + 8) <= end)
{
union
{
unsigned long long uint64;
double value;
} converter;
converter.uint64 = 0;
for (int i = 0; i < 8; ++i)
{
converter.uint64 |= (unsigned long long)(*test++) << ( ( 7 - i ) * 8 );
}
return converter.value;
}
else
{
return invalidResult;
}
}
else
{
++test;
}
}
}
else
{
++test;
}
}
return invalidResult;
}
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;
register ssize_t
i;
ssize_t
count,
index,
j,
number_layers;
#define PSDKeySize 5
#define PSDAdditionalLayerInformationLength 1
const char
additionalLayerInformation[PSDAdditionalLayerInformationLength][PSDKeySize] = {
"Mt16"
};
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
MagickBooleanType done = MagickFalse;
do
{
count = ReadBlob(image, 4, (unsigned char*)type);
if (count == 4)
ReversePSDString(image, type, (size_t)count);
if ((count != 4) || (LocaleNCompare(type, "8BIM", 4) != 0))
{
CheckMergedImageAlpha(psd_info, image);
return(MagickTrue);
}
else
{
count=ReadBlob(image,4,(unsigned char *) type);
if (count == 4)
ReversePSDString(image,type,4);
if ((count == 4) && ((LocaleNCompare(type, "Lr16", 4) == 0) ||
(LocaleNCompare(type, "Lr32", 4) == 0)))
{
size = GetPSDSize(psd_info, image);
done = MagickTrue;
}
else
{
MagickBooleanType found = MagickFalse;
for (i = 0; i < PSDAdditionalLayerInformationLength; i++)
{
if (LocaleNCompare(type, additionalLayerInformation[i], PSDKeySize-1) != 0)
continue;
found = MagickTrue;
break;
}
if (found == MagickFalse)
{
CheckMergedImageAlpha(psd_info, image);
return(MagickTrue);
}
size = ReadBlobLong(image);
if (size > 0)
{
DiscardBlobBytes(image, size);
}
}
}
} while (done == MagickFalse);
}
if (size == 0)
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=ReadBlob(image,4,(unsigned char *) type);
if (count == 4)
ReversePSDString(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=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
if (count != 4)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
ReversePSDString(image,layer_info[i].blendkey,4);
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;
}
int bytesRead = 18;
layer_info[i].mask.parameters = MaskParametersNone;
if (layer_info[i].mask.flags & 0x10)
{
unsigned char params = (unsigned char)ReadBlobByte(image);
++bytesRead;
if (params & 0x01)
{
layer_info[i].mask.maskDensity = (unsigned char)ReadBlobByte(image);
layer_info[i].mask.parameters |= MaskParameterUserDensity;
++bytesRead;
}
if (params & 0x02)
{
layer_info[i].mask.maskFeather = ReadBlobDouble(image);
layer_info[i].mask.parameters |= MaskParameterUserFeather;
bytesRead += sizeof(MagickDoubleType);
}
if (params & 0x0c)
{
layer_info[i].mask.parameters |= MaskParameterVectorMask;
}
else
{
layer_info[i].mask.flags &= ~0x10; // Remove the flag so it exports but without user mask options (they will be reported to the user though)
}
}
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-bytesRead)) == 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);
}
/* Parse layer info */
layer_info[i].layer_type = LayerTypeStandard;
layer_info[i].solid_color_found = MagickFalse;
unsigned char* pos = layer_info[i].info->datum;
if (pos)
{
char key[5];
unsigned char* infoEnd = pos + layer_info[i].info->length;
while (pos < infoEnd)
{
if (LocaleNCompare((const char*)pos, "8BIM", 4) == 0)
{
pos += 4;
key[0] = (char)(*pos++);
key[1] = (char)(*pos++);
key[2] = (char)(*pos++);
key[3] = (char)(*pos++);
key[4] = '\0';
size = (unsigned int)(*pos++) << 24;
size |= (unsigned int)(*pos++) << 16;
size |= (unsigned int)(*pos++) << 8;
size |= (unsigned int)(*pos++);
size = size & 0xffffffff;
if ((LocaleNCompare(key, "lsct", 4) == 0) || (LocaleNCompare(key, "lsdk", 4) == 0))
{
layer_info[i].layer_type |= (unsigned int)(*pos++) << 24;
layer_info[i].layer_type |= (unsigned int)(*pos++) << 16;
layer_info[i].layer_type |= (unsigned int)(*pos++) << 8;
layer_info[i].layer_type |= (unsigned int)(*pos++);
size_t nameCapacity = sizeof(layer_info[i].name) / sizeof(*layer_info[i].name);
switch (layer_info[i].layer_type)
{
case LayerTypeFolderStartClosed:
case LayerTypeFolderStartOpen:
{
char const* startLayerGroupString = "Layer Group: ";
size_t sl = 0;
while (*(startLayerGroupString + sl) != 0)
{
++sl;
}
size_t ll = 0;
while (*(layer_info[i].name + ll) != 0)
{
++ll;
}
for (size_t ni = ll + 1; ni > 0; )
{
--ni;
layer_info[i].name[sl + ni] = layer_info[i].name[ni];
}
for (size_t ni = 0; ni < sl; ++ni)
{
layer_info[i].name[ni] = startLayerGroupString[ni];
}
break;
}
case LayerTypeFolderEnd:
{
CopyMagickString((char*)layer_info[i].name, "End Layer Group", nameCapacity);
break;
}
}
break;
}
else if ((LocaleNCompare(key, "SoCo", 4) == 0))
{
// Solid color image, doesn't have image date so need to set the page up here
unsigned int version = 0;
version = (unsigned int)(*pos++) << 24;
version |= (unsigned int)(*pos++) << 16;
version |= (unsigned int)(*pos++) << 8;
version |= (unsigned int)(*pos++);
size -= 4;
if (version == 16)
{
double r = ReadDoubleFromDescriptor("Rd ", 4, pos, size);
double g = ReadDoubleFromDescriptor("Grn ", 4, pos, size);
double b = ReadDoubleFromDescriptor("Bl ", 4, pos, size);
if (r >= 0.0f && r >= 0.0f && r >= 0.0f)
{
QuantumInfo quantumInfo;
GetQuantumInfo(image_info, &quantumInfo);
layer_info[i].solid_color_found = MagickTrue;
layer_info[i].solid_color.red = (MagickRealType)((r / 255.0) * quantumInfo.scale);
layer_info[i].solid_color.green = (MagickRealType)((g / 255.0) * quantumInfo.scale);
layer_info[i].solid_color.blue = (MagickRealType)((b / 255.0) * quantumInfo.scale);
if (layer_info[i].page.height == 0 && layer_info[i].page.width == 0)
{
layer_info[i].page.x = MAX(layer_info[i].mask.page.x, 0);
layer_info[i].page.y = MAX(layer_info[i].mask.page.y, 0);
layer_info[i].page.width = MIN(layer_info[i].mask.page.width, psd_info->columns);
layer_info[i].page.height = MIN(layer_info[i].mask.page.height, psd_info->rows);
}
}
}
pos += size;
}
else
{
pos += size;
}
}
else
{
break;
}
}
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0))
{
if (layer_info[i].layer_type != LayerTypeStandard)
{
layer_info[i].image = CloneImage(image, 1, 1, MagickFalse, exception);
layer_info[i].visible = MagickFalse;
}
else
{
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;
}
for (i = 0; i < number_layers; i++)
{
if (layer_info[i].layer_type != LayerTypeStandard)
{
layer_info[i].image->columns = layer_info[i].page.width;
layer_info[i].image->rows = layer_info[i].page.height;
}
}
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;
register 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;
register ssize_t
i;
size_t
imageListLength;
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;
if (psd_info.mode == LabMode)
(void) SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
psd_info.min_channels=4;
(void) SetImageColorspace(image,CMYKColorspace,exception);
}
else
if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == 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);
}
else
if (psd_info.mode == IndexedMode)
psd_info.min_channels=1;
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,
exception);
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");
imageListLength=GetImageListLength(image);
if ((psd_info.has_merged_image != MagickFalse) || (imageListLength == 1))
psd_info.has_merged_image=(MagickBooleanType) ReadPSDMergedImage(
image_info,image,&psd_info,exception);
if ((psd_info.has_merged_image == MagickFalse) && (imageListLength == 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);
}
}
if (psd_info.has_merged_image == MagickFalse)
{
Image
*merged;
if (imageListLength == 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);
ReplaceImageInList(&image,merged);
}
if (profile != (StringInfo *) NULL)
{
Image
*next;
i=0;
next=image;
while (next != (Image *) NULL)
{
if (next->page.width > 0 && next->page.height > 0 && 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;
register ssize_t
i,
j;
register 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;
register const Quantum
*p;
register 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;
register 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)
{
register 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)); )
{
register 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)
{
register 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)); )
{
register 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;
register 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;
register 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;
MagickBooleanType
status;
PSDInfo
psd_info;
register 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 */
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)
{
MagickOffsetType
size_offset;
size_t
size;
size_offset=TellBlob(image);
(void) SetPSDSize(&psd_info,image,0);
status=WritePSDLayersInternal(image,image_info,&psd_info,&size,
exception);
size_offset+=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);
}
|
kmeans_clustering.c | /*****************************************************************************/
/*IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. */
/*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. */
/* */
/* */
/*Copyright (c) 2005 Northwestern University */
/*All rights reserved. */
/*Redistribution of the software in source and binary forms, */
/*with or without modification, is 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 Northwestern 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, NON-INFRINGEMENT AND */
/*FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL */
/*NORTHWESTERN UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, */
/*INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/*(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */
/*SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) */
/*HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, */
/*STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/*POSSIBILITY OF SUCH DAMAGE. */
/******************************************************************************/
/*************************************************************************/
/** File: kmeans_clustering.c **/
/** Description: Implementation of regular k-means clustering **/
/** algorithm **/
/** Author: Wei-keng Liao **/
/** ECE Department, Northwestern University **/
/** email: wkliao@ece.northwestern.edu **/
/** **/
/** Edited by: Jay Pisharath **/
/** Northwestern University. **/
/** **/
/** ================================================================ **/
/** **/
/** Edited by: Sang-Ha Lee **/
/** University of Virginia **/
/** **/
/** Description: No longer supports fuzzy c-means clustering; **/
/** only regular k-means clustering. **/
/** Simplified for main functionality: regular k-means **/
/** clustering. **/
/** **/
/*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include "kmeans.h"
#include <omp.h>
#define RANDOM_MAX 2147483647
#ifndef FLT_MAX
#define FLT_MAX 3.40282347e+38
#endif
extern double wtime(void);
extern int num_omp_threads;
int find_nearest_point(float *pt, /* [nfeatures] */
int nfeatures,
float **pts, /* [npts][nfeatures] */
int npts)
{
int index, i;
float min_dist=FLT_MAX;
/* find the cluster center id with min distance to pt */
for (i=0; i<npts; i++) {
float dist;
dist = euclid_dist_2(pt, pts[i], nfeatures); /* no need square root */
if (dist < min_dist) {
min_dist = dist;
index = i;
}
}
return(index);
}
/*----< euclid_dist_2() >----------------------------------------------------*/
/* multi-dimensional spatial Euclid distance square */
__inline
float euclid_dist_2(float *pt1,
float *pt2,
int numdims)
{
int i;
float ans=0.0;
for (i=0; i<numdims; i++)
ans += (pt1[i]-pt2[i]) * (pt1[i]-pt2[i]);
return(ans);
}
/*----< kmeans_clustering() >---------------------------------------------*/
float** kmeans_clustering(float **feature, /* in: [npoints][nfeatures] */
int nfeatures,
int npoints,
int nclusters,
float threshold,
int *membership) /* out: [npoints] */
{
int i, j, k, n=0, index, loop=0;
int *new_centers_len; /* [nclusters]: no. of points in each cluster */
float **new_centers; /* [nclusters][nfeatures] */
float **clusters; /* out: [nclusters][nfeatures] */
float delta;
double timing;
int nthreads;
int **partial_new_centers_len;
float ***partial_new_centers;
nthreads = num_omp_threads;
/* allocate space for returning variable clusters[] */
clusters = (float**) malloc(nclusters * sizeof(float*));
clusters[0] = (float*) malloc(nclusters * nfeatures * sizeof(float));
for (i=1; i<nclusters; i++)
clusters[i] = clusters[i-1] + nfeatures;
/* randomly pick cluster centers */
for (i=0; i<nclusters; i++) {
//n = (int)rand() % npoints;
for (j=0; j<nfeatures; j++)
clusters[i][j] = feature[n][j];
n++;
}
for (i=0; i<npoints; i++)
membership[i] = -1;
/* need to initialize new_centers_len and new_centers[0] to all 0 */
new_centers_len = (int*) calloc(nclusters, sizeof(int));
new_centers = (float**) malloc(nclusters * sizeof(float*));
new_centers[0] = (float*) calloc(nclusters * nfeatures, sizeof(float));
for (i=1; i<nclusters; i++)
new_centers[i] = new_centers[i-1] + nfeatures;
partial_new_centers_len = (int**) malloc(nthreads * sizeof(int*));
partial_new_centers_len[0] = (int*) calloc(nthreads*nclusters, sizeof(int));
for (i=1; i<nthreads; i++)
partial_new_centers_len[i] = partial_new_centers_len[i-1]+nclusters;
partial_new_centers =(float***)malloc(nthreads * sizeof(float**));
partial_new_centers[0] =(float**) malloc(nthreads*nclusters * sizeof(float*));
for (i=1; i<nthreads; i++)
partial_new_centers[i] = partial_new_centers[i-1] + nclusters;
for (i=0; i<nthreads; i++)
{
for (j=0; j<nclusters; j++)
partial_new_centers[i][j] = (float*)calloc(nfeatures, sizeof(float));
}
printf("num of threads = %d\n", num_omp_threads);
do {
delta = 0.0;
omp_set_num_threads(num_omp_threads);
#pragma omp parallel \
shared(feature,clusters,membership,partial_new_centers,partial_new_centers_len)
{
int tid = omp_get_thread_num();
#pragma omp for \
private(i,j,index) \
firstprivate(npoints,nclusters,nfeatures) \
schedule(static) \
reduction(+:delta)
for (i=0; i<npoints; i++) {
/* find the index of nestest cluster centers */
index = find_nearest_point(feature[i],
nfeatures,
clusters,
nclusters);
/* if membership changes, increase delta by 1 */
if (membership[i] != index) delta += 1.0;
/* assign the membership to object i */
membership[i] = index;
/* update new cluster centers : sum of all objects located
within */
partial_new_centers_len[tid][index]++;
for (j=0; j<nfeatures; j++)
partial_new_centers[tid][index][j] += feature[i][j];
}
} /* end of #pragma omp parallel */
/* let the main thread perform the array reduction */
for (i=0; i<nclusters; i++) {
for (j=0; j<nthreads; j++) {
new_centers_len[i] += partial_new_centers_len[j][i];
partial_new_centers_len[j][i] = 0.0;
for (k=0; k<nfeatures; k++) {
new_centers[i][k] += partial_new_centers[j][i][k];
partial_new_centers[j][i][k] = 0.0;
}
}
}
/* replace old cluster centers with new_centers */
for (i=0; i<nclusters; i++) {
for (j=0; j<nfeatures; j++) {
if (new_centers_len[i] > 0)
clusters[i][j] = new_centers[i][j] / new_centers_len[i];
new_centers[i][j] = 0.0; /* set back to 0 */
}
new_centers_len[i] = 0; /* set back to 0 */
}
} while (delta > threshold && loop++ < 500);
free(new_centers[0]);
free(new_centers);
free(new_centers_len);
return clusters;
}
|
GB_unop__tgamma_fp32_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__tgamma_fp32_fp32)
// op(A') function: GB (_unop_tran__tgamma_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = tgammaf (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 = tgammaf (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] = tgammaf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_TGAMMA || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__tgamma_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = tgammaf (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = tgammaf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__tgamma_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
|
omp_dotprod_hybrid.c | /*****************************************************************************
* FILE: omp_dotprod_hybrid.c
* DESCRIPTION:
* This simple program is the hybrid version of a dot product and the fourth
* of four codes used to show the progression from a serial program to a
* hybrid MPI/OpenMP program. The relevant codes are:
* - omp_dotprod_serial.c - Serial version
* - omp_dotprod_openmp.c - OpenMP only version
* - omp_dotprod_mpi.c - MPI only version
* - omp_dotprod_hybrid.c - Hybrid MPI and OpenMP version
* SOURCE: Blaise Barney
* LAST REVISED: 06/02/17 Blaise Barney
******************************************************************************/
#include <mpi.h>
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
/* Define length of dot product vectors and number of OpenMP threads */
#define VECLEN 100
#define NUMTHREADS 8
int main (int argc, char* argv[])
{
int i, myid, tid, numprocs, len=VECLEN, threads=NUMTHREADS;
double *a, *b;
double mysum, allsum, sum, psum;
/* MPI Initialization */
MPI_Init (&argc, &argv);
MPI_Comm_size (MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank (MPI_COMM_WORLD, &myid);
/*
Each MPI task uses OpenMP to perform the dot product, obtains its partial sum,
and then calls MPI_Reduce to obtain the global sum.
*/
if (myid == 0)
printf("Starting omp_dotprod_hybrid. Using %d tasks...\n",numprocs);
/* Assign storage for dot product vectors */
a = (double*) malloc (len*threads*sizeof(double));
b = (double*) malloc (len*threads*sizeof(double));
/* Initialize dot product vectors */
for (i=0; i<len*threads; i++) {
a[i]=1.0;
b[i]=a[i];
}
/*
Perform the dot product in an OpenMP parallel region for loop with a sum reduction
For illustration purposes:
- Explicitly sets number of threads
- Gets and prints number of threads used
- Each thread keeps track of its partial sum
*/
/* Initialize OpenMP reduction sum */
sum = 0.0;
#pragma omp parallel private(i,tid,psum) num_threads(threads)
{
psum = 0.0;
tid = omp_get_thread_num();
if (tid ==0)
{
threads = omp_get_num_threads();
printf("Task %d using %d threads\n",myid, threads);
}
#pragma omp for reduction(+:sum)
for (i=0; i<len*threads; i++)
{
sum += (a[i] * b[i]);
psum = sum;
}
printf("Task %d thread %d partial sum = %f\n",myid, tid, psum);
}
/* Print this task's partial sum */
mysum = sum;
printf("Task %d partial sum = %f\n",myid, mysum);
/* After the dot product, perform a summation of results on each node */
MPI_Reduce (&mysum, &allsum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (myid == 0)
printf ("Done. Hybrid version: global sum = %f \n", allsum);
free (a);
free (b);
MPI_Finalize();
}
|
DRB031-truedepfirstdimension-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.
*/
/*
There is a loop-carried true dependence within the outer level loop.
Data race pair: b[i][j]@66:7 vs. b[i-1][j-1]@66:15
*/
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
int i,j;
int n=1000, m=1000;
double b[1000][1000];
#pragma omp parallel for private(i, j)
for (i=0; i<n; i++)
#pragma omp parallel for private(j)
for (j=0; j<m; j++)
b[i][j] = 0.5;
for (i=1;i<n;i++)
#pragma omp parallel for private(j)
for (j=1;j<m;j++)
b[i][j]=b[i-1][j-1];
for (i=0;i<n;i++)
for (j=0;j<m;j++)
printf("b[%d][%d]=%f\n", i, j, b[i][j]);
return 0;
}
|
DES_bs_b.c | /*
* This file is part of John the Ripper password cracker,
* Copyright (c) 1996-2001,2003,2010-2013,2015 by Solar Designer
*
* Addition of single DES encryption with no salt by
* Deepika Dutta Mishra <dipikadutta at gmail.com> in 2012, no
* rights reserved.
*/
#ifdef _MSC_VER
#undef _OPENMP
#endif
#include "arch.h"
#include "common.h"
#include "DES_bs.h"
#include "memdbg.h"
#if DES_BS_ASM && defined(_OPENMP) && defined(__GNUC__)
#warning Assembly code and OpenMP are both requested - will provide the former, but not the latter (for DES-based hashes). This may likely be corrected by enabling SIMD intrinsics with the C compiler (try adding -msse2 to OMPFLAGS).
#endif
#if !DES_BS_ASM
#define vzero (*(vtype *)&DES_bs_all.zero)
#if DES_bs_mt
#define vones (*(vtype *)&DES_bs_all_by_tnum(-1).ones)
#else
#define vones (*(vtype *)&DES_bs_all.ones)
#endif
#define DES_BS_VECTOR_LOOPS 0
#if defined(__ARM_NEON) && DES_BS_DEPTH == 64
#include <arm_neon.h>
typedef uint32x2_t vtype;
#define vst(dst, ofs, src) \
vst1_u32((uint32_t *)((DES_bs_vector *)&(dst) + (ofs)), (src))
#define vxorf(a, b) \
veor_u32((a), (b))
#define vnot(dst, a) \
(dst) = vmvn_u32((a))
#define vand(dst, a, b) \
(dst) = vand_u32((a), (b))
#define vor(dst, a, b) \
(dst) = vorr_u32((a), (b))
#define vandn(dst, a, b) \
(dst) = vbic_u32((a), (b))
#define vsel(dst, a, b, c) \
(dst) = vbsl_u32((c), (b), (a))
#if 0
#define vshl1(dst, src) \
(dst) = vadd_u32((src), (src))
#endif
#define vshl(dst, src, shift) \
(dst) = vshl_n_u32((src), (shift))
#define vshr(dst, src, shift) \
(dst) = vshr_n_u32((src), (shift))
#elif defined(__ARM_NEON) && ARCH_BITS == 32 && DES_BS_DEPTH == 96
#include <arm_neon.h>
typedef struct {
uint32x2_t f;
unsigned ARCH_WORD g;
} vtype;
#define vst(dst, ofs, src) \
vst1_u32( \
(uint32_t *)&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g
#define vxor(dst, a, b) \
(dst).f = veor_u32((a).f, (b).f); \
(dst).g = (a).g ^ (b).g
#define vnot(dst, a) \
(dst).f = vmvn_u32((a).f); \
(dst).g = ~(a).g
#define vand(dst, a, b) \
(dst).f = vand_u32((a).f, (b).f); \
(dst).g = (a).g & (b).g
#define vor(dst, a, b) \
(dst).f = vorr_u32((a).f, (b).f); \
(dst).g = (a).g | (b).g
#define vandn(dst, a, b) \
(dst).f = vbic_u32((a).f, (b).f); \
(dst).g = (a).g & ~(b).g
#define vsel(dst, a, b, c) \
(dst).f = vbsl_u32((c).f, (b).f, (a).f); \
(dst).g = (((a).g & ~(c).g) ^ ((b).g & (c).g))
#elif defined(__ARM_NEON) && DES_BS_DEPTH == 128 && defined(DES_BS_2X64)
#include <arm_neon.h>
typedef struct {
uint32x2_t f, g;
} vtype;
#define vst(dst, ofs, src) \
vst1_u32( \
(uint32_t *)&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
vst1_u32( \
(uint32_t *)&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g, \
(src).g)
#define vxor(dst, a, b) \
(dst).f = veor_u32((a).f, (b).f); \
(dst).g = veor_u32((a).g, (b).g)
#define vnot(dst, a) \
(dst).f = vmvn_u32((a).f); \
(dst).g = vmvn_u32((a).g)
#define vand(dst, a, b) \
(dst).f = vand_u32((a).f, (b).f); \
(dst).g = vand_u32((a).g, (b).g)
#define vor(dst, a, b) \
(dst).f = vorr_u32((a).f, (b).f); \
(dst).g = vorr_u32((a).g, (b).g)
#define vandn(dst, a, b) \
(dst).f = vbic_u32((a).f, (b).f); \
(dst).g = vbic_u32((a).g, (b).g)
#define vsel(dst, a, b, c) \
(dst).f = vbsl_u32((c).f, (b).f, (a).f); \
(dst).g = vbsl_u32((c).g, (b).g, (a).g)
#elif defined(__ARM_NEON) && DES_BS_DEPTH == 128
#include <arm_neon.h>
typedef uint32x4_t vtype;
#define vst(dst, ofs, src) \
vst1q_u32((uint32_t *)((DES_bs_vector *)&(dst) + (ofs)), (src))
#define vxorf(a, b) \
veorq_u32((a), (b))
#define vnot(dst, a) \
(dst) = vmvnq_u32((a))
#define vand(dst, a, b) \
(dst) = vandq_u32((a), (b))
#define vor(dst, a, b) \
(dst) = vorrq_u32((a), (b))
#define vandn(dst, a, b) \
(dst) = vbicq_u32((a), (b))
#define vsel(dst, a, b, c) \
(dst) = vbslq_u32((c), (b), (a))
#if 0
#define vshl1(dst, src) \
(dst) = vaddq_u32((src), (src))
#endif
#define vshl(dst, src, shift) \
(dst) = vshlq_n_u32((src), (shift))
#define vshr(dst, src, shift) \
(dst) = vshrq_n_u32((src), (shift))
#elif defined(__ARM_NEON) && \
((ARCH_BITS == 64 && DES_BS_DEPTH == 192) || \
(ARCH_BITS == 32 && DES_BS_DEPTH == 160))
#include <arm_neon.h>
typedef struct {
uint32x4_t f;
unsigned ARCH_WORD g;
} vtype;
#define vst(dst, ofs, src) \
vst1q_u32( \
(uint32_t *)&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g
#define vxor(dst, a, b) \
(dst).f = veorq_u32((a).f, (b).f); \
(dst).g = (a).g ^ (b).g
#define vnot(dst, a) \
(dst).f = vmvnq_u32((a).f); \
(dst).g = ~(a).g
#define vand(dst, a, b) \
(dst).f = vandq_u32((a).f, (b).f); \
(dst).g = (a).g & (b).g
#define vor(dst, a, b) \
(dst).f = vorrq_u32((a).f, (b).f); \
(dst).g = (a).g | (b).g
#define vandn(dst, a, b) \
(dst).f = vbicq_u32((a).f, (b).f); \
(dst).g = (a).g & ~(b).g
#define vsel(dst, a, b, c) \
(dst).f = vbslq_u32((c).f, (b).f, (a).f); \
(dst).g = (((a).g & ~(c).g) ^ ((b).g & (c).g))
#elif defined(__ARM_NEON) && DES_BS_DEPTH == 256
#include <arm_neon.h>
typedef struct {
uint32x4_t f, g;
} vtype;
#define vst(dst, ofs, src) \
vst1q_u32( \
(uint32_t *)&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
vst1q_u32( \
(uint32_t *)&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g, \
(src).g)
#define vxor(dst, a, b) \
(dst).f = veorq_u32((a).f, (b).f); \
(dst).g = veorq_u32((a).g, (b).g)
#define vnot(dst, a) \
(dst).f = vmvnq_u32((a).f); \
(dst).g = vmvnq_u32((a).g)
#define vand(dst, a, b) \
(dst).f = vandq_u32((a).f, (b).f); \
(dst).g = vandq_u32((a).g, (b).g)
#define vor(dst, a, b) \
(dst).f = vorrq_u32((a).f, (b).f); \
(dst).g = vorrq_u32((a).g, (b).g)
#define vandn(dst, a, b) \
(dst).f = vbicq_u32((a).f, (b).f); \
(dst).g = vbicq_u32((a).g, (b).g)
#define vsel(dst, a, b, c) \
(dst).f = vbslq_u32((c).f, (b).f, (a).f); \
(dst).g = vbslq_u32((c).g, (b).g, (a).g)
#elif defined(__ALTIVEC__) && DES_BS_DEPTH == 128
#ifdef __linux__
#include <altivec.h>
#endif
typedef vector signed int vtype;
#define vst(dst, ofs, src) \
vec_st((src), (ofs) * sizeof(DES_bs_vector), (dst))
#define vxorf(a, b) \
vec_xor((a), (b))
#define vnot(dst, a) \
(dst) = vec_nor((a), (a))
#define vand(dst, a, b) \
(dst) = vec_and((a), (b))
#define vor(dst, a, b) \
(dst) = vec_or((a), (b))
#define vandn(dst, a, b) \
(dst) = vec_andc((a), (b))
#define vsel(dst, a, b, c) \
(dst) = vec_sel((a), (b), (vector bool int)(c))
#elif defined(__ALTIVEC__) && \
((ARCH_BITS == 64 && DES_BS_DEPTH == 192) || \
(ARCH_BITS == 32 && DES_BS_DEPTH == 160))
#ifdef __linux__
#include <altivec.h>
#endif
typedef struct {
vector signed int f;
unsigned ARCH_WORD g;
} vtype;
#define vst(dst, ofs, src) \
vec_st((src).f, (ofs) * sizeof(DES_bs_vector), ((vtype *)&(dst))->f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g
#define vxor(dst, a, b) \
(dst).f = vec_xor((a).f, (b).f); \
(dst).g = (a).g ^ (b).g
#define vnot(dst, a) \
(dst).f = vec_nor((a).f, (a).f); \
(dst).g = ~(a).g
#define vand(dst, a, b) \
(dst).f = vec_and((a).f, (b).f); \
(dst).g = (a).g & (b).g
#define vor(dst, a, b) \
(dst).f = vec_or((a).f, (b).f); \
(dst).g = (a).g | (b).g
#define vandn(dst, a, b) \
(dst).f = vec_andc((a).f, (b).f); \
(dst).g = (a).g & ~(b).g
#define vsel(dst, a, b, c) \
(dst).f = vec_sel((a).f, (b).f, (vector bool int)(c).f); \
(dst).g = (((a).g & ~(c).g) ^ ((b).g & (c).g))
#elif defined(__ALTIVEC__) && DES_BS_DEPTH == 256
#ifdef __linux__
#include <altivec.h>
#endif
typedef struct {
vector signed int f, g;
} vtype;
#define vst(dst, ofs, src) \
vec_st((src).f, (ofs) * sizeof(DES_bs_vector), ((vtype *)&(dst))->f); \
vec_st((src).g, (ofs) * sizeof(DES_bs_vector), ((vtype *)&(dst))->g)
#define vxor(dst, a, b) \
(dst).f = vec_xor((a).f, (b).f); \
(dst).g = vec_xor((a).g, (b).g)
#define vnot(dst, a) \
(dst).f = vec_nor((a).f, (a).f); \
(dst).g = vec_nor((a).g, (a).g)
#define vand(dst, a, b) \
(dst).f = vec_and((a).f, (b).f); \
(dst).g = vec_and((a).g, (b).g)
#define vor(dst, a, b) \
(dst).f = vec_or((a).f, (b).f); \
(dst).g = vec_or((a).g, (b).g)
#define vandn(dst, a, b) \
(dst).f = vec_andc((a).f, (b).f); \
(dst).g = vec_andc((a).g, (b).g)
#define vsel(dst, a, b, c) \
(dst).f = vec_sel((a).f, (b).f, (vector bool int)(c).f); \
(dst).g = vec_sel((a).g, (b).g, (vector bool int)(c).g)
#elif defined(__MIC__) && DES_BS_DEPTH == 512
#include <immintrin.h>
typedef __m512i vtype;
#define vst(dst, ofs, src) \
_mm512_store_epi32((vtype *)((DES_bs_vector *)&(dst) + (ofs)), (src))
#define vxorf(a, b) \
_mm512_xor_epi32((a), (b))
#define vand(dst, a, b) \
(dst) = _mm512_and_epi32((a), (b))
#define vor(dst, a, b) \
(dst) = _mm512_or_epi32((a), (b))
#define vandn(dst, a, b) \
(dst) = _mm512_andnot_epi32((b), (a))
#define vshl1(dst, src) \
(dst) = _mm512_add_epi32((src), (src))
#define vshl(dst, src, shift) \
(dst) = _mm512_slli_epi32((src), (shift))
#define vshr(dst, src, shift) \
(dst) = _mm512_srli_epi32((src), (shift))
#elif defined(__AVX__) && DES_BS_DEPTH == 256 && !defined(DES_BS_NO_AVX256)
#include <immintrin.h>
typedef __m256i vtype;
#define vst(dst, ofs, src) \
_mm256_store_si256((vtype *)((DES_bs_vector *)&(dst) + (ofs)), (src))
#define vxorf(a, b) \
_mm256_xor_si256((a), (b))
#define vand(dst, a, b) \
(dst) = _mm256_and_si256((a), (b))
#define vor(dst, a, b) \
(dst) = _mm256_or_si256((a), (b))
#define vandn(dst, a, b) \
(dst) = _mm256_andnot_si256((b), (a))
#ifdef __XOP__
/* This could be _mm256_cmov_si256(), but it does not exist (yet?) */
#define vsel(dst, a, b, c) \
(dst) = __builtin_ia32_vpcmov_v8sf256((b), (a), (c))
#endif
#define vshl1(dst, src) \
(dst) = _mm256_add_epi8((src), (src))
#define vshl(dst, src, shift) \
(dst) = _mm256_slli_epi64((src), (shift))
#define vshr(dst, src, shift) \
(dst) = _mm256_srli_epi64((src), (shift))
#elif defined(__AVX__) && DES_BS_DEPTH == 384 && !defined(DES_BS_NO_AVX128)
#include <immintrin.h>
#ifdef __XOP__
#include <x86intrin.h>
#endif
typedef struct {
__m256i f;
__m128i g;
} vtype;
#define vst(dst, ofs, src) \
_mm256_store_si256(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
_mm_store_si128(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g, \
(src).g)
#define vxor(dst, a, b) \
(dst).f = _mm256_xor_si256((a).f, (b).f); \
(dst).g = _mm_xor_si128((a).g, (b).g)
#define vand(dst, a, b) \
(dst).f = _mm256_and_si256((a).f, (b).f); \
(dst).g = _mm_and_si128((a).g, (b).g)
#define vor(dst, a, b) \
(dst).f = _mm256_or_si256((a).f, (b).f); \
(dst).g = _mm_or_si128((a).g, (b).g)
#define vandn(dst, a, b) \
(dst).f = _mm256_andnot_si256((b).f, (a).f); \
(dst).g = _mm_andnot_si128((b).g, (a).g)
#ifdef __XOP__
/* This could be _mm256_cmov_ps(), but it does not exist (yet?) */
#define vsel(dst, a, b, c) \
(dst).f = __builtin_ia32_vpcmov_v8sf256((b).f, (a).f, (c).f); \
(dst).g = _mm_cmov_si128((b).g, (a).g, (c).g)
#endif
#define vshl(dst, src, shift) \
(dst).f = _mm256_slli_epi64((src).f, (shift)); \
(dst).g = _mm_slli_epi64((src).g, (shift))
#define vshr(dst, src, shift) \
(dst).f = _mm256_srli_epi64((src).f, (shift)); \
(dst).g = _mm_srli_epi64((src).g, (shift))
#elif defined(__AVX__) && DES_BS_DEPTH == 512
#include <immintrin.h>
typedef struct {
__m256i f, g;
} vtype;
#define vst(dst, ofs, src) \
_mm256_store_si256(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
_mm256_store_si256(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g, \
(src).g)
#define vxor(dst, a, b) \
(dst).f = _mm256_xor_si256((a).f, (b).f); \
(dst).g = _mm256_xor_si256((a).g, (b).g)
#define vand(dst, a, b) \
(dst).f = _mm256_and_si256((a).f, (b).f); \
(dst).g = _mm256_and_si256((a).g, (b).g)
#define vor(dst, a, b) \
(dst).f = _mm256_or_si256((a).f, (b).f); \
(dst).g = _mm256_or_si256((a).g, (b).g)
#define vandn(dst, a, b) \
(dst).f = _mm256_andnot_si256((b).f, (a).f); \
(dst).g = _mm256_andnot_si256((b).g, (a).g)
#ifdef __XOP__
/* This could be _mm256_cmov_ps(), but it does not exist (yet?) */
#define vsel(dst, a, b, c) \
(dst).f = __builtin_ia32_vpcmov_v8sf256((b).f, (a).f, (c).f); \
(dst).g = __builtin_ia32_vpcmov_v8sf256((b).g, (a).g, (c).g)
#endif
#define vshl(dst, src, shift) \
(dst).f = _mm256_slli_epi64((src).f, (shift)); \
(dst).g = _mm256_slli_epi64((src).g, (shift))
#define vshr(dst, src, shift) \
(dst).f = _mm256_srli_epi64((src).f, (shift)); \
(dst).g = _mm256_srli_epi64((src).g, (shift))
#elif defined(__AVX__) && defined(__MMX__) && DES_BS_DEPTH == 320 && \
!defined(DES_BS_NO_MMX)
#include <immintrin.h>
#include <mmintrin.h>
typedef struct {
__m256i f;
__m64 g;
} vtype;
#define vst(dst, ofs, src) \
_mm256_store_si256(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g
#define vxor(dst, a, b) \
(dst).f = _mm256_xor_si256((a).f, (b).f); \
(dst).g = _mm_xor_si64((a).g, (b).g)
#define vand(dst, a, b) \
(dst).f = _mm256_and_si256((a).f, (b).f); \
(dst).g = _mm_and_si64((a).g, (b).g)
#define vor(dst, a, b) \
(dst).f = _mm256_or_si256((a).f, (b).f); \
(dst).g = _mm_or_si64((a).g, (b).g)
#define vandn(dst, a, b) \
(dst).f = _mm256_andnot_si256((b).f, (a).f); \
(dst).g = _mm_andnot_si64((b).g, (a).g)
#define vshl(dst, src, shift) \
(dst).f = _mm256_slli_epi64((src).f, (shift)); \
(dst).g = _mm_slli_si64((src).g, (shift))
#define vshr(dst, src, shift) \
(dst).f = _mm256_srli_epi64((src).f, (shift)); \
(dst).g = _mm_srli_si64((src).g, (shift))
#elif defined(__AVX__) && \
((ARCH_BITS == 64 && DES_BS_DEPTH == 320) || \
(ARCH_BITS == 32 && DES_BS_DEPTH == 288))
#include <immintrin.h>
#include <mmintrin.h>
typedef struct {
__m256i f;
unsigned ARCH_WORD g;
} vtype;
#define vst(dst, ofs, src) \
_mm256_store_si256(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g
#define vxor(dst, a, b) \
(dst).f = _mm256_xor_si256((a).f, (b).f); \
(dst).g = (a).g ^ (b).g
#define vnot(dst, a) \
(dst).f = _mm256_xor_si256((a).f, vones.f); \
(dst).g = ~(a).g
#define vand(dst, a, b) \
(dst).f = _mm256_and_si256((a).f, (b).f); \
(dst).g = (a).g & (b).g
#define vor(dst, a, b) \
(dst).f = _mm256_or_si256((a).f, (b).f); \
(dst).g = (a).g | (b).g
#define vandn(dst, a, b) \
(dst).f = _mm256_andnot_si256((b).f, (a).f); \
(dst).g = (a).g & ~(b).g
#define vshl(dst, src, shift) \
(dst).f = _mm256_slli_epi64((src).f, (shift)); \
(dst).g = (src).g << (shift)
#define vshr(dst, src, shift) \
(dst).f = _mm256_srli_epi64((src).f, (shift)); \
(dst).g = (src).g >> (shift)
#elif defined(__AVX__) && defined(__MMX__) && \
((ARCH_BITS == 64 && DES_BS_DEPTH == 384) || \
(ARCH_BITS == 32 && DES_BS_DEPTH == 352))
#include <immintrin.h>
#include <mmintrin.h>
typedef struct {
__m256i f;
__m64 g;
unsigned ARCH_WORD h;
} vtype;
#define vst(dst, ofs, src) \
_mm256_store_si256(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g; \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->h = (src).h
#define vxor(dst, a, b) \
(dst).f = _mm256_xor_si256((a).f, (b).f); \
(dst).g = _mm_xor_si64((a).g, (b).g); \
(dst).h = (a).h ^ (b).h
#define vnot(dst, a) \
(dst).f = _mm256_xor_si256((a).f, vones.f); \
(dst).g = _mm_xor_si64((a).g, vones.g); \
(dst).h = ~(a).h
#define vand(dst, a, b) \
(dst).f = _mm256_and_si256((a).f, (b).f); \
(dst).g = _mm_and_si64((a).g, (b).g); \
(dst).h = (a).h & (b).h
#define vor(dst, a, b) \
(dst).f = _mm256_or_si256((a).f, (b).f); \
(dst).g = _mm_or_si64((a).g, (b).g); \
(dst).h = (a).h | (b).h
#define vandn(dst, a, b) \
(dst).f = _mm256_andnot_si256((b).f, (a).f); \
(dst).g = _mm_andnot_si64((b).g, (a).g); \
(dst).h = (a).h & ~(b).h
#define vshl(dst, src, shift) \
(dst).f = _mm256_slli_epi64((src).f, (shift)); \
(dst).g = _mm_slli_si64((src).g, (shift)); \
(dst).h = (src).h << (shift)
#define vshr(dst, src, shift) \
(dst).f = _mm256_srli_epi64((src).f, (shift)); \
(dst).g = _mm_srli_si64((src).g, (shift)); \
(dst).h = (src).h >> (shift)
#elif defined(__SSE2__) && DES_BS_DEPTH == 128
#ifdef __AVX__
#include <immintrin.h>
#ifdef __XOP__
#include <x86intrin.h>
#endif
#else
#include <emmintrin.h>
#endif
typedef __m128i vtype;
#define vst(dst, ofs, src) \
_mm_store_si128((vtype *)((DES_bs_vector *)&(dst) + (ofs)), (src))
#define vxorf(a, b) \
_mm_xor_si128((a), (b))
#define vand(dst, a, b) \
(dst) = _mm_and_si128((a), (b))
#define vor(dst, a, b) \
(dst) = _mm_or_si128((a), (b))
#define vandn(dst, a, b) \
(dst) = _mm_andnot_si128((b), (a))
#ifdef __XOP__
#define vsel(dst, a, b, c) \
(dst) = _mm_cmov_si128((b), (a), (c))
#else
#define vsel(dst, a, b, c) \
(dst) = _mm_xor_si128(_mm_andnot_si128((c), (a)), \
_mm_and_si128((c), (b)))
#endif
#define vshl1(dst, src) \
(dst) = _mm_add_epi8((src), (src))
#define vshl(dst, src, shift) \
(dst) = _mm_slli_epi64((src), (shift))
#define vshr(dst, src, shift) \
(dst) = _mm_srli_epi64((src), (shift))
#elif defined(__SSE2__) && DES_BS_DEPTH == 256 && defined(DES_BS_NO_MMX)
#ifdef __AVX__
#include <immintrin.h>
#ifdef __XOP__
#include <x86intrin.h>
#endif
#else
#include <emmintrin.h>
#endif
typedef struct {
__m128i f, g;
} vtype;
#define vst(dst, ofs, src) \
_mm_store_si128(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
_mm_store_si128(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g, \
(src).g)
#define vxor(dst, a, b) \
(dst).f = _mm_xor_si128((a).f, (b).f); \
(dst).g = _mm_xor_si128((a).g, (b).g)
#define vand(dst, a, b) \
(dst).f = _mm_and_si128((a).f, (b).f); \
(dst).g = _mm_and_si128((a).g, (b).g)
#define vor(dst, a, b) \
(dst).f = _mm_or_si128((a).f, (b).f); \
(dst).g = _mm_or_si128((a).g, (b).g)
#define vandn(dst, a, b) \
(dst).f = _mm_andnot_si128((b).f, (a).f); \
(dst).g = _mm_andnot_si128((b).g, (a).g)
#ifdef __XOP__
#define vsel(dst, a, b, c) \
(dst).f = _mm_cmov_si128((b).f, (a).f, (c).f); \
(dst).g = _mm_cmov_si128((b).g, (a).g, (c).g)
#endif
#define vshl1(dst, src) \
(dst).f = _mm_add_epi8((src).f, (src).f); \
(dst).g = _mm_add_epi8((src).g, (src).g)
#define vshl(dst, src, shift) \
(dst).f = _mm_slli_epi64((src).f, (shift)); \
(dst).g = _mm_slli_epi64((src).g, (shift))
#define vshr(dst, src, shift) \
(dst).f = _mm_srli_epi64((src).f, (shift)); \
(dst).g = _mm_srli_epi64((src).g, (shift))
#elif defined(__SSE2__) && defined(__MMX__) && DES_BS_DEPTH == 192 && \
!defined(DES_BS_NO_MMX)
#include <emmintrin.h>
#include <mmintrin.h>
typedef struct {
__m128i f;
__m64 g;
} vtype;
#define vst(dst, ofs, src) \
_mm_store_si128(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g
#define vxor(dst, a, b) \
(dst).f = _mm_xor_si128((a).f, (b).f); \
(dst).g = _mm_xor_si64((a).g, (b).g)
#define vand(dst, a, b) \
(dst).f = _mm_and_si128((a).f, (b).f); \
(dst).g = _mm_and_si64((a).g, (b).g)
#define vor(dst, a, b) \
(dst).f = _mm_or_si128((a).f, (b).f); \
(dst).g = _mm_or_si64((a).g, (b).g)
#define vandn(dst, a, b) \
(dst).f = _mm_andnot_si128((b).f, (a).f); \
(dst).g = _mm_andnot_si64((b).g, (a).g)
#define vshl1(dst, src) \
(dst).f = _mm_add_epi8((src).f, (src).f); \
(dst).g = _mm_add_pi8((src).g, (src).g)
#define vshl(dst, src, shift) \
(dst).f = _mm_slli_epi64((src).f, (shift)); \
(dst).g = _mm_slli_si64((src).g, (shift))
#define vshr(dst, src, shift) \
(dst).f = _mm_srli_epi64((src).f, (shift)); \
(dst).g = _mm_srli_si64((src).g, (shift))
#elif defined(__SSE2__) && \
((ARCH_BITS == 64 && DES_BS_DEPTH == 192) || \
(ARCH_BITS == 32 && DES_BS_DEPTH == 160))
#include <emmintrin.h>
typedef struct {
__m128i f;
unsigned ARCH_WORD g;
} vtype;
#define vst(dst, ofs, src) \
_mm_store_si128(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g
#define vxor(dst, a, b) \
(dst).f = _mm_xor_si128((a).f, (b).f); \
(dst).g = (a).g ^ (b).g
#define vnot(dst, a) \
(dst).f = _mm_xor_si128((a).f, vones.f); \
(dst).g = ~(a).g
#define vand(dst, a, b) \
(dst).f = _mm_and_si128((a).f, (b).f); \
(dst).g = (a).g & (b).g
#define vor(dst, a, b) \
(dst).f = _mm_or_si128((a).f, (b).f); \
(dst).g = (a).g | (b).g
#define vandn(dst, a, b) \
(dst).f = _mm_andnot_si128((b).f, (a).f); \
(dst).g = (a).g & ~(b).g
#define vshl1(dst, src) \
(dst).f = _mm_add_epi8((src).f, (src).f); \
(dst).g = (src).g << 1
#define vshl(dst, src, shift) \
(dst).f = _mm_slli_epi64((src).f, (shift)); \
(dst).g = (src).g << (shift)
#define vshr(dst, src, shift) \
(dst).f = _mm_srli_epi64((src).f, (shift)); \
(dst).g = (src).g >> (shift)
#elif defined(__SSE2__) && defined(__MMX__) && \
((ARCH_BITS == 64 && DES_BS_DEPTH == 256) || \
(ARCH_BITS == 32 && DES_BS_DEPTH == 224))
#include <emmintrin.h>
#include <mmintrin.h>
typedef struct {
__m128i f;
__m64 g;
unsigned ARCH_WORD h;
} vtype;
#define vst(dst, ofs, src) \
_mm_store_si128(&((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f, \
(src).f); \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g; \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->h = (src).h
#define vxor(dst, a, b) \
(dst).f = _mm_xor_si128((a).f, (b).f); \
(dst).g = _mm_xor_si64((a).g, (b).g); \
(dst).h = (a).h ^ (b).h
#define vnot(dst, a) \
(dst).f = _mm_xor_si128((a).f, vones.f); \
(dst).g = _mm_xor_si64((a).g, vones.g); \
(dst).h = ~(a).h
#define vand(dst, a, b) \
(dst).f = _mm_and_si128((a).f, (b).f); \
(dst).g = _mm_and_si64((a).g, (b).g); \
(dst).h = (a).h & (b).h
#define vor(dst, a, b) \
(dst).f = _mm_or_si128((a).f, (b).f); \
(dst).g = _mm_or_si64((a).g, (b).g); \
(dst).h = (a).h | (b).h
#define vandn(dst, a, b) \
(dst).f = _mm_andnot_si128((b).f, (a).f); \
(dst).g = _mm_andnot_si64((b).g, (a).g); \
(dst).h = (a).h & ~(b).h
#define vshl1(dst, src) \
(dst).f = _mm_add_epi8((src).f, (src).f); \
(dst).g = _mm_add_pi8((src).g, (src).g); \
(dst).h = (src).h << 1
#define vshl(dst, src, shift) \
(dst).f = _mm_slli_epi64((src).f, (shift)); \
(dst).g = _mm_slli_si64((src).g, (shift)); \
(dst).h = (src).h << (shift)
#define vshr(dst, src, shift) \
(dst).f = _mm_srli_epi64((src).f, (shift)); \
(dst).g = _mm_srli_si64((src).g, (shift)); \
(dst).h = (src).h >> (shift)
#elif defined(__MMX__) && ARCH_BITS != 64 && DES_BS_DEPTH == 64
#include <mmintrin.h>
typedef __m64 vtype;
#define vxorf(a, b) \
_mm_xor_si64((a), (b))
#define vand(dst, a, b) \
(dst) = _mm_and_si64((a), (b))
#define vor(dst, a, b) \
(dst) = _mm_or_si64((a), (b))
#define vandn(dst, a, b) \
(dst) = _mm_andnot_si64((b), (a))
#define vshl1(dst, src) \
(dst) = _mm_add_pi8((src), (src))
#define vshl(dst, src, shift) \
(dst) = _mm_slli_si64((src), (shift))
#define vshr(dst, src, shift) \
(dst) = _mm_srli_si64((src), (shift))
#elif defined(__MMX__) && ARCH_BITS == 32 && DES_BS_DEPTH == 96
#include <mmintrin.h>
typedef struct {
__m64 f;
unsigned ARCH_WORD g;
} vtype;
#define vst(dst, ofs, src) \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->f = (src).f; \
((vtype *)((DES_bs_vector *)&(dst) + (ofs)))->g = (src).g
#define vxor(dst, a, b) \
(dst).f = _mm_xor_si64((a).f, (b).f); \
(dst).g = (a).g ^ (b).g
#define vnot(dst, a) \
(dst).f = _mm_xor_si64((a).f, vones.f); \
(dst).g = ~(a).g
#define vand(dst, a, b) \
(dst).f = _mm_and_si64((a).f, (b).f); \
(dst).g = (a).g & (b).g
#define vor(dst, a, b) \
(dst).f = _mm_or_si64((a).f, (b).f); \
(dst).g = (a).g | (b).g
#define vandn(dst, a, b) \
(dst).f = _mm_andnot_si64((b).f, (a).f); \
(dst).g = (a).g & ~(b).g
#define vshl1(dst, src) \
(dst).f = _mm_add_pi8((src).f, (src).f); \
(dst).g = (src).g << 1
#define vshl(dst, src, shift) \
(dst).f = _mm_slli_si64((src).f, (shift)); \
(dst).g = (src).g << (shift)
#define vshr(dst, src, shift) \
(dst).f = _mm_srli_si64((src).f, (shift)); \
(dst).g = (src).g >> (shift)
#else
#if DES_BS_VECTOR
#undef DES_BS_VECTOR_LOOPS
#define DES_BS_VECTOR_LOOPS 1
#endif
typedef unsigned ARCH_WORD vtype;
#define vxorf(a, b) \
((a) ^ (b))
#define vnot(dst, a) \
(dst) = ~(a)
#define vand(dst, a, b) \
(dst) = (a) & (b)
#define vor(dst, a, b) \
(dst) = (a) | (b)
#define vandn(dst, a, b) \
(dst) = (a) & ~(b)
#define vsel(dst, a, b, c) \
(dst) = (((a) & ~(c)) ^ ((b) & (c)))
#define vshl(dst, src, shift) \
(dst) = (src) << (shift)
#define vshr(dst, src, shift) \
(dst) = (src) >> (shift)
/* Assume that 0 always fits in one load immediate instruction */
#undef vzero
#define vzero 0
/* Archs friendly to use of immediate values */
#if defined(__x86_64__) || defined(__i386__)
#undef vones
#define vones (~(vtype)0)
#endif
#endif
#ifndef vst
#define vst(dst, ofs, src) \
*((vtype *)((DES_bs_vector *)&(dst) + (ofs))) = (src)
#endif
#if !defined(vxor) && defined(vxorf)
#define vxor(dst, a, b) \
(dst) = vxorf((a), (b))
#endif
#if !defined(vxorf) && defined(vxor)
/*
* This requires gcc's "Statement Exprs" extension (also supported by a number
* of other C compilers).
*/
#define vxorf(a, b) \
({ vtype tmp; vxor(tmp, (a), (b)); tmp; })
#endif
#ifndef vnot
#define vnot(dst, a) \
vxor((dst), (a), vones)
#endif
#ifndef vshl1
#define vshl1(dst, src) \
vshl((dst), (src), 1)
#endif
#if !DES_BS_VECTOR_LOOPS && defined(vshl) && defined(vshr)
#define DES_BS_VECTOR_LOOPS_K 0
#define DEPTH_K
#define for_each_depth_k()
#define kvtype vtype
#define kvand vand
#define kvor vor
#define kvshl1 vshl1
#define kvshl vshl
#define kvshr vshr
#else
#if DES_BS_VECTOR
#define DES_BS_VECTOR_LOOPS_K 1
#define DEPTH_K [depth]
#define for_each_depth_k() \
for (depth = 0; depth < DES_BS_VECTOR; depth++)
#else
#define DES_BS_VECTOR_LOOPS_K 0
#endif
typedef unsigned ARCH_WORD kvtype;
#define kvand(dst, a, b) \
(dst) = (a) & (b)
#define kvor(dst, a, b) \
(dst) = (a) | (b)
#define kvshl1(dst, src) \
(dst) = (src) << 1
#define kvshl(dst, src, shift) \
(dst) = (src) << (shift)
#define kvshr(dst, src, shift) \
(dst) = (src) >> (shift)
#endif
#if !DES_BS_VECTOR || DES_BS_VECTOR_LOOPS_K
#ifdef __x86_64__
#define mask01 0x0101010101010101UL
#elif __i386__
#define mask01 0x01010101UL
#else
#undef mask01
#endif
#ifdef mask01
#define mask02 (mask01 << 1)
#define mask04 (mask01 << 2)
#define mask08 (mask01 << 3)
#define mask10 (mask01 << 4)
#define mask20 (mask01 << 5)
#define mask40 (mask01 << 6)
#define mask80 (mask01 << 7)
#endif
#endif
#ifndef mask01
#define mask01 (*(kvtype *)&DES_bs_all.masks[0])
#define mask02 (*(kvtype *)&DES_bs_all.masks[1])
#define mask04 (*(kvtype *)&DES_bs_all.masks[2])
#define mask08 (*(kvtype *)&DES_bs_all.masks[3])
#define mask10 (*(kvtype *)&DES_bs_all.masks[4])
#define mask20 (*(kvtype *)&DES_bs_all.masks[5])
#define mask40 (*(kvtype *)&DES_bs_all.masks[6])
#define mask80 (*(kvtype *)&DES_bs_all.masks[7])
#endif
#ifdef __i386__
/* register-starved */
#define LOAD_V \
kvtype v0 = *(kvtype *)&vp[0]; \
kvtype v4 = *(kvtype *)&vp[4];
#define v1 *(kvtype *)&vp[1]
#define v2 *(kvtype *)&vp[2]
#define v3 *(kvtype *)&vp[3]
#define v5 *(kvtype *)&vp[5]
#define v6 *(kvtype *)&vp[6]
#define v7 *(kvtype *)&vp[7]
#else
#define LOAD_V \
kvtype v0 = *(kvtype *)&vp[0]; \
kvtype v1 = *(kvtype *)&vp[1]; \
kvtype v2 = *(kvtype *)&vp[2]; \
kvtype v3 = *(kvtype *)&vp[3]; \
kvtype v4 = *(kvtype *)&vp[4]; \
kvtype v5 = *(kvtype *)&vp[5]; \
kvtype v6 = *(kvtype *)&vp[6]; \
kvtype v7 = *(kvtype *)&vp[7];
#endif
#define kvand_shl1_or(dst, src, mask) \
kvand(tmp, src, mask); \
kvshl1(tmp, tmp); \
kvor(dst, dst, tmp)
#define kvand_shl_or(dst, src, mask, shift) \
kvand(tmp, src, mask); \
kvshl(tmp, tmp, shift); \
kvor(dst, dst, tmp)
#define kvand_shl1(dst, src, mask) \
kvand(tmp, src, mask); \
kvshl1(dst, tmp)
#define kvand_or(dst, src, mask) \
kvand(tmp, src, mask); \
kvor(dst, dst, tmp)
#define kvand_shr_or(dst, src, mask, shift) \
kvand(tmp, src, mask); \
kvshr(tmp, tmp, shift); \
kvor(dst, dst, tmp)
#define kvand_shr(dst, src, mask, shift) \
kvand(tmp, src, mask); \
kvshr(dst, tmp, shift)
#define FINALIZE_NEXT_KEY_BIT_0 { \
kvtype m = mask01, va, vb, tmp; \
kvand(va, v0, m); \
kvand_shl1(vb, v1, m); \
kvand_shl_or(va, v2, m, 2); \
kvand_shl_or(vb, v3, m, 3); \
kvand_shl_or(va, v4, m, 4); \
kvand_shl_or(vb, v5, m, 5); \
kvand_shl_or(va, v6, m, 6); \
kvand_shl_or(vb, v7, m, 7); \
kvor(*(kvtype *)kp, va, vb); \
kp++; \
}
#define FINALIZE_NEXT_KEY_BIT_1 { \
kvtype m = mask02, va, vb, tmp; \
kvand_shr(va, v0, m, 1); \
kvand(vb, v1, m); \
kvand_shl1_or(va, v2, m); \
kvand_shl_or(vb, v3, m, 2); \
kvand_shl_or(va, v4, m, 3); \
kvand_shl_or(vb, v5, m, 4); \
kvand_shl_or(va, v6, m, 5); \
kvand_shl_or(vb, v7, m, 6); \
kvor(*(kvtype *)kp, va, vb); \
kp++; \
}
#define FINALIZE_NEXT_KEY_BIT_2 { \
kvtype m = mask04, va, vb, tmp; \
kvand_shr(va, v0, m, 2); \
kvand_shr(vb, v1, m, 1); \
kvand_or(va, v2, m); \
kvand_shl1_or(vb, v3, m); \
kvand_shl_or(va, v4, m, 2); \
kvand_shl_or(vb, v5, m, 3); \
kvand_shl_or(va, v6, m, 4); \
kvand_shl_or(vb, v7, m, 5); \
kvor(*(kvtype *)kp, va, vb); \
kp++; \
}
#define FINALIZE_NEXT_KEY_BIT_3 { \
kvtype m = mask08, va, vb, tmp; \
kvand_shr(va, v0, m, 3); \
kvand_shr(vb, v1, m, 2); \
kvand_shr_or(va, v2, m, 1); \
kvand_or(vb, v3, m); \
kvand_shl1_or(va, v4, m); \
kvand_shl_or(vb, v5, m, 2); \
kvand_shl_or(va, v6, m, 3); \
kvand_shl_or(vb, v7, m, 4); \
kvor(*(kvtype *)kp, va, vb); \
kp++; \
}
#define FINALIZE_NEXT_KEY_BIT_4 { \
kvtype m = mask10, va, vb, tmp; \
kvand_shr(va, v0, m, 4); \
kvand_shr(vb, v1, m, 3); \
kvand_shr_or(va, v2, m, 2); \
kvand_shr_or(vb, v3, m, 1); \
kvand_or(va, v4, m); \
kvand_shl1_or(vb, v5, m); \
kvand_shl_or(va, v6, m, 2); \
kvand_shl_or(vb, v7, m, 3); \
kvor(*(kvtype *)kp, va, vb); \
kp++; \
}
#define FINALIZE_NEXT_KEY_BIT_5 { \
kvtype m = mask20, va, vb, tmp; \
kvand_shr(va, v0, m, 5); \
kvand_shr(vb, v1, m, 4); \
kvand_shr_or(va, v2, m, 3); \
kvand_shr_or(vb, v3, m, 2); \
kvand_shr_or(va, v4, m, 1); \
kvand_or(vb, v5, m); \
kvand_shl1_or(va, v6, m); \
kvand_shl_or(vb, v7, m, 2); \
kvor(*(kvtype *)kp, va, vb); \
kp++; \
}
#define FINALIZE_NEXT_KEY_BIT_6 { \
kvtype m = mask40, va, vb, tmp; \
kvand_shr(va, v0, m, 6); \
kvand_shr(vb, v1, m, 5); \
kvand_shr_or(va, v2, m, 4); \
kvand_shr_or(vb, v3, m, 3); \
kvand_shr_or(va, v4, m, 2); \
kvand_shr_or(vb, v5, m, 1); \
kvand_or(va, v6, m); \
kvand_shl1_or(vb, v7, m); \
kvor(*(kvtype *)kp, va, vb); \
kp++; \
}
#define FINALIZE_NEXT_KEY_BIT_7 { \
kvtype m = mask80, va, vb, tmp; \
kvand_shr(va, v0, m, 7); \
kvand_shr(vb, v1, m, 6); \
kvand_shr_or(va, v2, m, 5); \
kvand_shr_or(vb, v3, m, 4); \
kvand_shr_or(va, v4, m, 3); \
kvand_shr_or(vb, v5, m, 2); \
kvand_shr_or(va, v6, m, 1); \
kvand_or(vb, v7, m); \
kvor(*(kvtype *)kp, va, vb); \
kp++; \
}
#if DES_bs_mt
static MAYBE_INLINE void DES_bs_finalize_keys(int t)
#else
static MAYBE_INLINE void DES_bs_finalize_keys(void)
#endif
{
#if DES_BS_VECTOR_LOOPS_K
int depth;
#endif
for_each_depth_k() {
DES_bs_vector *kp = (DES_bs_vector *)&DES_bs_all.K[0] DEPTH_K;
int ic;
for (ic = 0; ic < 8; ic++) {
DES_bs_vector *vp =
(DES_bs_vector *)&DES_bs_all.xkeys.v[ic][0] DEPTH_K;
LOAD_V
FINALIZE_NEXT_KEY_BIT_0
FINALIZE_NEXT_KEY_BIT_1
FINALIZE_NEXT_KEY_BIT_2
FINALIZE_NEXT_KEY_BIT_3
FINALIZE_NEXT_KEY_BIT_4
FINALIZE_NEXT_KEY_BIT_5
FINALIZE_NEXT_KEY_BIT_6
}
}
#if DES_BS_EXPAND
{
int index;
for (index = 0; index < 0x300; index++)
for_each_depth_k() {
#if DES_BS_VECTOR_LOOPS_K
DES_bs_all.KS.v[index] DEPTH_K =
DES_bs_all.KSp[index] DEPTH_K;
#else
vst(*(kvtype *)&DES_bs_all.KS.v[index], 0,
*(kvtype *)DES_bs_all.KSp[index]);
#endif
}
}
#endif
}
#endif
#if DES_bs_mt
MAYBE_INLINE void DES_bs_set_salt_for_thread(int t, unsigned int salt)
#else
void DES_bs_set_salt(ARCH_WORD salt)
#endif
{
unsigned int new = salt;
unsigned int old = DES_bs_all.salt;
int dst;
DES_bs_all.salt = new;
for (dst = 0; dst < 24; dst++) {
if ((new ^ old) & 1) {
DES_bs_vector *sp1, *sp2;
int src1 = dst;
int src2 = dst + 24;
if (new & 1) {
src1 = src2;
src2 = dst;
}
sp1 = DES_bs_all.Ens[src1];
sp2 = DES_bs_all.Ens[src2];
DES_bs_all.E.E[dst] = (ARCH_WORD *)sp1;
DES_bs_all.E.E[dst + 24] = (ARCH_WORD *)sp2;
DES_bs_all.E.E[dst + 48] = (ARCH_WORD *)(sp1 + 32);
DES_bs_all.E.E[dst + 72] = (ARCH_WORD *)(sp2 + 32);
}
new >>= 1;
old >>= 1;
if (new == old)
break;
}
}
#if !DES_BS_ASM
/* Include the S-boxes here so that the compiler can inline them */
#if DES_BS == 3
#include "sboxes-s.c"
#elif DES_BS == 2
#include "sboxes.c"
#else
#undef andn
#include "nonstd.c"
#endif
#define b DES_bs_all.B
#define e DES_bs_all.E.E
#if DES_BS_VECTOR_LOOPS
#define kd [depth]
#define bd [depth]
#define ed [depth]
#define DEPTH [depth]
#define for_each_depth() \
for (depth = 0; depth < DES_BS_VECTOR; depth++)
#else
#if DES_BS_EXPAND
#define kd
#else
#define kd [0]
#endif
#define bd
#define ed [0]
#define DEPTH
#define for_each_depth()
#endif
#define DES_bs_clear_block_8(i) \
for_each_depth() { \
vst(b[i] bd, 0, zero); \
vst(b[i] bd, 1, zero); \
vst(b[i] bd, 2, zero); \
vst(b[i] bd, 3, zero); \
vst(b[i] bd, 4, zero); \
vst(b[i] bd, 5, zero); \
vst(b[i] bd, 6, zero); \
vst(b[i] bd, 7, zero); \
}
#define DES_bs_clear_block \
DES_bs_clear_block_8(0); \
DES_bs_clear_block_8(8); \
DES_bs_clear_block_8(16); \
DES_bs_clear_block_8(24); \
DES_bs_clear_block_8(32); \
DES_bs_clear_block_8(40); \
DES_bs_clear_block_8(48); \
DES_bs_clear_block_8(56);
#define DES_bs_set_block_8(i, v0, v1, v2, v3, v4, v5, v6, v7) \
for_each_depth() { \
vst(b[i] bd, 0, v0); \
vst(b[i] bd, 1, v1); \
vst(b[i] bd, 2, v2); \
vst(b[i] bd, 3, v3); \
vst(b[i] bd, 4, v4); \
vst(b[i] bd, 5, v5); \
vst(b[i] bd, 6, v6); \
vst(b[i] bd, 7, v7); \
}
#define x(p) vxorf(*(vtype *)&e[p] ed, *(vtype *)&k[p] kd)
#define y(p, q) vxorf(*(vtype *)&b[p] bd, *(vtype *)&k[q] kd)
#define z(r) ((vtype *)&b[r] bd)
void DES_bs_crypt_25(int keys_count)
{
#if DES_bs_mt
int t, n = (keys_count + (DES_BS_DEPTH - 1)) / DES_BS_DEPTH;
#endif
#ifdef _OPENMP
#pragma omp parallel for default(none) private(t) shared(n, DES_bs_all_p, keys_count)
#endif
for_each_t(n) {
#if DES_BS_EXPAND
DES_bs_vector *k;
#else
ARCH_WORD **k;
#endif
int iterations, rounds_and_swapped;
#if DES_BS_VECTOR_LOOPS
int depth;
#endif
if (DES_bs_all.keys_changed)
goto finalize_keys;
body:
#if DES_bs_mt
DES_bs_set_salt_for_thread(t, DES_bs_all_by_tnum(-1).salt);
#endif
{
vtype zero = vzero;
DES_bs_clear_block
}
#if DES_BS_EXPAND
k = DES_bs_all.KS.v;
#else
k = DES_bs_all.KS.p;
#endif
rounds_and_swapped = 8;
iterations = 25;
start:
for_each_depth()
s1(x(0), x(1), x(2), x(3), x(4), x(5),
z(40), z(48), z(54), z(62));
for_each_depth()
s2(x(6), x(7), x(8), x(9), x(10), x(11),
z(44), z(59), z(33), z(49));
for_each_depth()
s3(y(7, 12), y(8, 13), y(9, 14),
y(10, 15), y(11, 16), y(12, 17),
z(55), z(47), z(61), z(37));
for_each_depth()
s4(y(11, 18), y(12, 19), y(13, 20),
y(14, 21), y(15, 22), y(16, 23),
z(57), z(51), z(41), z(32));
for_each_depth()
s5(x(24), x(25), x(26), x(27), x(28), x(29),
z(39), z(45), z(56), z(34));
for_each_depth()
s6(x(30), x(31), x(32), x(33), x(34), x(35),
z(35), z(60), z(42), z(50));
for_each_depth()
s7(y(23, 36), y(24, 37), y(25, 38),
y(26, 39), y(27, 40), y(28, 41),
z(63), z(43), z(53), z(38));
for_each_depth()
s8(y(27, 42), y(28, 43), y(29, 44),
y(30, 45), y(31, 46), y(0, 47),
z(36), z(58), z(46), z(52));
if (rounds_and_swapped == 0x100) goto next;
swap:
for_each_depth()
s1(x(48), x(49), x(50), x(51), x(52), x(53),
z(8), z(16), z(22), z(30));
for_each_depth()
s2(x(54), x(55), x(56), x(57), x(58), x(59),
z(12), z(27), z(1), z(17));
for_each_depth()
s3(y(39, 60), y(40, 61), y(41, 62),
y(42, 63), y(43, 64), y(44, 65),
z(23), z(15), z(29), z(5));
for_each_depth()
s4(y(43, 66), y(44, 67), y(45, 68),
y(46, 69), y(47, 70), y(48, 71),
z(25), z(19), z(9), z(0));
for_each_depth()
s5(x(72), x(73), x(74), x(75), x(76), x(77),
z(7), z(13), z(24), z(2));
for_each_depth()
s6(x(78), x(79), x(80), x(81), x(82), x(83),
z(3), z(28), z(10), z(18));
for_each_depth()
s7(y(55, 84), y(56, 85), y(57, 86),
y(58, 87), y(59, 88), y(60, 89),
z(31), z(11), z(21), z(6));
for_each_depth()
s8(y(59, 90), y(60, 91), y(61, 92),
y(62, 93), y(63, 94), y(32, 95),
z(4), z(26), z(14), z(20));
k += 96;
if (--rounds_and_swapped) goto start;
k -= (0x300 + 48);
rounds_and_swapped = 0x108;
if (--iterations) goto swap;
#if DES_bs_mt
continue;
#else
return;
#endif
next:
k -= (0x300 - 48);
rounds_and_swapped = 8;
iterations--;
goto start;
finalize_keys:
DES_bs_all.keys_changed = 0;
#if DES_bs_mt
DES_bs_finalize_keys(t);
#else
DES_bs_finalize_keys();
#endif
goto body;
}
}
void DES_bs_crypt(int count, int keys_count)
{
#if DES_bs_mt
int t, n = (keys_count + (DES_BS_DEPTH - 1)) / DES_BS_DEPTH;
#endif
#ifdef _OPENMP
#pragma omp parallel for default(none) private(t) shared(n, DES_bs_all_p, count, keys_count)
#endif
for_each_t(n) {
#if DES_BS_EXPAND
DES_bs_vector *k;
#else
ARCH_WORD **k;
#endif
int iterations, rounds_and_swapped;
#if DES_BS_VECTOR_LOOPS
int depth;
#endif
if (DES_bs_all.keys_changed)
goto finalize_keys;
body:
#if DES_bs_mt
DES_bs_set_salt_for_thread(t, DES_bs_all_by_tnum(-1).salt);
#endif
{
vtype zero = vzero;
DES_bs_clear_block
}
#if DES_BS_EXPAND
k = DES_bs_all.KS.v;
#else
k = DES_bs_all.KS.p;
#endif
rounds_and_swapped = 8;
iterations = count;
start:
for_each_depth()
s1(x(0), x(1), x(2), x(3), x(4), x(5),
z(40), z(48), z(54), z(62));
for_each_depth()
s2(x(6), x(7), x(8), x(9), x(10), x(11),
z(44), z(59), z(33), z(49));
for_each_depth()
s3(x(12), x(13), x(14), x(15), x(16), x(17),
z(55), z(47), z(61), z(37));
for_each_depth()
s4(x(18), x(19), x(20), x(21), x(22), x(23),
z(57), z(51), z(41), z(32));
for_each_depth()
s5(x(24), x(25), x(26), x(27), x(28), x(29),
z(39), z(45), z(56), z(34));
for_each_depth()
s6(x(30), x(31), x(32), x(33), x(34), x(35),
z(35), z(60), z(42), z(50));
for_each_depth()
s7(x(36), x(37), x(38), x(39), x(40), x(41),
z(63), z(43), z(53), z(38));
for_each_depth()
s8(x(42), x(43), x(44), x(45), x(46), x(47),
z(36), z(58), z(46), z(52));
if (rounds_and_swapped == 0x100) goto next;
swap:
for_each_depth()
s1(x(48), x(49), x(50), x(51), x(52), x(53),
z(8), z(16), z(22), z(30));
for_each_depth()
s2(x(54), x(55), x(56), x(57), x(58), x(59),
z(12), z(27), z(1), z(17));
for_each_depth()
s3(x(60), x(61), x(62), x(63), x(64), x(65),
z(23), z(15), z(29), z(5));
for_each_depth()
s4(x(66), x(67), x(68), x(69), x(70), x(71),
z(25), z(19), z(9), z(0));
for_each_depth()
s5(x(72), x(73), x(74), x(75), x(76), x(77),
z(7), z(13), z(24), z(2));
for_each_depth()
s6(x(78), x(79), x(80), x(81), x(82), x(83),
z(3), z(28), z(10), z(18));
for_each_depth()
s7(x(84), x(85), x(86), x(87), x(88), x(89),
z(31), z(11), z(21), z(6));
for_each_depth()
s8(x(90), x(91), x(92), x(93), x(94), x(95),
z(4), z(26), z(14), z(20));
k += 96;
if (--rounds_and_swapped) goto start;
k -= (0x300 + 48);
rounds_and_swapped = 0x108;
if (--iterations) goto swap;
#if DES_bs_mt
continue;
#else
return;
#endif
next:
k -= (0x300 - 48);
rounds_and_swapped = 8;
if (--iterations) goto start;
#if DES_bs_mt
continue;
#else
return;
#endif
finalize_keys:
DES_bs_all.keys_changed = 0;
#if DES_bs_mt
DES_bs_finalize_keys(t);
#else
DES_bs_finalize_keys();
#endif
goto body;
}
}
#undef x
#if DES_bs_mt
static MAYBE_INLINE void DES_bs_finalize_keys_LM(int t)
#else
static MAYBE_INLINE void DES_bs_finalize_keys_LM(void)
#endif
{
#if DES_BS_VECTOR_LOOPS_K
int depth;
#endif
for_each_depth_k() {
DES_bs_vector *kp = (DES_bs_vector *)&DES_bs_all.K[0] DEPTH_K;
int ic;
for (ic = 0; ic < 7; ic++) {
DES_bs_vector *vp =
(DES_bs_vector *)&DES_bs_all.xkeys.v[ic][0] DEPTH_K;
LOAD_V
FINALIZE_NEXT_KEY_BIT_0
FINALIZE_NEXT_KEY_BIT_1
FINALIZE_NEXT_KEY_BIT_2
FINALIZE_NEXT_KEY_BIT_3
FINALIZE_NEXT_KEY_BIT_4
FINALIZE_NEXT_KEY_BIT_5
FINALIZE_NEXT_KEY_BIT_6
FINALIZE_NEXT_KEY_BIT_7
}
}
}
#undef kd
#if DES_BS_VECTOR_LOOPS
#define kd [depth]
#else
#define kd [0]
#endif
int DES_bs_crypt_LM(int *pcount, struct db_salt *salt)
{
int keys_count = *pcount;
#if DES_bs_mt
int t, n = (keys_count + (DES_BS_DEPTH - 1)) / DES_BS_DEPTH;
#endif
#ifdef _OPENMP
#pragma omp parallel for default(none) private(t) shared(n, DES_bs_all_p, keys_count)
#endif
for_each_t(n) {
ARCH_WORD **k;
int rounds;
#if DES_BS_VECTOR_LOOPS
int depth;
#endif
{
vtype z = vzero, o = vones;
DES_bs_set_block_8(0, z, z, z, z, z, z, z, z);
DES_bs_set_block_8(8, o, o, o, z, o, z, z, z);
DES_bs_set_block_8(16, z, z, z, z, z, z, z, o);
DES_bs_set_block_8(24, z, z, o, z, z, o, o, o);
DES_bs_set_block_8(32, z, z, z, o, z, o, o, o);
DES_bs_set_block_8(40, z, z, z, z, z, o, z, z);
DES_bs_set_block_8(48, o, o, z, z, z, z, o, z);
DES_bs_set_block_8(56, o, z, o, z, o, o, o, o);
}
#if DES_bs_mt
DES_bs_finalize_keys_LM(t);
#else
DES_bs_finalize_keys_LM();
#endif
k = DES_bs_all.KS.p;
rounds = 8;
do {
for_each_depth()
s1(y(31, 0), y(0, 1), y(1, 2),
y(2, 3), y(3, 4), y(4, 5),
z(40), z(48), z(54), z(62));
for_each_depth()
s2(y(3, 6), y(4, 7), y(5, 8),
y(6, 9), y(7, 10), y(8, 11),
z(44), z(59), z(33), z(49));
for_each_depth()
s3(y(7, 12), y(8, 13), y(9, 14),
y(10, 15), y(11, 16), y(12, 17),
z(55), z(47), z(61), z(37));
for_each_depth()
s4(y(11, 18), y(12, 19), y(13, 20),
y(14, 21), y(15, 22), y(16, 23),
z(57), z(51), z(41), z(32));
for_each_depth()
s5(y(15, 24), y(16, 25), y(17, 26),
y(18, 27), y(19, 28), y(20, 29),
z(39), z(45), z(56), z(34));
for_each_depth()
s6(y(19, 30), y(20, 31), y(21, 32),
y(22, 33), y(23, 34), y(24, 35),
z(35), z(60), z(42), z(50));
for_each_depth()
s7(y(23, 36), y(24, 37), y(25, 38),
y(26, 39), y(27, 40), y(28, 41),
z(63), z(43), z(53), z(38));
for_each_depth()
s8(y(27, 42), y(28, 43), y(29, 44),
y(30, 45), y(31, 46), y(0, 47),
z(36), z(58), z(46), z(52));
for_each_depth()
s1(y(63, 48), y(32, 49), y(33, 50),
y(34, 51), y(35, 52), y(36, 53),
z(8), z(16), z(22), z(30));
for_each_depth()
s2(y(35, 54), y(36, 55), y(37, 56),
y(38, 57), y(39, 58), y(40, 59),
z(12), z(27), z(1), z(17));
for_each_depth()
s3(y(39, 60), y(40, 61), y(41, 62),
y(42, 63), y(43, 64), y(44, 65),
z(23), z(15), z(29), z(5));
for_each_depth()
s4(y(43, 66), y(44, 67), y(45, 68),
y(46, 69), y(47, 70), y(48, 71),
z(25), z(19), z(9), z(0));
for_each_depth()
s5(y(47, 72), y(48, 73), y(49, 74),
y(50, 75), y(51, 76), y(52, 77),
z(7), z(13), z(24), z(2));
for_each_depth()
s6(y(51, 78), y(52, 79), y(53, 80),
y(54, 81), y(55, 82), y(56, 83),
z(3), z(28), z(10), z(18));
for_each_depth()
s7(y(55, 84), y(56, 85), y(57, 86),
y(58, 87), y(59, 88), y(60, 89),
z(31), z(11), z(21), z(6));
for_each_depth()
s8(y(59, 90), y(60, 91), y(61, 92),
y(62, 93), y(63, 94), y(32, 95),
z(4), z(26), z(14), z(20));
k += 96;
} while (--rounds);
}
return keys_count;
}
#if DES_bs_mt
static MAYBE_INLINE void DES_bs_finalize_keys_plain(int t)
#else
static MAYBE_INLINE void DES_bs_finalize_keys_plain(void)
#endif
{
#if DES_BS_VECTOR_LOOPS_K
int depth;
#endif
for_each_depth_k() {
DES_bs_vector *kp = (DES_bs_vector *)&DES_bs_all.K[0] DEPTH_K;
int ic;
for (ic = 0; ic < 8; ic++) {
DES_bs_vector *vp =
(DES_bs_vector *)&DES_bs_all.xkeys.v[ic][0] DEPTH_K;
LOAD_V
FINALIZE_NEXT_KEY_BIT_0
FINALIZE_NEXT_KEY_BIT_1
FINALIZE_NEXT_KEY_BIT_2
FINALIZE_NEXT_KEY_BIT_3
FINALIZE_NEXT_KEY_BIT_4
FINALIZE_NEXT_KEY_BIT_5
FINALIZE_NEXT_KEY_BIT_6
}
}
}
#undef v1
#undef v2
#undef v3
#undef v5
#undef v6
#undef v7
/* Single Des Encryption with no salt */
#undef kd
#if DES_BS_VECTOR_LOOPS
#define kd [depth]
#else
#define kd [0]
#endif
#if DES_BS_VECTOR
#define INDX [index]
#else
#define INDX
#endif
void DES_bs_crypt_plain(int keys_count)
{
#if DES_bs_mt
int t, n = (keys_count + (DES_BS_DEPTH - 1)) / DES_BS_DEPTH;
#endif
#ifdef _OPENMP
#pragma omp parallel for default(none) private(t) shared(n, DES_bs_all_p, keys_count, DES_bs_P)
#endif
for_each_t(n) {
ARCH_WORD **k;
int rounds;
#if DES_BS_VECTOR_LOOPS
int depth;
#endif
int i;
#if DES_BS_VECTOR
int index;
#endif
for (i=0; i<64; i++)
{
#if DES_BS_VECTOR
for (index=0; index<DES_BS_VECTOR_SIZE; index++)
#endif
DES_bs_all.B[i]INDX = DES_bs_P[i]INDX;
}
#if DES_bs_mt
DES_bs_finalize_keys_plain(t);
#else
DES_bs_finalize_keys_plain();
#endif
k = DES_bs_all.KS.p;
rounds = 8;
do {
for_each_depth()
s1(y(31, 0), y(0, 1), y(1, 2),
y(2, 3), y(3, 4), y(4, 5),
z(40), z(48), z(54), z(62));
for_each_depth()
s2(y(3, 6), y(4, 7), y(5, 8),
y(6, 9), y(7, 10), y(8, 11),
z(44), z(59), z(33), z(49));
for_each_depth()
s3(y(7, 12), y(8, 13), y(9, 14),
y(10, 15), y(11, 16), y(12, 17),
z(55), z(47), z(61), z(37));
for_each_depth()
s4(y(11, 18), y(12, 19), y(13, 20),
y(14, 21), y(15, 22), y(16, 23),
z(57), z(51), z(41), z(32));
for_each_depth()
s5(y(15, 24), y(16, 25), y(17, 26),
y(18, 27), y(19, 28), y(20, 29),
z(39), z(45), z(56), z(34));
for_each_depth()
s6(y(19, 30), y(20, 31), y(21, 32),
y(22, 33), y(23, 34), y(24, 35),
z(35), z(60), z(42), z(50));
for_each_depth()
s7(y(23, 36), y(24, 37), y(25, 38),
y(26, 39), y(27, 40), y(28, 41),
z(63), z(43), z(53), z(38));
for_each_depth()
s8(y(27, 42), y(28, 43), y(29, 44),
y(30, 45), y(31, 46), y(0, 47),
z(36), z(58), z(46), z(52));
for_each_depth()
s1(y(63, 48), y(32, 49), y(33, 50),
y(34, 51), y(35, 52), y(36, 53),
z(8), z(16), z(22), z(30));
for_each_depth()
s2(y(35, 54), y(36, 55), y(37, 56),
y(38, 57), y(39, 58), y(40, 59),
z(12), z(27), z(1), z(17));
for_each_depth()
s3(y(39, 60), y(40, 61), y(41, 62),
y(42, 63), y(43, 64), y(44, 65),
z(23), z(15), z(29), z(5));
for_each_depth()
s4(y(43, 66), y(44, 67), y(45, 68),
y(46, 69), y(47, 70), y(48, 71),
z(25), z(19), z(9), z(0));
for_each_depth()
s5(y(47, 72), y(48, 73), y(49, 74),
y(50, 75), y(51, 76), y(52, 77),
z(7), z(13), z(24), z(2));
for_each_depth()
s6(y(51, 78), y(52, 79), y(53, 80),
y(54, 81), y(55, 82), y(56, 83),
z(3), z(28), z(10), z(18));
for_each_depth()
s7(y(55, 84), y(56, 85), y(57, 86),
y(58, 87), y(59, 88), y(60, 89),
z(31), z(11), z(21), z(6));
for_each_depth()
s8(y(59, 90), y(60, 91), y(61, 92),
y(62, 93), y(63, 94), y(32, 95),
z(4), z(26), z(14), z(20));
k += 96;
} while (--rounds);
}}
#endif
#ifdef INDX
#undef INDX
#endif
#if DES_BS_VECTOR
#define INDX [k]
#else
#define INDX
#endif
void DES_bs_generate_plaintext(unsigned char *plaintext)
{
int i, j;
#if DES_BS_VECTOR
int k;
#endif
/* Set same plaintext for all bit layers */
for (i = 0; i < 64; i++) {
j = (int) (plaintext[i/8] >> (7-(i%8))) & 0x01;
if (j==1)
j = -1;
#if DES_BS_VECTOR
for (k=0; k<DES_BS_VECTOR_SIZE; k++)
#endif
DES_bs_P[i]INDX = j;
}
}
|
GB_unop__bnot_int32_int32.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_int32_int32)
// op(A') function: GB (_unop_tran__bnot_int32_int32)
// C type: int32_t
// A type: int32_t
// cast: int32_t cij = aij
// unaryop: cij = ~(aij)
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
int32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = ~(x) ;
// casting
#define GB_CAST(z, aij) \
int32_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int32_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_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__bnot_int32_int32)
(
int32_t *Cx, // Cx and Ax may be aliased
const int32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// 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 (int32_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int32_t aij = Ax [p] ;
int32_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 ;
int32_t aij = Ax [p] ;
int32_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_int32_int32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__asinh_fp32_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef 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__asinh_fp32_fp32)
// op(A') function: GB (_unop_tran__asinh_fp32_fp32)
// C type: float
// A type: float
// cast: float cij = aij
// unaryop: cij = asinhf (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 = asinhf (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] = asinhf (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ASINH || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__asinh_fp32_fp32)
(
float *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
float aij = Ax [p] ;
float z = aij ;
Cx [p] = asinhf (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
float z = aij ;
Cx [p] = asinhf (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__asinh_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
|
quantize.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE %
% Q Q U U A A NN N T I ZZ E %
% Q Q U U AAAAA N N N T I ZZZ EEEEE %
% Q QQ U U A A N NN T I ZZ E %
% QQQQ UUU A A N N T IIIII ZZZZZ EEEEE %
% %
% %
% MagickCore Methods to Reduce the Number of Unique Colors in an Image %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Realism in computer graphics typically requires using 24 bits/pixel to
% generate an image. Yet many graphic display devices do not contain the
% amount of memory necessary to match the spatial and color resolution of
% the human eye. The Quantize methods takes a 24 bit image and reduces
% the number of colors so it can be displayed on raster device with less
% bits per pixel. In most instances, the quantized image closely
% resembles the original reference image.
%
% A reduction of colors in an image is also desirable for image
% transmission and real-time animation.
%
% QuantizeImage() takes a standard RGB or monochrome images and quantizes
% them down to some fixed number of colors.
%
% For purposes of color allocation, an image is a set of n pixels, where
% each pixel is a point in RGB space. RGB space is a 3-dimensional
% vector space, and each pixel, Pi, is defined by an ordered triple of
% red, green, and blue coordinates, (Ri, Gi, Bi).
%
% Each primary color component (red, green, or blue) represents an
% intensity which varies linearly from 0 to a maximum value, Cmax, which
% corresponds to full saturation of that color. Color allocation is
% defined over a domain consisting of the cube in RGB space with opposite
% vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax =
% 255.
%
% The algorithm maps this domain onto a tree in which each node
% represents a cube within that domain. In the following discussion
% these cubes are defined by the coordinate of two opposite vertices (vertex
% nearest the origin in RGB space and the vertex farthest from the origin).
%
% The tree's root node represents the entire domain, (0,0,0) through
% (Cmax,Cmax,Cmax). Each lower level in the tree is generated by
% subdividing one node's cube into eight smaller cubes of equal size.
% This corresponds to bisecting the parent cube with planes passing
% through the midpoints of each edge.
%
% The basic algorithm operates in three phases: Classification,
% Reduction, and Assignment. Classification builds a color description
% tree for the image. Reduction collapses the tree until the number it
% represents, at most, the number of colors desired in the output image.
% Assignment defines the output image's color map and sets each pixel's
% color by restorage_class in the reduced tree. Our goal is to minimize
% the numerical discrepancies between the original colors and quantized
% colors (quantization error).
%
% Classification begins by initializing a color description tree of
% sufficient depth to represent each possible input color in a leaf.
% However, it is impractical to generate a fully-formed color description
% tree in the storage_class phase for realistic values of Cmax. If
% colors components in the input image are quantized to k-bit precision,
% so that Cmax= 2k-1, the tree would need k levels below the root node to
% allow representing each possible input color in a leaf. This becomes
% prohibitive because the tree's total number of nodes is 1 +
% sum(i=1, k, 8k).
%
% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
% Initializes data structures for nodes only as they are needed; (2)
% Chooses a maximum depth for the tree as a function of the desired
% number of colors in the output image (currently log2(colormap size)).
%
% For each pixel in the input image, storage_class scans downward from
% the root of the color description tree. At each level of the tree it
% identifies the single node which represents a cube in RGB space
% containing the pixel's color. It updates the following data for each
% such node:
%
% n1: Number of pixels whose color is contained in the RGB cube which
% this node represents;
%
% n2: Number of pixels whose color is not represented in a node at
% lower depth in the tree; initially, n2 = 0 for all nodes except
% leaves of the tree.
%
% Sr, Sg, Sb: Sums of the red, green, and blue component values for all
% pixels not classified at a lower depth. The combination of these sums
% and n2 will ultimately characterize the mean color of a set of pixels
% represented by this node.
%
% E: the distance squared in RGB space between each pixel contained
% within a node and the nodes' center. This represents the
% quantization error for a node.
%
% Reduction repeatedly prunes the tree until the number of nodes with n2
% > 0 is less than or equal to the maximum number of colors allowed in
% the output image. On any given iteration over the tree, it selects
% those nodes whose E count is minimal for pruning and merges their color
% statistics upward. It uses a pruning threshold, Ep, to govern node
% selection as follows:
%
% Ep = 0
% while number of nodes with (n2 > 0) > required maximum number of colors
% prune all nodes such that E <= Ep
% Set Ep to minimum E in remaining nodes
%
% This has the effect of minimizing any quantization error when merging
% two nodes together.
%
% When a node to be pruned has offspring, the pruning procedure invokes
% itself recursively in order to prune the tree from the leaves upward.
% n2, Sr, Sg, and Sb in a node being pruned are always added to the
% corresponding data in that node's parent. This retains the pruned
% node's color characteristics for later averaging.
%
% For each node, n2 pixels exist for which that node represents the
% smallest volume in RGB space containing those pixel's colors. When n2
% > 0 the node will uniquely define a color in the output image. At the
% beginning of reduction, n2 = 0 for all nodes except a the leaves of
% the tree which represent colors present in the input image.
%
% The other pixel count, n1, indicates the total number of colors within
% the cubic volume which the node represents. This includes n1 - n2
% pixels whose colors should be defined by nodes at a lower level in the
% tree.
%
% Assignment generates the output image from the pruned tree. The output
% image consists of two parts: (1) A color map, which is an array of
% color descriptions (RGB triples) for each color present in the output
% image; (2) A pixel array, which represents each pixel as an index
% into the color map array.
%
% First, the assignment phase makes one pass over the pruned color
% description tree to establish the image's color map. For each node
% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
% color of all pixels that classify no lower than this node. Each of
% these colors becomes an entry in the color map.
%
% Finally, the assignment phase reclassifies each pixel in the pruned
% tree to identify the deepest node containing the pixel's color. The
% pixel's value in the pixel array becomes the index of this node's mean
% color in the color map.
%
% This method is based on a similar algorithm written by Paul Raveling.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/compare.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/histogram.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
/*
Define declarations.
*/
#if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE)
#define CacheShift 2
#else
#define CacheShift 3
#endif
#define ErrorQueueLength 16
#define MaxNodes 266817
#define MaxTreeDepth 8
#define NodesInAList 1920
/*
Typdef declarations.
*/
typedef struct _DoublePixelPacket
{
double
red,
green,
blue,
alpha;
} DoublePixelPacket;
typedef struct _NodeInfo
{
struct _NodeInfo
*parent,
*child[16];
MagickSizeType
number_unique;
DoublePixelPacket
total_color;
double
quantize_error;
size_t
color_number,
id,
level;
} NodeInfo;
typedef struct _Nodes
{
NodeInfo
*nodes;
struct _Nodes
*next;
} Nodes;
typedef struct _CubeInfo
{
NodeInfo
*root;
size_t
colors,
maximum_colors;
ssize_t
transparent_index;
MagickSizeType
transparent_pixels;
DoublePixelPacket
target;
double
distance,
pruning_threshold,
next_threshold;
size_t
nodes,
free_nodes,
color_number;
NodeInfo
*next_node;
Nodes
*node_queue;
MemoryInfo
*memory_info;
ssize_t
*cache;
DoublePixelPacket
error[ErrorQueueLength];
double
weights[ErrorQueueLength];
QuantizeInfo
*quantize_info;
MagickBooleanType
associate_alpha;
ssize_t
x,
y;
size_t
depth;
MagickOffsetType
offset;
MagickSizeType
span;
} CubeInfo;
/*
Method prototypes.
*/
static CubeInfo
*GetCubeInfo(const QuantizeInfo *,const size_t,const size_t);
static NodeInfo
*GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *);
static MagickBooleanType
AssignImageColors(Image *,CubeInfo *,ExceptionInfo *),
ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *),
DitherImage(Image *,CubeInfo *,ExceptionInfo *),
SetGrayscaleImage(Image *,ExceptionInfo *),
SetImageColormap(Image *,CubeInfo *,ExceptionInfo *);
static void
ClosestColor(const Image *,CubeInfo *,const NodeInfo *),
DefineImageColormap(Image *,CubeInfo *,NodeInfo *),
DestroyCubeInfo(CubeInfo *),
PruneLevel(CubeInfo *,const NodeInfo *),
PruneToCubeDepth(CubeInfo *,const NodeInfo *),
ReduceImageColors(const Image *,CubeInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireQuantizeInfo() allocates the QuantizeInfo structure.
%
% The format of the AcquireQuantizeInfo method is:
%
% QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
*/
MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info)
{
QuantizeInfo
*quantize_info;
quantize_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*quantize_info));
GetQuantizeInfo(quantize_info);
if (image_info != (ImageInfo *) NULL)
{
const char
*option;
quantize_info->dither_method=image_info->dither == MagickFalse ?
NoDitherMethod : RiemersmaDitherMethod;
option=GetImageOption(image_info,"dither");
if (option != (const char *) NULL)
quantize_info->dither_method=(DitherMethod) ParseCommandOption(
MagickDitherOptions,MagickFalse,option);
quantize_info->measure_error=image_info->verbose;
}
return(quantize_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A s s i g n I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AssignImageColors() generates the output image from the pruned tree. The
% output image consists of two parts: (1) A color map, which is an array
% of color descriptions (RGB triples) for each color present in the
% output image; (2) A pixel array, which represents each pixel as an
% index into the color map array.
%
% First, the assignment phase makes one pass over the pruned color
% description tree to establish the image's color map. For each node
% with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean
% color of all pixels that classify no lower than this node. Each of
% these colors becomes an entry in the color map.
%
% Finally, the assignment phase reclassifies each pixel in the pruned
% tree to identify the deepest node containing the pixel's color. The
% pixel's value in the pixel array becomes the index of this node's mean
% color in the color map.
%
% The format of the AssignImageColors() method is:
%
% MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
*/
static inline void AssociateAlphaPixel(const Image *image,
const CubeInfo *cube_info,const Quantum *pixel,DoublePixelPacket *alpha_pixel)
{
double
alpha;
if ((cube_info->associate_alpha == MagickFalse) ||
(GetPixelAlpha(image,pixel) == OpaqueAlpha))
{
alpha_pixel->red=(double) GetPixelRed(image,pixel);
alpha_pixel->green=(double) GetPixelGreen(image,pixel);
alpha_pixel->blue=(double) GetPixelBlue(image,pixel);
alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
return;
}
alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel));
alpha_pixel->red=alpha*GetPixelRed(image,pixel);
alpha_pixel->green=alpha*GetPixelGreen(image,pixel);
alpha_pixel->blue=alpha*GetPixelBlue(image,pixel);
alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel);
}
static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info,
const PixelInfo *pixel,DoublePixelPacket *alpha_pixel)
{
double
alpha;
if ((cube_info->associate_alpha == MagickFalse) ||
(pixel->alpha == OpaqueAlpha))
{
alpha_pixel->red=(double) pixel->red;
alpha_pixel->green=(double) pixel->green;
alpha_pixel->blue=(double) pixel->blue;
alpha_pixel->alpha=(double) pixel->alpha;
return;
}
alpha=(double) (QuantumScale*pixel->alpha);
alpha_pixel->red=alpha*pixel->red;
alpha_pixel->green=alpha*pixel->green;
alpha_pixel->blue=alpha*pixel->blue;
alpha_pixel->alpha=(double) pixel->alpha;
}
static inline size_t ColorToNodeId(const CubeInfo *cube_info,
const DoublePixelPacket *pixel,size_t index)
{
size_t
id;
id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) |
((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 |
((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2);
if (cube_info->associate_alpha != MagickFalse)
id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3;
return(id);
}
static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info,
ExceptionInfo *exception)
{
#define AssignImageTag "Assign/Image"
ColorspaceType
colorspace;
ssize_t
y;
/*
Allocate image colormap.
*/
colorspace=image->colorspace;
if (cube_info->quantize_info->colorspace != UndefinedColorspace)
(void) TransformImageColorspace(image,cube_info->quantize_info->colorspace,
exception);
cube_info->transparent_pixels=0;
cube_info->transparent_index=(-1);
if (SetImageColormap(image,cube_info,exception) == MagickFalse)
return(MagickFalse);
/*
Create a reduced color image.
*/
if (cube_info->quantize_info->dither_method != NoDitherMethod)
(void) DitherImage(image,cube_info,exception);
else
{
CacheView
*image_view;
MagickBooleanType
status;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
CubeInfo
cube;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
count;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
cube=(*cube_info);
for (x=0; x < (ssize_t) image->columns; x+=count)
{
DoublePixelPacket
pixel;
register const NodeInfo
*node_info;
register ssize_t
i;
size_t
id,
index;
/*
Identify the deepest node containing the pixel's color.
*/
for (count=1; (x+count) < (ssize_t) image->columns; count++)
{
PixelInfo
packet;
GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet);
if (IsPixelEquivalent(image,q,&packet) == MagickFalse)
break;
}
AssociateAlphaPixel(image,&cube,q,&pixel);
node_info=cube.root;
for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
{
id=ColorToNodeId(&cube,&pixel,index);
if (node_info->child[id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[id];
}
/*
Find closest color among siblings and their children.
*/
cube.target=pixel;
cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1.0);
ClosestColor(image,&cube,node_info->parent);
index=cube.color_number;
for (i=0; i < (ssize_t) count; i++)
{
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) index,q);
if (cube.quantize_info->measure_error == MagickFalse)
{
SetPixelRed(image,ClampToQuantum(
image->colormap[index].red),q);
SetPixelGreen(image,ClampToQuantum(
image->colormap[index].green),q);
SetPixelBlue(image,ClampToQuantum(
image->colormap[index].blue),q);
if (cube.associate_alpha != MagickFalse)
SetPixelAlpha(image,ClampToQuantum(
image->colormap[index].alpha),q);
}
q+=GetPixelChannels(image);
}
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
}
if (cube_info->quantize_info->measure_error != MagickFalse)
(void) GetImageQuantizeError(image,exception);
if ((cube_info->quantize_info->number_colors == 2) &&
((cube_info->quantize_info->colorspace == LinearGRAYColorspace) ||
(cube_info->quantize_info->colorspace == GRAYColorspace)))
{
double
intensity;
/*
Monochrome image.
*/
intensity=GetPixelInfoLuma(image->colormap+0) < QuantumRange/2.0 ? 0.0 :
QuantumRange;
if (image->colors > 1)
{
intensity=0.0;
if (GetPixelInfoLuma(image->colormap+0) >
GetPixelInfoLuma(image->colormap+1))
intensity=(double) QuantumRange;
}
image->colormap[0].red=intensity;
image->colormap[0].green=intensity;
image->colormap[0].blue=intensity;
if (image->colors > 1)
{
image->colormap[1].red=(double) QuantumRange-intensity;
image->colormap[1].green=(double) QuantumRange-intensity;
image->colormap[1].blue=(double) QuantumRange-intensity;
}
}
(void) SyncImage(image,exception);
if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
(IssRGBCompatibleColorspace(colorspace) == MagickFalse))
(void) TransformImageColorspace(image,colorspace,exception);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l a s s i f y I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClassifyImageColors() begins by initializing a color description tree
% of sufficient depth to represent each possible input color in a leaf.
% However, it is impractical to generate a fully-formed color
% description tree in the storage_class phase for realistic values of
% Cmax. If colors components in the input image are quantized to k-bit
% precision, so that Cmax= 2k-1, the tree would need k levels below the
% root node to allow representing each possible input color in a leaf.
% This becomes prohibitive because the tree's total number of nodes is
% 1 + sum(i=1,k,8k).
%
% A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255.
% Therefore, to avoid building a fully populated tree, QUANTIZE: (1)
% Initializes data structures for nodes only as they are needed; (2)
% Chooses a maximum depth for the tree as a function of the desired
% number of colors in the output image (currently log2(colormap size)).
%
% For each pixel in the input image, storage_class scans downward from
% the root of the color description tree. At each level of the tree it
% identifies the single node which represents a cube in RGB space
% containing It updates the following data for each such node:
%
% n1 : Number of pixels whose color is contained in the RGB cube
% which this node represents;
%
% n2 : Number of pixels whose color is not represented in a node at
% lower depth in the tree; initially, n2 = 0 for all nodes except
% leaves of the tree.
%
% Sr, Sg, Sb : Sums of the red, green, and blue component values for
% all pixels not classified at a lower depth. The combination of
% these sums and n2 will ultimately characterize the mean color of a
% set of pixels represented by this node.
%
% E: the distance squared in RGB space between each pixel contained
% within a node and the nodes' center. This represents the quantization
% error for a node.
%
% The format of the ClassifyImageColors() method is:
%
% MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
% const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o image: the image.
%
*/
static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info)
{
MagickBooleanType
associate_alpha;
associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue :
MagickFalse;
if ((cube_info->quantize_info->number_colors == 2) &&
((cube_info->quantize_info->colorspace == LinearGRAYColorspace) ||
(cube_info->quantize_info->colorspace == GRAYColorspace)))
associate_alpha=MagickFalse;
cube_info->associate_alpha=associate_alpha;
}
static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info,
const Image *image,ExceptionInfo *exception)
{
#define ClassifyImageTag "Classify/Image"
CacheView
*image_view;
DoublePixelPacket
error,
mid,
midpoint,
pixel;
MagickBooleanType
proceed;
double
bisect;
NodeInfo
*node_info;
size_t
count,
id,
index,
level;
ssize_t
y;
/*
Classify the first cube_info->maximum_colors colors to a tree depth of 8.
*/
SetAssociatedAlpha(image,cube_info);
if (cube_info->quantize_info->colorspace != image->colorspace)
{
if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
(cube_info->quantize_info->colorspace != CMYKColorspace))
(void) TransformImageColorspace((Image *) image,
cube_info->quantize_info->colorspace,exception);
else
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace((Image *) image,sRGBColorspace,
exception);
}
midpoint.red=(double) QuantumRange/2.0;
midpoint.green=(double) QuantumRange/2.0;
midpoint.blue=(double) QuantumRange/2.0;
midpoint.alpha=(double) QuantumRange/2.0;
error.alpha=0.0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (cube_info->nodes > MaxNodes)
{
/*
Prune one level if the color tree is too large.
*/
PruneLevel(cube_info,cube_info->root);
cube_info->depth--;
}
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
{
/*
Start at the root and descend the color cube tree.
*/
for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
{
PixelInfo
packet;
GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
break;
}
AssociateAlphaPixel(image,cube_info,p,&pixel);
index=MaxTreeDepth-1;
bisect=((double) QuantumRange+1.0)/2.0;
mid=midpoint;
node_info=cube_info->root;
for (level=1; level <= MaxTreeDepth; level++)
{
double
distance;
bisect*=0.5;
id=ColorToNodeId(cube_info,&pixel,index);
mid.red+=(id & 1) != 0 ? bisect : -bisect;
mid.green+=(id & 2) != 0 ? bisect : -bisect;
mid.blue+=(id & 4) != 0 ? bisect : -bisect;
mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
if (node_info->child[id] == (NodeInfo *) NULL)
{
/*
Set colors of new node to contain pixel.
*/
node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
if (node_info->child[id] == (NodeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
continue;
}
if (level == MaxTreeDepth)
cube_info->colors++;
}
/*
Approximate the quantization error represented by this node.
*/
node_info=node_info->child[id];
error.red=QuantumScale*(pixel.red-mid.red);
error.green=QuantumScale*(pixel.green-mid.green);
error.blue=QuantumScale*(pixel.blue-mid.blue);
if (cube_info->associate_alpha != MagickFalse)
error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
distance=(double) (error.red*error.red+error.green*error.green+
error.blue*error.blue+error.alpha*error.alpha);
if (IsNaN(distance) != 0)
distance=0.0;
node_info->quantize_error+=count*sqrt(distance);
cube_info->root->quantize_error+=node_info->quantize_error;
index--;
}
/*
Sum RGB for this leaf for later derivation of the mean cube color.
*/
node_info->number_unique+=count;
node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
if (cube_info->associate_alpha != MagickFalse)
node_info->total_color.alpha+=count*QuantumScale*
ClampPixel(pixel.alpha);
else
node_info->total_color.alpha+=count*QuantumScale*
ClampPixel((MagickRealType) OpaqueAlpha);
p+=count*GetPixelChannels(image);
}
if (cube_info->colors > cube_info->maximum_colors)
{
PruneToCubeDepth(cube_info,cube_info->root);
break;
}
proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
break;
}
for (y++; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (cube_info->nodes > MaxNodes)
{
/*
Prune one level if the color tree is too large.
*/
PruneLevel(cube_info,cube_info->root);
cube_info->depth--;
}
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count)
{
/*
Start at the root and descend the color cube tree.
*/
for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++)
{
PixelInfo
packet;
GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet);
if (IsPixelEquivalent(image,p,&packet) == MagickFalse)
break;
}
AssociateAlphaPixel(image,cube_info,p,&pixel);
index=MaxTreeDepth-1;
bisect=((double) QuantumRange+1.0)/2.0;
mid=midpoint;
node_info=cube_info->root;
for (level=1; level <= cube_info->depth; level++)
{
double
distance;
bisect*=0.5;
id=ColorToNodeId(cube_info,&pixel,index);
mid.red+=(id & 1) != 0 ? bisect : -bisect;
mid.green+=(id & 2) != 0 ? bisect : -bisect;
mid.blue+=(id & 4) != 0 ? bisect : -bisect;
mid.alpha+=(id & 8) != 0 ? bisect : -bisect;
if (node_info->child[id] == (NodeInfo *) NULL)
{
/*
Set colors of new node to contain pixel.
*/
node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info);
if (node_info->child[id] == (NodeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","%s",
image->filename);
continue;
}
if (level == cube_info->depth)
cube_info->colors++;
}
/*
Approximate the quantization error represented by this node.
*/
node_info=node_info->child[id];
error.red=QuantumScale*(pixel.red-mid.red);
error.green=QuantumScale*(pixel.green-mid.green);
error.blue=QuantumScale*(pixel.blue-mid.blue);
if (cube_info->associate_alpha != MagickFalse)
error.alpha=QuantumScale*(pixel.alpha-mid.alpha);
distance=(double) (error.red*error.red+error.green*error.green+
error.blue*error.blue+error.alpha*error.alpha);
if (IsNaN(distance) != 0)
distance=0.0;
node_info->quantize_error+=count*sqrt(distance);
cube_info->root->quantize_error+=node_info->quantize_error;
index--;
}
/*
Sum RGB for this leaf for later derivation of the mean cube color.
*/
node_info->number_unique+=count;
node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red);
node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green);
node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue);
if (cube_info->associate_alpha != MagickFalse)
node_info->total_color.alpha+=count*QuantumScale*
ClampPixel(pixel.alpha);
else
node_info->total_color.alpha+=count*QuantumScale*
ClampPixel((MagickRealType) OpaqueAlpha);
p+=count*GetPixelChannels(image);
}
proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
break;
}
image_view=DestroyCacheView(image_view);
if (cube_info->quantize_info->colorspace != image->colorspace)
if ((cube_info->quantize_info->colorspace != UndefinedColorspace) &&
(cube_info->quantize_info->colorspace != CMYKColorspace))
(void) TransformImageColorspace((Image *) image,sRGBColorspace,exception);
return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneQuantizeInfo() makes a duplicate of the given quantize info structure,
% or if quantize info is NULL, a new one.
%
% The format of the CloneQuantizeInfo method is:
%
% QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o clone_info: Method CloneQuantizeInfo returns a duplicate of the given
% quantize info, or if image info is NULL a new one.
%
% o quantize_info: a structure of type info.
%
*/
MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info)
{
QuantizeInfo
*clone_info;
clone_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*clone_info));
GetQuantizeInfo(clone_info);
if (quantize_info == (QuantizeInfo *) NULL)
return(clone_info);
clone_info->number_colors=quantize_info->number_colors;
clone_info->tree_depth=quantize_info->tree_depth;
clone_info->dither_method=quantize_info->dither_method;
clone_info->colorspace=quantize_info->colorspace;
clone_info->measure_error=quantize_info->measure_error;
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o s e s t C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClosestColor() traverses the color cube tree at a particular node and
% determines which colormap entry best represents the input color.
%
% The format of the ClosestColor method is:
%
% void ClosestColor(const Image *image,CubeInfo *cube_info,
% const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: the address of a structure of type NodeInfo which points to a
% node in the color cube tree that is to be pruned.
%
*/
static void ClosestColor(const Image *image,CubeInfo *cube_info,
const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
ClosestColor(image,cube_info,node_info->child[i]);
if (node_info->number_unique != 0)
{
double
pixel;
register double
alpha,
beta,
distance;
register DoublePixelPacket
*magick_restrict q;
register PixelInfo
*magick_restrict p;
/*
Determine if this color is "closest".
*/
p=image->colormap+node_info->color_number;
q=(&cube_info->target);
alpha=1.0;
beta=1.0;
if (cube_info->associate_alpha != MagickFalse)
{
alpha=(double) (QuantumScale*p->alpha);
beta=(double) (QuantumScale*q->alpha);
}
pixel=alpha*p->red-beta*q->red;
distance=pixel*pixel;
if (distance <= cube_info->distance)
{
pixel=alpha*p->green-beta*q->green;
distance+=pixel*pixel;
if (distance <= cube_info->distance)
{
pixel=alpha*p->blue-beta*q->blue;
distance+=pixel*pixel;
if (distance <= cube_info->distance)
{
if (cube_info->associate_alpha != MagickFalse)
{
pixel=p->alpha-q->alpha;
distance+=pixel*pixel;
}
if (distance <= cube_info->distance)
{
cube_info->distance=distance;
cube_info->color_number=node_info->color_number;
}
}
}
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p r e s s I m a g e C o l o r m a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CompressImageColormap() compresses an image colormap by removing any
% duplicate or unused color entries.
%
% The format of the CompressImageColormap method is:
%
% MagickBooleanType CompressImageColormap(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType CompressImageColormap(Image *image,
ExceptionInfo *exception)
{
QuantizeInfo
quantize_info;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (IsPaletteImage(image) == MagickFalse)
return(MagickFalse);
GetQuantizeInfo(&quantize_info);
quantize_info.number_colors=image->colors;
quantize_info.tree_depth=MaxTreeDepth;
return(QuantizeImage(&quantize_info,image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f i n e I m a g e C o l o r m a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefineImageColormap() traverses the color cube tree and notes each colormap
% entry. A colormap entry is any node in the color cube tree where the
% of unique colors is not zero.
%
% The format of the DefineImageColormap method is:
%
% void DefineImageColormap(Image *image,CubeInfo *cube_info,
% NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: the address of a structure of type NodeInfo which points to a
% node in the color cube tree that is to be pruned.
%
*/
static void DefineImageColormap(Image *image,CubeInfo *cube_info,
NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
DefineImageColormap(image,cube_info,node_info->child[i]);
if (node_info->number_unique != 0)
{
register double
alpha;
register PixelInfo
*magick_restrict q;
/*
Colormap entry is defined by the mean color in this cube.
*/
q=image->colormap+image->colors;
alpha=(double) ((MagickOffsetType) node_info->number_unique);
alpha=PerceptibleReciprocal(alpha);
if (cube_info->associate_alpha == MagickFalse)
{
q->red=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.red);
q->green=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.green);
q->blue=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.blue);
q->alpha=(double) OpaqueAlpha;
}
else
{
double
opacity;
opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha);
q->alpha=(double) ClampToQuantum(opacity);
if (q->alpha == OpaqueAlpha)
{
q->red=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.red);
q->green=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.green);
q->blue=(double) ClampToQuantum(alpha*QuantumRange*
node_info->total_color.blue);
}
else
{
double
gamma;
gamma=(double) (QuantumScale*q->alpha);
gamma=PerceptibleReciprocal(gamma);
q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange*
node_info->total_color.red);
q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange*
node_info->total_color.green);
q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange*
node_info->total_color.blue);
if (node_info->number_unique > cube_info->transparent_pixels)
{
cube_info->transparent_pixels=node_info->number_unique;
cube_info->transparent_index=(ssize_t) image->colors;
}
}
}
node_info->color_number=image->colors++;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y C u b e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyCubeInfo() deallocates memory associated with an image.
%
% The format of the DestroyCubeInfo method is:
%
% DestroyCubeInfo(CubeInfo *cube_info)
%
% A description of each parameter follows:
%
% o cube_info: the address of a structure of type CubeInfo.
%
*/
static void DestroyCubeInfo(CubeInfo *cube_info)
{
register Nodes
*nodes;
/*
Release color cube tree storage.
*/
do
{
nodes=cube_info->node_queue->next;
cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory(
cube_info->node_queue->nodes);
cube_info->node_queue=(Nodes *) RelinquishMagickMemory(
cube_info->node_queue);
cube_info->node_queue=nodes;
} while (cube_info->node_queue != (Nodes *) NULL);
if (cube_info->memory_info != (MemoryInfo *) NULL)
cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info);
cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info);
cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo
% structure.
%
% The format of the DestroyQuantizeInfo method is:
%
% QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
*/
MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(quantize_info != (QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickCoreSignature);
quantize_info->signature=(~MagickCoreSignature);
quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info);
return(quantize_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DitherImage() distributes the difference between an original image and
% the corresponding color reduced algorithm to neighboring pixels using
% serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns
% MagickTrue if the image is dithered otherwise MagickFalse.
%
% The format of the DitherImage method is:
%
% MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static DoublePixelPacket **DestroyPixelThreadSet(DoublePixelPacket **pixels)
{
register ssize_t
i;
assert(pixels != (DoublePixelPacket **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (DoublePixelPacket *) NULL)
pixels[i]=(DoublePixelPacket *) RelinquishMagickMemory(pixels[i]);
pixels=(DoublePixelPacket **) RelinquishMagickMemory(pixels);
return(pixels);
}
static DoublePixelPacket **AcquirePixelThreadSet(const size_t count)
{
DoublePixelPacket
**pixels;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(DoublePixelPacket **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (DoublePixelPacket **) NULL)
return((DoublePixelPacket **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(DoublePixelPacket *) AcquireQuantumMemory(count,2*
sizeof(**pixels));
if (pixels[i] == (DoublePixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
}
return(pixels);
}
static inline ssize_t CacheOffset(CubeInfo *cube_info,
const DoublePixelPacket *pixel)
{
#define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift)))
#define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift)))
#define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift)))
#define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift)))
ssize_t
offset;
offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) |
GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) |
BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue))));
if (cube_info->associate_alpha != MagickFalse)
offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha)));
return(offset);
}
static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info,
ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
CacheView
*image_view;
const char
*artifact;
double
amount;
DoublePixelPacket
**pixels;
MagickBooleanType
status;
ssize_t
y;
/*
Distribute quantization error using Floyd-Steinberg.
*/
pixels=AcquirePixelThreadSet(image->columns);
if (pixels == (DoublePixelPacket **) NULL)
return(MagickFalse);
status=MagickTrue;
amount=1.0;
artifact=GetImageArtifact(image,"dither:diffusion-amount");
if (artifact != (const char *) NULL)
amount=StringToDoubleInterval(artifact,1.0);
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
CubeInfo
cube;
DoublePixelPacket
*current,
*previous;
register Quantum
*magick_restrict q;
register ssize_t
x;
size_t
index;
ssize_t
v;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
cube=(*cube_info);
current=pixels[id]+(y & 0x01)*image->columns;
previous=pixels[id]+((y+1) & 0x01)*image->columns;
v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1);
for (x=0; x < (ssize_t) image->columns; x++)
{
DoublePixelPacket
color,
pixel;
register ssize_t
i;
ssize_t
u;
u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x;
AssociateAlphaPixel(image,&cube,q+u*GetPixelChannels(image),&pixel);
if (x > 0)
{
pixel.red+=7.0*amount*current[u-v].red/16;
pixel.green+=7.0*amount*current[u-v].green/16;
pixel.blue+=7.0*amount*current[u-v].blue/16;
if (cube.associate_alpha != MagickFalse)
pixel.alpha+=7.0*amount*current[u-v].alpha/16;
}
if (y > 0)
{
if (x < (ssize_t) (image->columns-1))
{
pixel.red+=previous[u+v].red/16;
pixel.green+=previous[u+v].green/16;
pixel.blue+=previous[u+v].blue/16;
if (cube.associate_alpha != MagickFalse)
pixel.alpha+=previous[u+v].alpha/16;
}
pixel.red+=5.0*amount*previous[u].red/16;
pixel.green+=5.0*amount*previous[u].green/16;
pixel.blue+=5.0*amount*previous[u].blue/16;
if (cube.associate_alpha != MagickFalse)
pixel.alpha+=5.0*amount*previous[u].alpha/16;
if (x > 0)
{
pixel.red+=3.0*amount*previous[u-v].red/16;
pixel.green+=3.0*amount*previous[u-v].green/16;
pixel.blue+=3.0*amount*previous[u-v].blue/16;
if (cube.associate_alpha != MagickFalse)
pixel.alpha+=3.0*amount*previous[u-v].alpha/16;
}
}
pixel.red=(double) ClampPixel(pixel.red);
pixel.green=(double) ClampPixel(pixel.green);
pixel.blue=(double) ClampPixel(pixel.blue);
if (cube.associate_alpha != MagickFalse)
pixel.alpha=(double) ClampPixel(pixel.alpha);
i=CacheOffset(&cube,&pixel);
if (cube.cache[i] < 0)
{
register NodeInfo
*node_info;
register size_t
node_id;
/*
Identify the deepest node containing the pixel's color.
*/
node_info=cube.root;
for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
{
node_id=ColorToNodeId(&cube,&pixel,index);
if (node_info->child[node_id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[node_id];
}
/*
Find closest color among siblings and their children.
*/
cube.target=pixel;
cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+
1.0);
ClosestColor(image,&cube,node_info->parent);
cube.cache[i]=(ssize_t) cube.color_number;
}
/*
Assign pixel to closest colormap entry.
*/
index=(size_t) cube.cache[i];
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) index,q+u*GetPixelChannels(image));
if (cube.quantize_info->measure_error == MagickFalse)
{
SetPixelRed(image,ClampToQuantum(image->colormap[index].red),
q+u*GetPixelChannels(image));
SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),
q+u*GetPixelChannels(image));
SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),
q+u*GetPixelChannels(image));
if (cube.associate_alpha != MagickFalse)
SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),
q+u*GetPixelChannels(image));
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
/*
Store the error.
*/
AssociateAlphaPixelInfo(&cube,image->colormap+index,&color);
current[u].red=pixel.red-color.red;
current[u].green=pixel.green-color.green;
current[u].blue=pixel.blue-color.blue;
if (cube.associate_alpha != MagickFalse)
current[u].alpha=pixel.alpha-color.alpha;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
}
image_view=DestroyCacheView(image_view);
pixels=DestroyPixelThreadSet(pixels);
return(MagickTrue);
}
static MagickBooleanType
RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int,
ExceptionInfo *);
static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info,
const size_t level,const unsigned int direction,ExceptionInfo *exception)
{
if (level == 1)
switch (direction)
{
case WestGravity:
{
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
break;
}
case EastGravity:
{
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
break;
}
case NorthGravity:
{
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
break;
}
case SouthGravity:
{
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
break;
}
default:
break;
}
else
switch (direction)
{
case WestGravity:
{
Riemersma(image,image_view,cube_info,level-1,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,SouthGravity,
exception);
break;
}
case EastGravity:
{
Riemersma(image,image_view,cube_info,level-1,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,NorthGravity,
exception);
break;
}
case NorthGravity:
{
Riemersma(image,image_view,cube_info,level-1,WestGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,EastGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,NorthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,EastGravity,
exception);
break;
}
case SouthGravity:
{
Riemersma(image,image_view,cube_info,level-1,EastGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,NorthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,WestGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,SouthGravity,
exception);
(void) RiemersmaDither(image,image_view,cube_info,SouthGravity,
exception);
Riemersma(image,image_view,cube_info,level-1,WestGravity,
exception);
break;
}
default:
break;
}
}
static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view,
CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
DoublePixelPacket
color,
pixel;
MagickBooleanType
proceed;
register CubeInfo
*p;
size_t
index;
p=cube_info;
if ((p->x >= 0) && (p->x < (ssize_t) image->columns) &&
(p->y >= 0) && (p->y < (ssize_t) image->rows))
{
register Quantum
*magick_restrict q;
register ssize_t
i;
/*
Distribute error.
*/
q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception);
if (q == (Quantum *) NULL)
return(MagickFalse);
AssociateAlphaPixel(image,cube_info,q,&pixel);
for (i=0; i < ErrorQueueLength; i++)
{
pixel.red+=p->weights[i]*p->error[i].red;
pixel.green+=p->weights[i]*p->error[i].green;
pixel.blue+=p->weights[i]*p->error[i].blue;
if (cube_info->associate_alpha != MagickFalse)
pixel.alpha+=p->weights[i]*p->error[i].alpha;
}
pixel.red=(double) ClampPixel(pixel.red);
pixel.green=(double) ClampPixel(pixel.green);
pixel.blue=(double) ClampPixel(pixel.blue);
if (cube_info->associate_alpha != MagickFalse)
pixel.alpha=(double) ClampPixel(pixel.alpha);
i=CacheOffset(cube_info,&pixel);
if (p->cache[i] < 0)
{
register NodeInfo
*node_info;
register size_t
id;
/*
Identify the deepest node containing the pixel's color.
*/
node_info=p->root;
for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--)
{
id=ColorToNodeId(cube_info,&pixel,index);
if (node_info->child[id] == (NodeInfo *) NULL)
break;
node_info=node_info->child[id];
}
/*
Find closest color among siblings and their children.
*/
p->target=pixel;
p->distance=(double) (4.0*(QuantumRange+1.0)*((double)
QuantumRange+1.0)+1.0);
ClosestColor(image,p,node_info->parent);
p->cache[i]=(ssize_t) p->color_number;
}
/*
Assign pixel to closest colormap entry.
*/
index=(size_t) p->cache[i];
if (image->storage_class == PseudoClass)
SetPixelIndex(image,(Quantum) index,q);
if (cube_info->quantize_info->measure_error == MagickFalse)
{
SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q);
if (cube_info->associate_alpha != MagickFalse)
SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
return(MagickFalse);
/*
Propagate the error as the last entry of the error queue.
*/
(void) memmove(p->error,p->error+1,(ErrorQueueLength-1)*
sizeof(p->error[0]));
AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color);
p->error[ErrorQueueLength-1].red=pixel.red-color.red;
p->error[ErrorQueueLength-1].green=pixel.green-color.green;
p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue;
if (cube_info->associate_alpha != MagickFalse)
p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha;
proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span);
if (proceed == MagickFalse)
return(MagickFalse);
p->offset++;
}
switch (direction)
{
case WestGravity: p->x--; break;
case EastGravity: p->x++; break;
case NorthGravity: p->y--; break;
case SouthGravity: p->y++; break;
}
return(MagickTrue);
}
static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
register ssize_t
i;
size_t
depth;
if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod)
return(FloydSteinbergDither(image,cube_info,exception));
/*
Distribute quantization error along a Hilbert curve.
*/
(void) memset(cube_info->error,0,ErrorQueueLength*sizeof(*cube_info->error));
cube_info->x=0;
cube_info->y=0;
i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows);
for (depth=1; i != 0; depth++)
i>>=1;
if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows))
depth++;
cube_info->offset=0;
cube_info->span=(MagickSizeType) image->columns*image->rows;
image_view=AcquireAuthenticCacheView(image,exception);
if (depth > 1)
Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception);
status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t C u b e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetCubeInfo() initialize the Cube data structure.
%
% The format of the GetCubeInfo method is:
%
% CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info,
% const size_t depth,const size_t maximum_colors)
%
% A description of each parameter follows.
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o depth: Normally, this integer value is zero or one. A zero or
% one tells Quantize to choose a optimal tree depth of Log4(number_colors).
% A tree of this depth generally allows the best representation of the
% reference image with the least amount of memory and the fastest
% computational speed. In some cases, such as an image with low color
% dispersion (a few number of colors), a value other than
% Log4(number_colors) is required. To expand the color tree completely,
% use a value of 8.
%
% o maximum_colors: maximum colors.
%
*/
static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info,
const size_t depth,const size_t maximum_colors)
{
CubeInfo
*cube_info;
double
sum,
weight;
register ssize_t
i;
size_t
length;
/*
Initialize tree to describe color cube_info.
*/
cube_info=(CubeInfo *) AcquireQuantumMemory(1,sizeof(*cube_info));
if (cube_info == (CubeInfo *) NULL)
return((CubeInfo *) NULL);
(void) memset(cube_info,0,sizeof(*cube_info));
cube_info->depth=depth;
if (cube_info->depth > MaxTreeDepth)
cube_info->depth=MaxTreeDepth;
if (cube_info->depth < 2)
cube_info->depth=2;
cube_info->maximum_colors=maximum_colors;
/*
Initialize root node.
*/
cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL);
if (cube_info->root == (NodeInfo *) NULL)
return((CubeInfo *) NULL);
cube_info->root->parent=cube_info->root;
cube_info->quantize_info=CloneQuantizeInfo(quantize_info);
if (cube_info->quantize_info->dither_method == NoDitherMethod)
return(cube_info);
/*
Initialize dither resources.
*/
length=(size_t) (1UL << (4*(8-CacheShift)));
cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache));
if (cube_info->memory_info == (MemoryInfo *) NULL)
return((CubeInfo *) NULL);
cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info);
/*
Initialize color cache.
*/
(void) memset(cube_info->cache,(-1),sizeof(*cube_info->cache)*length);
/*
Distribute weights along a curve of exponential decay.
*/
weight=1.0;
for (i=0; i < ErrorQueueLength; i++)
{
cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight);
weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0));
}
/*
Normalize the weighting factors.
*/
weight=0.0;
for (i=0; i < ErrorQueueLength; i++)
weight+=cube_info->weights[i];
sum=0.0;
for (i=0; i < ErrorQueueLength; i++)
{
cube_info->weights[i]/=weight;
sum+=cube_info->weights[i];
}
cube_info->weights[0]+=1.0-sum;
return(cube_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t N o d e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetNodeInfo() allocates memory for a new node in the color cube tree and
% presets all fields to zero.
%
% The format of the GetNodeInfo method is:
%
% NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
% const size_t level,NodeInfo *parent)
%
% A description of each parameter follows.
%
% o node: The GetNodeInfo method returns a pointer to a queue of nodes.
%
% o id: Specifies the child number of the node.
%
% o level: Specifies the level in the storage_class the node resides.
%
*/
static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id,
const size_t level,NodeInfo *parent)
{
NodeInfo
*node_info;
if (cube_info->free_nodes == 0)
{
Nodes
*nodes;
/*
Allocate a new queue of nodes.
*/
nodes=(Nodes *) AcquireQuantumMemory(1,sizeof(*nodes));
if (nodes == (Nodes *) NULL)
return((NodeInfo *) NULL);
nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList,
sizeof(*nodes->nodes));
if (nodes->nodes == (NodeInfo *) NULL)
return((NodeInfo *) NULL);
nodes->next=cube_info->node_queue;
cube_info->node_queue=nodes;
cube_info->next_node=nodes->nodes;
cube_info->free_nodes=NodesInAList;
}
cube_info->nodes++;
cube_info->free_nodes--;
node_info=cube_info->next_node++;
(void) memset(node_info,0,sizeof(*node_info));
node_info->parent=parent;
node_info->id=id;
node_info->level=level;
return(node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e Q u a n t i z e E r r o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageQuantizeError() measures the difference between the original
% and quantized images. This difference is the total quantization error.
% The error is computed by summing over all pixels in an image the distance
% squared in RGB space between each reference pixel value and its quantized
% value. These values are computed:
%
% o mean_error_per_pixel: This value is the mean error for any single
% pixel in the image.
%
% o normalized_mean_square_error: This value is the normalized mean
% quantization error for any single pixel in the image. This distance
% measure is normalized to a range between 0 and 1. It is independent
% of the range of red, green, and blue values in the image.
%
% o normalized_maximum_square_error: Thsi value is the normalized
% maximum quantization error for any single pixel in the image. This
% distance measure is normalized to a range between 0 and 1. It is
% independent of the range of red, green, and blue values in your image.
%
% The format of the GetImageQuantizeError method is:
%
% MagickBooleanType GetImageQuantizeError(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageQuantizeError(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
double
alpha,
area,
beta,
distance,
maximum_error,
mean_error,
mean_error_per_pixel;
ssize_t
index,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
image->total_colors=GetNumberColors(image,(FILE *) NULL,exception);
(void) memset(&image->error,0,sizeof(image->error));
if (image->storage_class == DirectClass)
return(MagickTrue);
alpha=1.0;
beta=1.0;
area=3.0*image->columns*image->rows;
maximum_error=0.0;
mean_error_per_pixel=0.0;
mean_error=0.0;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=(ssize_t) GetPixelIndex(image,p);
if (image->alpha_trait == BlendPixelTrait)
{
alpha=(double) (QuantumScale*GetPixelAlpha(image,p));
beta=(double) (QuantumScale*image->colormap[index].alpha);
}
distance=fabs((double) (alpha*GetPixelRed(image,p)-beta*
image->colormap[index].red));
mean_error_per_pixel+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta*
image->colormap[index].green));
mean_error_per_pixel+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
distance=fabs((double) (alpha*GetPixelBlue(image,p)-beta*
image->colormap[index].blue));
mean_error_per_pixel+=distance;
mean_error+=distance*distance;
if (distance > maximum_error)
maximum_error=distance;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area;
image->error.normalized_mean_error=(double) QuantumScale*QuantumScale*
mean_error/area;
image->error.normalized_maximum_error=(double) QuantumScale*maximum_error;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t Q u a n t i z e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetQuantizeInfo() initializes the QuantizeInfo structure.
%
% The format of the GetQuantizeInfo method is:
%
% GetQuantizeInfo(QuantizeInfo *quantize_info)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to a QuantizeInfo structure.
%
*/
MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(quantize_info != (QuantizeInfo *) NULL);
(void) memset(quantize_info,0,sizeof(*quantize_info));
quantize_info->number_colors=256;
quantize_info->dither_method=RiemersmaDitherMethod;
quantize_info->colorspace=UndefinedColorspace;
quantize_info->measure_error=MagickFalse;
quantize_info->signature=MagickCoreSignature;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% K m e a n s I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% KmeansImage() applies k-means color reduction to an image. This is a
% colorspace clustering or segmentation technique.
%
% The format of the KmeansImage method is:
%
% MagickBooleanType KmeansImage(Image *image,const size_t number_colors,
% const size_t max_iterations,const double tolerance,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o number_colors: number of colors to use as seeds.
%
% o max_iterations: maximum number of iterations while converging.
%
% o tolerance: the maximum tolerance.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _KmeansInfo
{
double
red,
green,
blue,
alpha,
black,
count,
distortion;
} KmeansInfo;
static KmeansInfo **DestroyKmeansThreadSet(KmeansInfo **kmeans_info)
{
register ssize_t
i;
assert(kmeans_info != (KmeansInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (kmeans_info[i] != (KmeansInfo *) NULL)
kmeans_info[i]=(KmeansInfo *) RelinquishMagickMemory(kmeans_info[i]);
kmeans_info=(KmeansInfo **) RelinquishMagickMemory(kmeans_info);
return(kmeans_info);
}
static KmeansInfo **AcquireKmeansThreadSet(const size_t number_colors)
{
KmeansInfo
**kmeans_info;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
kmeans_info=(KmeansInfo **) AcquireQuantumMemory(number_threads,
sizeof(*kmeans_info));
if (kmeans_info == (KmeansInfo **) NULL)
return((KmeansInfo **) NULL);
(void) memset(kmeans_info,0,number_threads*sizeof(*kmeans_info));
for (i=0; i < (ssize_t) number_threads; i++)
{
kmeans_info[i]=(KmeansInfo *) AcquireQuantumMemory(number_colors,
sizeof(**kmeans_info));
if (kmeans_info[i] == (KmeansInfo *) NULL)
return(DestroyKmeansThreadSet(kmeans_info));
}
return(kmeans_info);
}
static inline double KmeansMetric(const Image *magick_restrict image,
const Quantum *magick_restrict p,const PixelInfo *magick_restrict q)
{
register double
gamma,
metric,
pixel;
gamma=1.0;
metric=0.0;
if ((image->alpha_trait != UndefinedPixelTrait) ||
(q->alpha_trait != UndefinedPixelTrait))
{
pixel=GetPixelAlpha(image,p)-(q->alpha_trait != UndefinedPixelTrait ?
q->alpha : OpaqueAlpha);
metric+=pixel*pixel;
if (image->alpha_trait != UndefinedPixelTrait)
gamma*=QuantumScale*GetPixelAlpha(image,p);
if (q->alpha_trait != UndefinedPixelTrait)
gamma*=QuantumScale*q->alpha;
}
if (image->colorspace == CMYKColorspace)
{
pixel=QuantumScale*(GetPixelBlack(image,p)-q->black);
metric+=gamma*pixel*pixel;
gamma*=QuantumScale*(QuantumRange-GetPixelBlack(image,p));
gamma*=QuantumScale*(QuantumRange-q->black);
}
metric*=3.0;
pixel=QuantumScale*(GetPixelRed(image,p)-q->red);
if (IsHueCompatibleColorspace(image->colorspace) != MagickFalse)
{
if (fabs((double) pixel) > 0.5)
pixel-=0.5;
pixel*=2.0;
}
metric+=gamma*pixel*pixel;
pixel=QuantumScale*(GetPixelGreen(image,p)-q->green);
metric+=gamma*pixel*pixel;
pixel=QuantumScale*(GetPixelBlue(image,p)-q->blue);
metric+=gamma*pixel*pixel;
return(metric);
}
MagickExport MagickBooleanType KmeansImage(Image *image,
const size_t number_colors,const size_t max_iterations,const double tolerance,
ExceptionInfo *exception)
{
#define KmeansImageTag "Kmeans/Image"
#define RandomColorComponent(info) (QuantumRange*GetPseudoRandomValue(info))
CacheView
*image_view;
const char
*colors;
double
previous_tolerance;
KmeansInfo
**kmeans_pixels;
MagickBooleanType
verbose,
status;
register ssize_t
n;
size_t
number_threads;
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);
colors=GetImageArtifact(image,"kmeans:seed-colors");
if (colors == (const char *) NULL)
{
CubeInfo
*cube_info;
QuantizeInfo
*quantize_info;
size_t
colors,
depth;
/*
Seed clusters from color quantization.
*/
quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
quantize_info->colorspace=image->colorspace;
quantize_info->number_colors=number_colors;
quantize_info->dither_method=NoDitherMethod;
colors=number_colors;
for (depth=1; colors != 0; depth++)
colors>>=2;
cube_info=GetCubeInfo(quantize_info,depth,number_colors);
if (cube_info == (CubeInfo *) NULL)
{
quantize_info=DestroyQuantizeInfo(quantize_info);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
status=ClassifyImageColors(cube_info,image,exception);
if (status != MagickFalse)
{
if (cube_info->colors > cube_info->maximum_colors)
ReduceImageColors(image,cube_info);
status=SetImageColormap(image,cube_info,exception);
}
DestroyCubeInfo(cube_info);
quantize_info=DestroyQuantizeInfo(quantize_info);
if (status == MagickFalse)
return(status);
}
else
{
char
color[MagickPathExtent];
register const char
*p;
/*
Seed clusters from color list (e.g. red;green;blue).
*/
status=AcquireImageColormap(image,number_colors,exception);
if (status == MagickFalse)
return(status);
for (n=0, p=colors; n < (ssize_t) image->colors; n++)
{
register const char
*q;
for (q=p; *q != '\0'; q++)
if (*q == ';')
break;
(void) CopyMagickString(color,p,(size_t) MagickMin(q-p+1,
MagickPathExtent));
(void) QueryColorCompliance(color,AllCompliance,image->colormap+n,
exception);
if (*q == '\0')
{
n++;
break;
}
p=q+1;
}
if (n < (ssize_t) image->colors)
{
RandomInfo
*random_info;
/*
Seed clusters from random values.
*/
random_info=AcquireRandomInfo();
for ( ; n < (ssize_t) image->colors; n++)
{
(void) QueryColorCompliance("#000",AllCompliance,image->colormap+n,
exception);
image->colormap[n].red=RandomColorComponent(random_info);
image->colormap[n].green=RandomColorComponent(random_info);
image->colormap[n].blue=RandomColorComponent(random_info);
if (image->alpha_trait != BlendPixelTrait)
image->colormap[n].alpha=RandomColorComponent(random_info);
if (image->colorspace == CMYKColorspace)
image->colormap[n].black=RandomColorComponent(random_info);
}
random_info=DestroyRandomInfo(random_info);
}
}
/*
Iterative refinement.
*/
kmeans_pixels=AcquireKmeansThreadSet(number_colors);
if (kmeans_pixels == (KmeansInfo **) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
previous_tolerance=0.0;
verbose=IsStringTrue(GetImageArtifact(image,"debug"));
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
image_view=AcquireAuthenticCacheView(image,exception);
for (n=0; n < (ssize_t) max_iterations; n++)
{
double
distortion;
register ssize_t
i;
ssize_t
y;
for (i=0; i < (ssize_t) number_threads; i++)
(void) memset(kmeans_pixels[i],0,image->colors*sizeof(*kmeans_pixels[i]));
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
min_distance;
register ssize_t
i;
ssize_t
j;
/*
Assign each pixel whose mean has the least squared color distance.
*/
j=0;
min_distance=KmeansMetric(image,q,image->colormap+0);
for (i=1; i < (ssize_t) image->colors; i++)
{
double
distance;
if (min_distance <= MagickEpsilon)
break;
distance=KmeansMetric(image,q,image->colormap+i);
if (distance < min_distance)
{
min_distance=distance;
j=i;
}
}
kmeans_pixels[id][j].red+=QuantumScale*GetPixelRed(image,q);
kmeans_pixels[id][j].green+=QuantumScale*GetPixelGreen(image,q);
kmeans_pixels[id][j].blue+=QuantumScale*GetPixelBlue(image,q);
if (image->alpha_trait != BlendPixelTrait)
kmeans_pixels[id][j].alpha+=QuantumScale*GetPixelAlpha(image,q);
if (image->colorspace == CMYKColorspace)
kmeans_pixels[id][j].black+=QuantumScale*GetPixelBlack(image,q);
kmeans_pixels[id][j].count++;
kmeans_pixels[id][j].distortion+=min_distance;
SetPixelIndex(image,(Quantum) j,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
if (status == MagickFalse)
break;
/*
Reduce sums to [0] entry.
*/
for (i=1; i < (ssize_t) number_threads; i++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) image->colors; j++)
{
kmeans_pixels[0][j].red+=kmeans_pixels[i][j].red;
kmeans_pixels[0][j].green+=kmeans_pixels[i][j].green;
kmeans_pixels[0][j].blue+=kmeans_pixels[i][j].blue;
if (image->alpha_trait != BlendPixelTrait)
kmeans_pixels[0][j].alpha+=kmeans_pixels[i][j].alpha;
if (image->colorspace == CMYKColorspace)
kmeans_pixels[0][j].black+=kmeans_pixels[i][j].black;
kmeans_pixels[0][j].count+=kmeans_pixels[i][j].count;
kmeans_pixels[0][j].distortion+=kmeans_pixels[i][j].distortion;
}
}
/*
Calculate the new means (centroids) of the pixels in the new clusters.
*/
distortion=0.0;
for (i=0; i < (ssize_t) image->colors; i++)
{
double
gamma;
gamma=PerceptibleReciprocal((double) kmeans_pixels[0][i].count);
image->colormap[i].red=gamma*QuantumRange*kmeans_pixels[0][i].red;
image->colormap[i].green=gamma*QuantumRange*kmeans_pixels[0][i].green;
image->colormap[i].blue=gamma*QuantumRange*kmeans_pixels[0][i].blue;
if (image->alpha_trait != BlendPixelTrait)
image->colormap[i].alpha=gamma*QuantumRange*kmeans_pixels[0][i].alpha;
if (image->colorspace == CMYKColorspace)
image->colormap[i].black=gamma*QuantumRange*kmeans_pixels[0][i].black;
distortion+=kmeans_pixels[0][i].distortion;
}
if (verbose != MagickFalse)
(void) FormatLocaleFile(stderr,"distortion[%.20g]: %*g %*g\n",(double) n,
GetMagickPrecision(),distortion,GetMagickPrecision(),
fabs(distortion-previous_tolerance));
if (fabs(distortion-previous_tolerance) <= tolerance)
break;
previous_tolerance=distortion;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
proceed=SetImageProgress(image,KmeansImageTag,(MagickOffsetType) n,
max_iterations);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
kmeans_pixels=DestroyKmeansThreadSet(kmeans_pixels);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
(void) SetImageProgress(image,KmeansImageTag,(MagickOffsetType)
max_iterations-1,max_iterations);
if (status == MagickFalse)
return(status);
return(SyncImage(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P o s t e r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PosterizeImage() reduces the image to a limited number of colors for a
% "poster" effect.
%
% The format of the PosterizeImage method is:
%
% MagickBooleanType PosterizeImage(Image *image,const size_t levels,
% const DitherMethod dither_method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: Specifies a pointer to an Image structure.
%
% o levels: Number of color levels allowed in each channel. Very low values
% (2, 3, or 4) have the most visible effect.
%
% o dither_method: choose from UndefinedDitherMethod, NoDitherMethod,
% RiemersmaDitherMethod, FloydSteinbergDitherMethod.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickRound(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return(floor(x));
return(ceil(x));
}
MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels,
const DitherMethod dither_method,ExceptionInfo *exception)
{
#define PosterizeImageTag "Posterize/Image"
#define PosterizePixel(pixel) ClampToQuantum((MagickRealType) QuantumRange*( \
MagickRound(QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1))
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
QuantizeInfo
*quantize_info;
register ssize_t
i;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (image->storage_class == PseudoClass)
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->colors,1)
#endif
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Posterize colormap.
*/
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].red=(double)
PosterizePixel(image->colormap[i].red);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].green=(double)
PosterizePixel(image->colormap[i].green);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].blue=(double)
PosterizePixel(image->colormap[i].blue);
if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)
image->colormap[i].alpha=(double)
PosterizePixel(image->colormap[i].alpha);
}
/*
Posterize image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)
SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q);
if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)
SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q);
if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)
SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q);
if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q);
if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) &&
(image->alpha_trait == BlendPixelTrait))
SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,PosterizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL);
quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels*
levels,MaxColormapSize+1);
quantize_info->dither_method=dither_method;
quantize_info->tree_depth=MaxTreeDepth;
status=QuantizeImage(quantize_info,image,exception);
quantize_info=DestroyQuantizeInfo(quantize_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e C h i l d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneChild() deletes the given node and merges its statistics into its
% parent.
%
% The format of the PruneSubtree method is:
%
% PruneChild(CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
*/
static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info)
{
NodeInfo
*parent;
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
PruneChild(cube_info,node_info->child[i]);
/*
Merge color statistics into parent.
*/
parent=node_info->parent;
parent->number_unique+=node_info->number_unique;
parent->total_color.red+=node_info->total_color.red;
parent->total_color.green+=node_info->total_color.green;
parent->total_color.blue+=node_info->total_color.blue;
parent->total_color.alpha+=node_info->total_color.alpha;
parent->child[node_info->id]=(NodeInfo *) NULL;
cube_info->nodes--;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e L e v e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneLevel() deletes all nodes at the bottom level of the color tree merging
% their color statistics into their parent node.
%
% The format of the PruneLevel method is:
%
% PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
*/
static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
PruneLevel(cube_info,node_info->child[i]);
if (node_info->level == cube_info->depth)
PruneChild(cube_info,node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r u n e T o C u b e D e p t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PruneToCubeDepth() deletes any nodes at a depth greater than
% cube_info->depth while merging their color statistics into their parent
% node.
%
% The format of the PruneToCubeDepth method is:
%
% PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
*/
static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
PruneToCubeDepth(cube_info,node_info->child[i]);
if (node_info->level > cube_info->depth)
PruneChild(cube_info,node_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Q u a n t i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QuantizeImage() analyzes the colors within a reference image and chooses a
% fixed number of colors to represent the image. The goal of the algorithm
% is to minimize the color difference between the input and output image while
% minimizing the processing time.
%
% The format of the QuantizeImage method is:
%
% MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info,
Image *image,ExceptionInfo *exception)
{
CubeInfo
*cube_info;
MagickBooleanType
status;
size_t
depth,
maximum_colors;
assert(quantize_info != (const QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
maximum_colors=quantize_info->number_colors;
if (maximum_colors == 0)
maximum_colors=MaxColormapSize;
if (maximum_colors > MaxColormapSize)
maximum_colors=MaxColormapSize;
if (image->alpha_trait != BlendPixelTrait)
{
if (SetImageGray(image,exception) != MagickFalse)
(void) SetGrayscaleImage(image,exception);
}
depth=quantize_info->tree_depth;
if (depth == 0)
{
size_t
colors;
/*
Depth of color tree is: Log4(colormap size)+2.
*/
colors=maximum_colors;
for (depth=1; colors != 0; depth++)
colors>>=2;
if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2))
depth--;
if ((image->alpha_trait == BlendPixelTrait) && (depth > 5))
depth--;
if (SetImageGray(image,exception) != MagickFalse)
depth=MaxTreeDepth;
}
/*
Initialize color cube.
*/
cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ClassifyImageColors(cube_info,image,exception);
if (status != MagickFalse)
{
/*
Reduce the number of colors in the image.
*/
if (cube_info->colors > cube_info->maximum_colors)
ReduceImageColors(image,cube_info);
status=AssignImageColors(image,cube_info,exception);
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Q u a n t i z e I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QuantizeImages() analyzes the colors within a set of reference images and
% chooses a fixed number of colors to represent the set. The goal of the
% algorithm is to minimize the color difference between the input and output
% images while minimizing the processing time.
%
% The format of the QuantizeImages method is:
%
% MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
% Image *images,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o images: Specifies a pointer to a list of Image structures.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info,
Image *images,ExceptionInfo *exception)
{
CubeInfo
*cube_info;
Image
*image;
MagickBooleanType
proceed,
status;
MagickProgressMonitor
progress_monitor;
register ssize_t
i;
size_t
depth,
maximum_colors,
number_images;
assert(quantize_info != (const QuantizeInfo *) NULL);
assert(quantize_info->signature == MagickCoreSignature);
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (GetNextImageInList(images) == (Image *) NULL)
{
/*
Handle a single image with QuantizeImage.
*/
status=QuantizeImage(quantize_info,images,exception);
return(status);
}
status=MagickFalse;
maximum_colors=quantize_info->number_colors;
if (maximum_colors == 0)
maximum_colors=MaxColormapSize;
if (maximum_colors > MaxColormapSize)
maximum_colors=MaxColormapSize;
depth=quantize_info->tree_depth;
if (depth == 0)
{
size_t
colors;
/*
Depth of color tree is: Log4(colormap size)+2.
*/
colors=maximum_colors;
for (depth=1; colors != 0; depth++)
colors>>=2;
if (quantize_info->dither_method != NoDitherMethod)
depth--;
}
/*
Initialize color cube.
*/
cube_info=GetCubeInfo(quantize_info,depth,maximum_colors);
if (cube_info == (CubeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return(MagickFalse);
}
number_images=GetImageListLength(images);
image=images;
for (i=0; image != (Image *) NULL; i++)
{
progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,
image->client_data);
status=ClassifyImageColors(cube_info,image,exception);
if (status == MagickFalse)
break;
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
number_images);
if (proceed == MagickFalse)
break;
image=GetNextImageInList(image);
}
if (status != MagickFalse)
{
/*
Reduce the number of colors in an image sequence.
*/
ReduceImageColors(images,cube_info);
image=images;
for (i=0; image != (Image *) NULL; i++)
{
progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor)
NULL,image->client_data);
status=AssignImageColors(image,cube_info,exception);
if (status == MagickFalse)
break;
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i,
number_images);
if (proceed == MagickFalse)
break;
image=GetNextImageInList(image);
}
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Q u a n t i z e E r r o r F l a t t e n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% QuantizeErrorFlatten() traverses the color cube and flattens the quantization
% error into a sorted 1D array. This accelerates the color reduction process.
%
% Contributed by Yoya.
%
% The format of the QuantizeErrorFlatten method is:
%
% size_t QuantizeErrorFlatten(const CubeInfo *cube_info,
% const NodeInfo *node_info,const ssize_t offset,
% double *quantize_error)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is current pointer.
%
% o offset: quantize error offset.
%
% o quantize_error: the quantization error vector.
%
*/
static size_t QuantizeErrorFlatten(const CubeInfo *cube_info,
const NodeInfo *node_info,const ssize_t offset,double *quantize_error)
{
register ssize_t
i;
size_t
n,
number_children;
if (offset >= (ssize_t) cube_info->nodes)
return(0);
quantize_error[offset]=node_info->quantize_error;
n=1;
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children ; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
n+=QuantizeErrorFlatten(cube_info,node_info->child[i],offset+n,
quantize_error);
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e d u c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Reduce() traverses the color cube tree and prunes any node whose
% quantization error falls below a particular threshold.
%
% The format of the Reduce method is:
%
% Reduce(CubeInfo *cube_info,const NodeInfo *node_info)
%
% A description of each parameter follows.
%
% o cube_info: A pointer to the Cube structure.
%
% o node_info: pointer to node in color cube tree that is to be pruned.
%
*/
static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info)
{
register ssize_t
i;
size_t
number_children;
/*
Traverse any children.
*/
number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL;
for (i=0; i < (ssize_t) number_children; i++)
if (node_info->child[i] != (NodeInfo *) NULL)
Reduce(cube_info,node_info->child[i]);
if (node_info->quantize_error <= cube_info->pruning_threshold)
PruneChild(cube_info,node_info);
else
{
/*
Find minimum pruning threshold.
*/
if (node_info->number_unique > 0)
cube_info->colors++;
if (node_info->quantize_error < cube_info->next_threshold)
cube_info->next_threshold=node_info->quantize_error;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ R e d u c e I m a g e C o l o r s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReduceImageColors() repeatedly prunes the tree until the number of nodes
% with n2 > 0 is less than or equal to the maximum number of colors allowed
% in the output image. On any given iteration over the tree, it selects
% those nodes whose E value is minimal for pruning and merges their
% color statistics upward. It uses a pruning threshold, Ep, to govern
% node selection as follows:
%
% Ep = 0
% while number of nodes with (n2 > 0) > required maximum number of colors
% prune all nodes such that E <= Ep
% Set Ep to minimum E in remaining nodes
%
% This has the effect of minimizing any quantization error when merging
% two nodes together.
%
% When a node to be pruned has offspring, the pruning procedure invokes
% itself recursively in order to prune the tree from the leaves upward.
% n2, Sr, Sg, and Sb in a node being pruned are always added to the
% corresponding data in that node's parent. This retains the pruned
% node's color characteristics for later averaging.
%
% For each node, n2 pixels exist for which that node represents the
% smallest volume in RGB space containing those pixel's colors. When n2
% > 0 the node will uniquely define a color in the output image. At the
% beginning of reduction, n2 = 0 for all nodes except a the leaves of
% the tree which represent colors present in the input image.
%
% The other pixel count, n1, indicates the total number of colors
% within the cubic volume which the node represents. This includes n1 -
% n2 pixels whose colors should be defined by nodes at a lower level in
% the tree.
%
% The format of the ReduceImageColors method is:
%
% ReduceImageColors(const Image *image,CubeInfo *cube_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
*/
static int QuantizeErrorCompare(const void *error_p,const void *error_q)
{
double
*p,
*q;
p=(double *) error_p;
q=(double *) error_q;
if (*p > *q)
return(1);
if (fabs(*q-*p) <= MagickEpsilon)
return(0);
return(-1);
}
static void ReduceImageColors(const Image *image,CubeInfo *cube_info)
{
#define ReduceImageTag "Reduce/Image"
MagickBooleanType
proceed;
MagickOffsetType
offset;
size_t
span;
cube_info->next_threshold=0.0;
if (cube_info->colors > cube_info->maximum_colors)
{
double
*quantize_error;
/*
Enable rapid reduction of the number of unique colors.
*/
quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes,
sizeof(*quantize_error));
if (quantize_error != (double *) NULL)
{
(void) QuantizeErrorFlatten(cube_info,cube_info->root,0,
quantize_error);
qsort(quantize_error,cube_info->nodes,sizeof(double),
QuantizeErrorCompare);
if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100))
cube_info->next_threshold=quantize_error[cube_info->nodes-110*
(cube_info->maximum_colors+1)/100];
quantize_error=(double *) RelinquishMagickMemory(quantize_error);
}
}
for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; )
{
cube_info->pruning_threshold=cube_info->next_threshold;
cube_info->next_threshold=cube_info->root->quantize_error-1;
cube_info->colors=0;
Reduce(cube_info,cube_info->root);
offset=(MagickOffsetType) span-cube_info->colors;
proceed=SetImageProgress(image,ReduceImageTag,offset,span-
cube_info->maximum_colors+1);
if (proceed == MagickFalse)
break;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m a p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemapImage() replaces the colors of an image with the closest of the colors
% from the reference image.
%
% The format of the RemapImage method is:
%
% MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
% Image *image,const Image *remap_image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o image: the image.
%
% o remap_image: the reference image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info,
Image *image,const Image *remap_image,ExceptionInfo *exception)
{
CubeInfo
*cube_info;
MagickBooleanType
status;
/*
Initialize color cube.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(remap_image != (Image *) NULL);
assert(remap_image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
quantize_info->number_colors);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ClassifyImageColors(cube_info,remap_image,exception);
if (status != MagickFalse)
{
/*
Classify image colors from the reference image.
*/
cube_info->quantize_info->number_colors=cube_info->colors;
status=AssignImageColors(image,cube_info,exception);
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e m a p I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RemapImages() replaces the colors of a sequence of images with the
% closest color from a reference image.
%
% The format of the RemapImage method is:
%
% MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
% Image *images,Image *remap_image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o quantize_info: Specifies a pointer to an QuantizeInfo structure.
%
% o images: the image sequence.
%
% o remap_image: the reference image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info,
Image *images,const Image *remap_image,ExceptionInfo *exception)
{
CubeInfo
*cube_info;
Image
*image;
MagickBooleanType
status;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=images;
if (remap_image == (Image *) NULL)
{
/*
Create a global colormap for an image sequence.
*/
status=QuantizeImages(quantize_info,images,exception);
return(status);
}
/*
Classify image colors from the reference image.
*/
cube_info=GetCubeInfo(quantize_info,MaxTreeDepth,
quantize_info->number_colors);
if (cube_info == (CubeInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ClassifyImageColors(cube_info,remap_image,exception);
if (status != MagickFalse)
{
/*
Classify image colors from the reference image.
*/
cube_info->quantize_info->number_colors=cube_info->colors;
image=images;
for ( ; image != (Image *) NULL; image=GetNextImageInList(image))
{
status=AssignImageColors(image,cube_info,exception);
if (status == MagickFalse)
break;
}
}
DestroyCubeInfo(cube_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t G r a y s c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetGrayscaleImage() converts an image to a PseudoClass grayscale image.
%
% The format of the SetGrayscaleImage method is:
%
% MagickBooleanType SetGrayscaleImage(Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int IntensityCompare(const void *x,const void *y)
{
double
intensity;
PixelInfo
*color_1,
*color_2;
color_1=(PixelInfo *) x;
color_2=(PixelInfo *) y;
intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)-
GetPixelInfoIntensity((const Image *) NULL,color_2);
if (intensity < (double) INT_MIN)
intensity=(double) INT_MIN;
if (intensity > (double) INT_MAX)
intensity=(double) INT_MAX;
return((int) intensity);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static MagickBooleanType SetGrayscaleImage(Image *image,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
PixelInfo
*colormap;
register ssize_t
i;
size_t
extent;
ssize_t
*colormap_index,
j,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->type != GrayscaleType)
(void) TransformImageColorspace(image,GRAYColorspace,exception);
extent=MagickMax(image->colors+1,MagickMax(MaxColormapSize,MaxMap+1));
colormap_index=(ssize_t *) AcquireQuantumMemory(extent,
sizeof(*colormap_index));
if (colormap_index == (ssize_t *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
if (image->storage_class != PseudoClass)
{
(void) memset(colormap_index,(-1),extent*sizeof(*colormap_index));
if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
image->colors=0;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register size_t
intensity;
intensity=ScaleQuantumToMap(GetPixelRed(image,q));
if (colormap_index[intensity] < 0)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_SetGrayscaleImage)
#endif
if (colormap_index[intensity] < 0)
{
colormap_index[intensity]=(ssize_t) image->colors;
image->colormap[image->colors].red=(double)
GetPixelRed(image,q);
image->colormap[image->colors].green=(double)
GetPixelGreen(image,q);
image->colormap[image->colors].blue=(double)
GetPixelBlue(image,q);
image->colors++;
}
}
SetPixelIndex(image,(Quantum) colormap_index[intensity],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
}
(void) memset(colormap_index,0,extent*sizeof(*colormap_index));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].alpha=(double) i;
qsort((void *) image->colormap,image->colors,sizeof(PixelInfo),
IntensityCompare);
colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap));
if (colormap == (PixelInfo *) NULL)
{
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
j=0;
colormap[j]=image->colormap[0];
for (i=0; i < (ssize_t) image->colors; i++)
{
if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse)
{
j++;
colormap[j]=image->colormap[i];
}
colormap_index[(ssize_t) image->colormap[i].alpha]=j;
}
image->colors=(size_t) (j+1);
image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap);
image->colormap=colormap;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap(
GetPixelIndex(image,q))],q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index);
image->type=GrayscaleType;
if (SetImageMonochrome(image,exception) != MagickFalse)
image->type=BilevelType;
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t I m a g e C o l o r m a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetImageColormap() traverses the color cube tree and sets the colormap of
% the image. A colormap entry is any node in the color cube tree where the
% of unique colors is not zero.
%
% The format of the SetImageColormap method is:
%
% MagickBooleanType SetImageColormap(Image *image,CubeInfo *cube_info,
% ExceptionInfo *node_info)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cube_info: A pointer to the Cube structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickBooleanType SetImageColormap(Image *image,CubeInfo *cube_info,
ExceptionInfo *exception)
{
size_t
number_colors;
number_colors=MagickMax(cube_info->maximum_colors,cube_info->colors);
if (AcquireImageColormap(image,number_colors,exception) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
image->colors=0;
DefineImageColormap(image,cube_info,cube_info->root);
if (image->colors != number_colors)
{
image->colormap=(PixelInfo *) ResizeQuantumMemory(image->colormap,
image->colors+1,sizeof(*image->colormap));
if (image->colormap == (PixelInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
return(MagickTrue);
}
|
omptarget.h | //===---- omptarget.h - OpenMP GPU initialization ---------------- CUDA -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations of all library macros, types,
// and functions.
//
//===----------------------------------------------------------------------===//
#ifndef OMPTARGET_H
#define OMPTARGET_H
#include "common/allocator.h"
#include "common/debug.h" // debug
#include "common/state-queue.h"
#include "common/support.h"
#include "interface.h" // interfaces with omp, compiler, and user
#include "target_impl.h"
#define OMPTARGET_NVPTX_VERSION 1.1
// used by the library for the interface with the app
#define DISPATCH_FINISHED 0
#define DISPATCH_NOTFINISHED 1
// used by dynamic scheduling
#define FINISHED 0
#define NOT_FINISHED 1
#define LAST_CHUNK 2
#define BARRIER_COUNTER 0
#define ORDERED_COUNTER 1
// arguments needed for L0 parallelism only.
class omptarget_nvptx_SharedArgs {
public:
// All these methods must be called by the master thread only.
INLINE void Init() {
args = buffer;
nArgs = MAX_SHARED_ARGS;
}
INLINE void DeInit() {
// Free any memory allocated for outlined parallel function with a large
// number of arguments.
if (nArgs > MAX_SHARED_ARGS) {
SafeFree(args, "new extended args");
Init();
}
}
INLINE void EnsureSize(size_t size) {
if (size > nArgs) {
if (nArgs > MAX_SHARED_ARGS) {
SafeFree(args, "new extended args");
}
args = (void **)SafeMalloc(size * sizeof(void *), "new extended args");
nArgs = size;
}
}
// Called by all threads.
INLINE void **GetArgs() const { return args; };
private:
// buffer of pre-allocated arguments.
void *buffer[MAX_SHARED_ARGS];
// pointer to arguments buffer.
// starts off as a pointer to 'buffer' but can be dynamically allocated.
void **args;
// starts off as MAX_SHARED_ARGS but can increase in size.
uint32_t nArgs;
};
extern omptarget_nvptx_SharedArgs EXTERN_SHARED(omptarget_nvptx_globalArgs);
// Worker slot type which is initialized with the default worker slot
// size of 4*32 bytes.
struct __kmpc_data_sharing_slot {
__kmpc_data_sharing_slot *Next;
__kmpc_data_sharing_slot *Prev;
void *PrevSlotStackPtr;
void *DataEnd;
char Data[DS_Worker_Warp_Slot_Size];
};
////////////////////////////////////////////////////////////////////////////////
// task ICV and (implicit & explicit) task state
class omptarget_nvptx_TaskDescr {
public:
// methods for flags
INLINE omp_sched_t GetRuntimeSched() const;
INLINE void SetRuntimeSched(omp_sched_t sched);
INLINE int InParallelRegion() const { return items.flags & TaskDescr_InPar; }
INLINE int InL2OrHigherParallelRegion() const {
return items.flags & TaskDescr_InParL2P;
}
INLINE int IsParallelConstruct() const {
return items.flags & TaskDescr_IsParConstr;
}
INLINE int IsTaskConstruct() const { return !IsParallelConstruct(); }
// methods for other fields
INLINE uint16_t &ThreadId() { return items.threadId; }
INLINE uint64_t &RuntimeChunkSize() { return items.runtimeChunkSize; }
INLINE omptarget_nvptx_TaskDescr *GetPrevTaskDescr() const { return prev; }
INLINE void SetPrevTaskDescr(omptarget_nvptx_TaskDescr *taskDescr) {
prev = taskDescr;
}
// init & copy
INLINE void InitLevelZeroTaskDescr();
INLINE void InitLevelOneTaskDescr(omptarget_nvptx_TaskDescr *parentTaskDescr);
INLINE void Copy(omptarget_nvptx_TaskDescr *sourceTaskDescr);
INLINE void CopyData(omptarget_nvptx_TaskDescr *sourceTaskDescr);
INLINE void CopyParent(omptarget_nvptx_TaskDescr *parentTaskDescr);
INLINE void CopyForExplicitTask(omptarget_nvptx_TaskDescr *parentTaskDescr);
INLINE void CopyToWorkDescr(omptarget_nvptx_TaskDescr *masterTaskDescr);
INLINE void CopyFromWorkDescr(omptarget_nvptx_TaskDescr *workTaskDescr);
INLINE void CopyConvergentParent(omptarget_nvptx_TaskDescr *parentTaskDescr,
uint16_t tid, uint16_t tnum);
INLINE void SaveLoopData();
INLINE void RestoreLoopData() const;
private:
// bits for flags: (6 used, 2 free)
// 3 bits (SchedMask) for runtime schedule
// 1 bit (InPar) if this thread has encountered one or more parallel region
// 1 bit (IsParConstr) if ICV for a parallel region (false = explicit task)
// 1 bit (InParL2+) if this thread has encountered L2 or higher parallel
// region
static const uint8_t TaskDescr_SchedMask = (0x1 | 0x2 | 0x4);
static const uint8_t TaskDescr_InPar = 0x10;
static const uint8_t TaskDescr_IsParConstr = 0x20;
static const uint8_t TaskDescr_InParL2P = 0x40;
struct SavedLoopDescr_items {
int64_t loopUpperBound;
int64_t nextLowerBound;
int64_t chunk;
int64_t stride;
kmp_sched_t schedule;
} loopData;
struct TaskDescr_items {
uint8_t flags; // 6 bit used (see flag above)
uint8_t unused;
uint16_t threadId; // thread id
uint64_t runtimeChunkSize; // runtime chunk size
} items;
omptarget_nvptx_TaskDescr *prev;
};
// build on kmp
typedef struct omptarget_nvptx_ExplicitTaskDescr {
omptarget_nvptx_TaskDescr
taskDescr; // omptarget_nvptx task description (must be first)
kmp_TaskDescr kmpTaskDescr; // kmp task description (must be last)
} omptarget_nvptx_ExplicitTaskDescr;
////////////////////////////////////////////////////////////////////////////////
// Descriptor of a parallel region (worksharing in general)
class omptarget_nvptx_WorkDescr {
public:
// access to data
INLINE omptarget_nvptx_TaskDescr *WorkTaskDescr() { return &masterTaskICV; }
private:
omptarget_nvptx_TaskDescr masterTaskICV;
};
////////////////////////////////////////////////////////////////////////////////
class omptarget_nvptx_TeamDescr {
public:
// access to data
INLINE omptarget_nvptx_TaskDescr *LevelZeroTaskDescr() {
return &levelZeroTaskDescr;
}
INLINE omptarget_nvptx_WorkDescr &WorkDescr() {
return workDescrForActiveParallel;
}
// init
INLINE void InitTeamDescr();
INLINE __kmpc_data_sharing_slot *GetPreallocatedSlotAddr(int wid) {
worker_rootS[wid].DataEnd =
&worker_rootS[wid].Data[0] + DS_Worker_Warp_Slot_Size;
// We currently do not have a next slot.
worker_rootS[wid].Next = 0;
worker_rootS[wid].Prev = 0;
worker_rootS[wid].PrevSlotStackPtr = 0;
return (__kmpc_data_sharing_slot *)&worker_rootS[wid];
}
private:
omptarget_nvptx_TaskDescr
levelZeroTaskDescr; // icv for team master initial thread
omptarget_nvptx_WorkDescr
workDescrForActiveParallel; // one, ONLY for the active par
ALIGN(16)
__kmpc_data_sharing_slot worker_rootS[DS_Max_Warp_Number];
};
////////////////////////////////////////////////////////////////////////////////
// thread private data (struct of arrays for better coalescing)
// tid refers here to the global thread id
// do not support multiple concurrent kernel a this time
class omptarget_nvptx_ThreadPrivateContext {
public:
// task
INLINE omptarget_nvptx_TaskDescr *Level1TaskDescr(int tid) {
return &levelOneTaskDescr[tid];
}
INLINE void SetTopLevelTaskDescr(int tid,
omptarget_nvptx_TaskDescr *taskICV) {
topTaskDescr[tid] = taskICV;
}
INLINE omptarget_nvptx_TaskDescr *GetTopLevelTaskDescr(int tid) const;
// parallel
INLINE uint16_t &NumThreadsForNextParallel(int tid) {
return nextRegion.tnum[tid];
}
// schedule (for dispatch)
INLINE kmp_sched_t &ScheduleType(int tid) { return schedule[tid]; }
INLINE int64_t &Chunk(int tid) { return chunk[tid]; }
INLINE int64_t &LoopUpperBound(int tid) { return loopUpperBound[tid]; }
INLINE int64_t &NextLowerBound(int tid) { return nextLowerBound[tid]; }
INLINE int64_t &Stride(int tid) { return stride[tid]; }
INLINE omptarget_nvptx_TeamDescr &TeamContext() { return teamContext; }
INLINE void InitThreadPrivateContext(int tid);
INLINE uint64_t &Cnt() { return cnt; }
private:
// team context for this team
omptarget_nvptx_TeamDescr teamContext;
// task ICV for implicit threads in the only parallel region
omptarget_nvptx_TaskDescr levelOneTaskDescr[MAX_THREADS_PER_TEAM];
// pointer where to find the current task ICV (top of the stack)
omptarget_nvptx_TaskDescr *topTaskDescr[MAX_THREADS_PER_TEAM];
union {
// Only one of the two is live at the same time.
// parallel
uint16_t tnum[MAX_THREADS_PER_TEAM];
} nextRegion;
// schedule (for dispatch)
kmp_sched_t schedule[MAX_THREADS_PER_TEAM]; // remember schedule type for #for
int64_t chunk[MAX_THREADS_PER_TEAM];
int64_t loopUpperBound[MAX_THREADS_PER_TEAM];
// state for dispatch with dyn/guided OR static (never use both at a time)
int64_t nextLowerBound[MAX_THREADS_PER_TEAM];
int64_t stride[MAX_THREADS_PER_TEAM];
uint64_t cnt;
};
/// Memory manager for statically allocated memory.
class omptarget_nvptx_SimpleMemoryManager {
private:
struct MemDataTy {
volatile unsigned keys[OMP_STATE_COUNT];
} MemData[MAX_SM] ALIGN(128);
INLINE static uint32_t hash(unsigned key) {
return key & (OMP_STATE_COUNT - 1);
}
public:
INLINE void Release();
INLINE const void *Acquire(const void *buf, size_t size);
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// global data tables
////////////////////////////////////////////////////////////////////////////////
extern omptarget_nvptx_SimpleMemoryManager omptarget_nvptx_simpleMemoryManager;
extern uint32_t EXTERN_SHARED(usedMemIdx);
extern uint32_t EXTERN_SHARED(usedSlotIdx);
#if _OPENMP
extern uint8_t parallelLevel[MAX_THREADS_PER_TEAM / WARPSIZE];
#pragma omp allocate(parallelLevel) allocator(omp_pteam_mem_alloc)
#else
extern uint8_t EXTERN_SHARED(parallelLevel)[MAX_THREADS_PER_TEAM / WARPSIZE];
#endif
extern uint16_t EXTERN_SHARED(threadLimit);
extern uint16_t EXTERN_SHARED(threadsInTeam);
extern uint16_t EXTERN_SHARED(nThreads);
extern omptarget_nvptx_ThreadPrivateContext *
EXTERN_SHARED(omptarget_nvptx_threadPrivateContext);
extern uint32_t EXTERN_SHARED(execution_param);
extern void *EXTERN_SHARED(ReductionScratchpadPtr);
////////////////////////////////////////////////////////////////////////////////
// work function (outlined parallel/simd functions) and arguments.
// needed for L1 parallelism only.
////////////////////////////////////////////////////////////////////////////////
typedef void *omptarget_nvptx_WorkFn;
extern volatile omptarget_nvptx_WorkFn EXTERN_SHARED(omptarget_nvptx_workFn);
////////////////////////////////////////////////////////////////////////////////
// get private data structures
////////////////////////////////////////////////////////////////////////////////
INLINE omptarget_nvptx_TeamDescr &getMyTeamDescriptor();
INLINE omptarget_nvptx_WorkDescr &getMyWorkDescriptor();
INLINE omptarget_nvptx_TaskDescr *
getMyTopTaskDescriptor(bool isSPMDExecutionMode);
INLINE omptarget_nvptx_TaskDescr *getMyTopTaskDescriptor(int globalThreadId);
////////////////////////////////////////////////////////////////////////////////
// inlined implementation
////////////////////////////////////////////////////////////////////////////////
INLINE uint32_t __kmpc_impl_ffs(uint32_t x) { return __builtin_ffs(x); }
INLINE uint32_t __kmpc_impl_popc(uint32_t x) { return __builtin_popcount(x); }
INLINE uint32_t __kmpc_impl_ffs(uint64_t x) { return __builtin_ffsl(x); }
INLINE uint32_t __kmpc_impl_popc(uint64_t x) { return __builtin_popcountl(x); }
#include "common/omptargeti.h"
#endif
|
GB_unop__identity_int64_fc32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_int64_fc32)
// op(A') function: GB (_unop_tran__identity_int64_fc32)
// C type: int64_t
// A type: GxB_FC32_t
// cast: int64_t cij = GB_cast_to_int64_t ((double) crealf (aij))
// unaryop: cij = aij
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT64 || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int64_fc32)
(
int64_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
int64_t z = GB_cast_to_int64_t ((double) crealf (aij)) ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC32_t aij = Ax [p] ;
int64_t z = GB_cast_to_int64_t ((double) crealf (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_int64_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
gmm.c | /** @file gmm.c
** @brief Gaussian Mixture Models - Implementation
** @author David Novotny
** @author Andrea Vedaldi
**/
/*
Copyright (C) 2013 David Novotny and Andrea Vedaldi.
All rights reserved.
This file is part of the VLFeat library and is made available under
the terms of the BSD license (see the COPYING file).
*/
/**
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@page gmm Gaussian Mixture Models (GMM)
@author David Novotny
@author Andrea Vedaldi
@tableofcontents
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@ref gmm.h is an implementation of *Gaussian Mixture Models* (GMMs).
The main functionality provided by this module is learning GMMs from
data by maximum likelihood. Model optimization uses the Expectation
Maximization (EM) algorithm @cite{dempster77maximum}. The
implementation supports @c float or @c double data types, is
parallelized, and is tuned to work reliably and effectively on
datasets of visual features. Stability is obtained in part by
regularizing and restricting the parameters of the GMM.
@ref gmm-starting demonstreates how to use the C API to compute the FV
representation of an image. For further details refer to:
- @subpage gmm-fundamentals
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@section gmm-starting Getting started
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
In order to use @ref gmm.h to learn a GMM from training data, create a
new ::VlGMM object instance, set the parameters as desired, and run
the training code. The following example learns @c numClusters
Gaussian components from @c numData vectors of dimension @c dimension
and storage class @c float using at most 100 EM iterations:
@code
float * means ;
float * covariances ;
float * priors ;
float * posteriors ;
double loglikelihood ;
// create a new instance of a GMM object for float data
gmm = vl_gmm_new (VL_TYPE_FLOAT, dimension, numClusters) ;
// set the maximum number of EM iterations to 100
vl_gmm_set_max_num_iterations (gmm, 100) ;
// set the initialization to random selection
vl_gmm_set_initialization (gmm,VlGMMRand);
// cluster the data, i.e. learn the GMM
vl_gmm_cluster (gmm, data, numData);
// get the means, covariances, and priors of the GMM
means = vl_gmm_get_means(gmm);
covariances = vl_gmm_get_covariances(gmm);
priors = vl_gmm_get_priors(gmm);
// get loglikelihood of the estimated GMM
loglikelihood = vl_gmm_get_loglikelihood(gmm) ;
// get the soft assignments of the data points to each cluster
posteriors = vl_gmm_get_posteriors(gmm) ;
@endcode
@note ::VlGMM assumes that the covariance matrices of the GMM are
diagonal. This reduces significantly the number of parameters to learn
and is usually an acceptable compromise in vision applications. If the
data is significantly correlated, it can be beneficial to de-correlate
it by PCA rotation or projection in pre-processing.
::vl_gmm_get_loglikelihood is used to get the final loglikelihood of
the estimated mixture, ::vl_gmm_get_means and ::vl_gmm_get_covariances
to obtain the means and the diagonals of the covariance matrices of
the estimated Gaussian modes, and ::vl_gmm_get_posteriors to get the
posterior probabilities that a given point is associated to each of
the modes (soft assignments).
The learning algorithm, which uses EM, finds a local optimum of the
objective function. Therefore the initialization is crucial in
obtaining a good model, measured in term of the final
loglikelihood. ::VlGMM supports a few methods (use
::vl_gmm_set_initialization to choose one) as follows:
Method | ::VlGMMInitialization enumeration | Description
----------------------|-----------------------------------------|-----------------------------------------------
Random initialization | ::VlGMMRand | Random initialization of the mixture parameters
KMeans | ::VlGMMKMeans | Initialization of the mixture parameters using ::VlKMeans
Custom | ::VlGMMCustom | User specified initialization
Note that in the case of ::VlGMMKMeans initialization, an object of
type ::VlKMeans object must be created and passed to the ::VlGMM
instance (see @ref kmeans to see how to correctly set up this object).
When a user wants to use the ::VlGMMCustom method, the initial means,
covariances and priors have to be specified using the
::vl_gmm_set_means, ::vl_gmm_set_covariances and ::vl_gmm_set_priors
methods.
**/
/**
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@page gmm-fundamentals GMM fundamentals
@tableofcontents
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
A *Gaussian Mixture Model* (GMM) is a mixture of $K$ multivariate
Gaussian distributions. In order to sample from a GMM, one samples
first the component index $k \in \{1,\dots,K\}$ with *prior
probability* $\pi_k$, and then samples the vector $\bx \in
\mathbb{R}^d$ from the $k$-th Gaussian distribution
$p(\bx|\mu_k,\Sigma_k)$. Here $\mu_k$ and $\Sigma_k$ are respectively
the *mean* and *covariance* of the distribution. The GMM is completely
specified by the parameters $\Theta=\{\pi_k,\mu_k,\Sigma_k; k =
1,\dots,K\}$
The density $p(\bx|\Theta)$ induced on the training data is obtained
by marginalizing the component selector $k$, obtaining
\[
p(\bx|\Theta)
= \sum_{k=1}^{K} \pi_k p( \bx_i |\mu_k,\Sigma_k),
\qquad
p( \bx |\mu_k,\Sigma_k)
=
\frac{1}{\sqrt{(2\pi)^d\det\Sigma_k}}
\exp\left[
-\frac{1}{2} (\bx-\mu_k)^\top\Sigma_k^{-1}(\bx-\mu_k)
\right].
\]
Learning a GMM to fit a dataset $X=(\bx_1, \dots, \bx_n)$ is usually
done by maximizing the log-likelihood of the data:
@f[
\ell(\Theta;X)
= E_{\bx\sim\hat p} [ \log p(\bx|\Theta) ]
= \frac{1}{n}\sum_{i=1}^{n} \log \sum_{k=1}^{K} \pi_k p(\bx_i|\mu_k, \Sigma_k)
@f]
where $\hat p$ is the empirical distribution of the data. An algorithm
to solve this problem is introduced next.
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@section gmm-em Learning a GMM by expectation maximization
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
The direct maximization of the log-likelihood function of a GMM is
difficult due to the fact that the assignments of points to Gaussian
mode is not observable and, as such, must be treated as a latent
variable.
Usually, GMMs are learned by using the *Expectation Maximization* (EM)
algorithm @cite{dempster77maximum}. Consider in general the problem of
estimating to the maximum likelihood a distribution $p(x|\Theta) =
\int p(x,h|\Theta)\,dh$, where $x$ is a measurement, $h$ is a *latent
variable*, and $\Theta$ are the model parameters. By introducing an
auxiliary distribution $q(h|x)$ on the latent variable, one can use
Jensen inequality to obtain the following lower bound on the
log-likelihood:
@f{align*}
\ell(\Theta;X) =
E_{x\sim\hat p} \log p(x|\Theta)
&= E_{x\sim\hat p} \log \int p(x,h|\Theta) \,dh \\
&= E_{x\sim\hat p} \log \int \frac{p(x,h|\Theta)}{q(h|x)} q(h|x)\,dh \\
&\geq E_{x\sim\hat p} \int q(h) \log \frac{p(x,h|\Theta)}{q(h|x)}\,dh \\
&= E_{(x,q) \sim q(h|x) \hat p(x)} \log p(x,h|\Theta) -
E_{(x,q) \sim q(h|x) \hat p(x)} \log q(h|x)
@f}
The first term of the last expression is the log-likelihood of the
model where both the $x$ and $h$ are observed and joinlty distributed
as $q(x|h)\hat p(x)$; the second term is the a average entropy of the
latent variable, which does not depend on $\Theta$. This lower bound
is maximized and becomes tight by setting $q(h|x) = p(h|x,\Theta)$ to
be the posterior distribution on the latent variable $h$ (given the
current estimate of the parameters $\Theta$). In fact:
\[
E_{x \sim \hat p} \log p(x|\Theta)
=
E_{(x,h) \sim p(h|x,\Theta) \hat p(x)}\left[ \log \frac{p(x,h|\Theta)}{p(h|x,\Theta)} \right]
=
E_{(x,h) \sim p(h|x,\Theta) \hat p(x)} [ \log p(x|\Theta) ]
=
\ell(\Theta;X).
\]
EM alternates between updating the latent variable auxiliary
distribution $q(h|x) = p(h|x,\Theta_t)$ (*expectation step*) given the
current estimate of the parameters $\Theta_t$, and then updating the
model parameters $\Theta_{t+1}$ by maximizing the log-likelihood lower
bound derived (*maximization step*). The simplification is that in the
maximization step both $x$ and $h$ are now ``observed'' quantities.
This procedure converges to a local optimum of the model
log-likelihood.
@subsection gmm-expectation-step Expectation step
In the case of a GMM, the latent variables are the point-to-cluster
assignments $k_i, i=1,\dots,n$, one for each of $n$ data points. The
auxiliary distribution $q(k_i|\bx_i) = q_{ik}$ is a matrix with $n
\times K$ entries. Each row $q_{i,:}$ can be thought of as a vector of
soft assignments of the data points $\bx_i$ to each of the Gaussian
modes. Setting $q_{ik} = p(k_i | \bx_i, \Theta)$ yields
\[
q_{ik} =
\frac
{\pi_k p(\bx_i|\mu_k,\Sigma_k)}
{\sum_{l=1}^K \pi_l p(\bx_i|\mu_l,\Sigma_l)}
\]
where the Gaussian density $p(\bx_i|\mu_k,\Sigma_k)$ was given above.
One important point to keep in mind when these probabilities are
computed is the fact that the Gaussian densities may attain very low
values and underflow in a vanilla implementation. Furthermore, VLFeat
GMM implementation restricts the covariance matrices to be
diagonal. In this case, the computation of the determinant of
$\Sigma_k$ reduces to computing the trace of the matrix and the
inversion of $\Sigma_k$ could be obtained by inverting the elements on
the diagonal of the covariance matrix.
@subsection gmm-maximization-step Maximization step
The M step estimates the parameters of the Gaussian mixture components
and the prior probabilities $\pi_k$ given the auxiliary distribution
on the point-to-cluster assignments computed in the E step. Since all
the variables are now ``observed'', the estimate is quite simple. For
example, the mean $\mu_k$ of a Gaussian mode is obtained as the mean
of the data points assigned to it (accounting for the strength of the
soft assignments). The other quantities are obtained in a similar
manner, yielding to:
@f{align*}
\mu_k &= { { \sum_{i=1}^n q_{ik} \bx_{i} } \over { \sum_{i=1}^n q_{ik} } },
\\
\Sigma_k &= { { \sum_{i=1}^n { q_{ik} (\bx_{i} - \mu_{k}) {(\bx_{i} - \mu_{k})}^T } } \over { \sum_{i=1}^n q_{ik} } },
\\
\pi_k &= { \sum_{i=1}^n { q_{ik} } \over { \sum_{i=1}^n \sum_{l=1}^K q_{il} } }.
@f}
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
@section gmm-fundamentals-init Initialization algorithms
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
The EM algorithm is a local optimization method. As such, the quality
of the solution strongly depends on the quality of the initial values
of the parameters (i.e. of the locations and shapes of the Gaussian
modes).
@ref gmm.h supports the following cluster initialization algorithms:
- <b>Random data points.</b> (::vl_gmm_init_with_rand_data) This method
sets the means of the modes by sampling at random a corresponding
number of data points, sets the covariance matrices of all the modes
are to the covariance of the entire dataset, and sets the prior
probabilities of the Gaussian modes to be uniform. This
initialization method is the fastest, simplest, as well as the one
most likely to end in a bad local minimum.
- <b>KMeans initialization</b> (::vl_gmm_init_with_kmeans) This
method uses KMeans to pre-cluster the points. It then sets the means
and covariances of the Gaussian distributions the sample means and
covariances of each KMeans cluster. It also sets the prior
probabilities to be proportional to the mass of each cluster. In
order to use this initialization method, a user can specify an
instance of ::VlKMeans by using the function
::vl_gmm_set_kmeans_init_object, or let ::VlGMM create one
automatically.
Alternatively, one can manually specify a starting point
(::vl_gmm_set_priors, ::vl_gmm_set_means, ::vl_gmm_set_covariances).
**/
#include "gmm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#ifndef VL_DISABLE_SSE2
#include "mathop_sse2.h"
#endif
#ifndef VL_DISABLE_AVX
#include "mathop_avx.h"
#endif
/* ---------------------------------------------------------------- */
#ifndef VL_GMM_INSTANTIATING
/* ---------------------------------------------------------------- */
#define VL_GMM_MIN_VARIANCE 1e-6
#define VL_GMM_MIN_POSTERIOR 1e-2
#define VL_GMM_MIN_PRIOR 1e-6
struct _VlGMM
{
vl_type dataType ; /**< Data type. */
vl_size dimension ; /**< Data dimensionality. */
vl_size numClusters ; /**< Number of clusters */
vl_size numData ; /**< Number of last time clustered data points. */
vl_size maxNumIterations ; /**< Maximum number of refinement iterations. */
vl_size numRepetitions ; /**< Number of clustering repetitions. */
int verbosity ; /**< Verbosity level. */
void * means; /**< Means of Gaussian modes. */
void * covariances; /**< Diagonals of covariance matrices of Gaussian modes. */
void * priors; /**< Weights of Gaussian modes. */
void * posteriors; /**< Probabilities of correspondences of points to clusters. */
double * sigmaLowBound ; /**< Lower bound on the diagonal covariance values. */
VlGMMInitialization initialization; /**< Initialization option */
VlKMeans * kmeansInit; /**< Kmeans object for initialization of gaussians */
double LL ; /**< Current solution loglikelihood */
vl_bool kmeansInitIsOwner; /**< Indicates whether a user provided the kmeans initialization object */
} ;
/* ---------------------------------------------------------------- */
/* Life-cycle */
/* ---------------------------------------------------------------- */
static void
_vl_gmm_prepare_for_data (VlGMM* self, vl_size numData)
{
if (self->numData < numData) {
vl_free(self->posteriors) ;
self->posteriors = vl_malloc(vl_get_type_size(self->dataType) * numData * self->numClusters) ;
}
self->numData = numData ;
}
/** @brief Create a new GMM object
** @param dataType type of data (::VL_TYPE_FLOAT or ::VL_TYPE_DOUBLE)
** @param dimension dimension of the data.
** @param numComponents number of Gaussian mixture components.
** @return new GMM object instance.
**/
VlGMM *
vl_gmm_new (vl_type dataType, vl_size dimension, vl_size numComponents)
{
vl_index i ;
vl_size size = vl_get_type_size(dataType) ;
VlGMM * self = vl_calloc(1, sizeof(VlGMM)) ;
self->dataType = dataType;
self->numClusters = numComponents ;
self->numData = 0;
self->dimension = dimension ;
self->initialization = VlGMMRand;
self->verbosity = 0 ;
self->maxNumIterations = 50;
self->numRepetitions = 1;
self->sigmaLowBound = NULL ;
self->priors = NULL ;
self->covariances = NULL ;
self->means = NULL ;
self->posteriors = NULL ;
self->kmeansInit = NULL ;
self->kmeansInitIsOwner = VL_FALSE;
self->priors = vl_calloc (numComponents, size) ;
self->means = vl_calloc (numComponents * dimension, size) ;
self->covariances = vl_calloc (numComponents * dimension, size) ;
self->sigmaLowBound = vl_calloc (dimension, sizeof(double)) ;
for (i = 0 ; i < (unsigned)self->dimension ; ++i) { self->sigmaLowBound[i] = 1e-4 ; }
return self ;
}
/** @brief Reset state
** @param self object.
**
** The function reset the state of the GMM object. It deletes
** any stored posterior and other internal state variables.
**/
void
vl_gmm_reset (VlGMM * self)
{
if (self->posteriors) {
vl_free(self->posteriors) ;
self->posteriors = NULL ;
self->numData = 0 ;
}
if (self->kmeansInit && self->kmeansInitIsOwner) {
vl_kmeans_delete(self->kmeansInit) ;
self->kmeansInit = NULL ;
self->kmeansInitIsOwner = VL_FALSE ;
}
}
/** @brief Deletes a GMM object
** @param self GMM object instance.
**
** The function deletes the GMM object instance created
** by ::vl_gmm_new.
**/
void
vl_gmm_delete (VlGMM * self)
{
if(self->means) vl_free(self->means);
if(self->covariances) vl_free(self->covariances);
if(self->priors) vl_free(self->priors);
if(self->posteriors) vl_free(self->posteriors);
if(self->kmeansInit && self->kmeansInitIsOwner) {
vl_kmeans_delete(self->kmeansInit);
}
vl_free(self);
}
/* ---------------------------------------------------------------- */
/* Getters and setters */
/* ---------------------------------------------------------------- */
/** @brief Get data type
** @param self object
** @return data type.
**/
vl_type
vl_gmm_get_data_type (VlGMM const * self)
{
return self->dataType ;
}
/** @brief Get the number of clusters
** @param self object
** @return number of clusters.
**/
vl_size
vl_gmm_get_num_clusters (VlGMM const * self)
{
return self->numClusters ;
}
/** @brief Get the number of data points
** @param self object
** @return number of data points.
**/
vl_size
vl_gmm_get_num_data (VlGMM const * self)
{
return self->numData ;
}
/** @brief Get the log likelihood of the current mixture
** @param self object
** @return loglikelihood.
**/
double
vl_gmm_get_loglikelihood (VlGMM const * self)
{
return self->LL ;
}
/** @brief Get verbosity level
** @param self object
** @return verbosity level.
**/
int
vl_gmm_get_verbosity (VlGMM const * self)
{
return self->verbosity ;
}
/** @brief Set verbosity level
** @param self object
** @param verbosity verbosity level.
**/
void
vl_gmm_set_verbosity (VlGMM * self, int verbosity)
{
self->verbosity = verbosity ;
}
/** @brief Get means
** @param self object
** @return cluster means.
**/
void const *
vl_gmm_get_means (VlGMM const * self)
{
return self->means ;
}
/** @brief Get covariances
** @param self object
** @return diagonals of cluster covariance matrices.
**/
void const *
vl_gmm_get_covariances (VlGMM const * self)
{
return self->covariances ;
}
/** @brief Get priors
** @param self object
** @return priors of cluster gaussians.
**/
void const *
vl_gmm_get_priors (VlGMM const * self)
{
return self->priors ;
}
/** @brief Get posteriors
** @param self object
** @return posterior probabilities of cluster memberships.
**/
void const *
vl_gmm_get_posteriors (VlGMM const * self)
{
return self->posteriors ;
}
/** @brief Get maximum number of iterations
** @param self object
** @return maximum number of iterations.
**/
vl_size
vl_gmm_get_max_num_iterations (VlGMM const * self)
{
return self->maxNumIterations ;
}
/** @brief Set maximum number of iterations
** @param self VlGMM filter.
** @param maxNumIterations maximum number of iterations.
**/
void
vl_gmm_set_max_num_iterations (VlGMM * self, vl_size maxNumIterations)
{
self->maxNumIterations = maxNumIterations ;
}
/** @brief Get maximum number of repetitions.
** @param self object
** @return current number of repretitions for quantization.
**/
vl_size
vl_gmm_get_num_repetitions (VlGMM const * self)
{
return self->numRepetitions ;
}
/** @brief Set maximum number of repetitions
** @param self object
** @param numRepetitions maximum number of repetitions.
** The number of repetitions cannot be smaller than 1.
**/
void
vl_gmm_set_num_repetitions (VlGMM * self, vl_size numRepetitions)
{
assert (numRepetitions >= 1) ;
self->numRepetitions = numRepetitions ;
}
/** @brief Get data dimension
** @param self object
** @return data dimension.
**/
vl_size
vl_gmm_get_dimension (VlGMM const * self)
{
return self->dimension ;
}
/** @brief Get initialization algorithm
** @param self object
** @return initialization algorithm.
**/
VlGMMInitialization
vl_gmm_get_initialization (VlGMM const * self)
{
return self->initialization ;
}
/** @brief Set initialization algorithm.
** @param self object
** @param init initialization algorithm.
**/
void
vl_gmm_set_initialization (VlGMM * self, VlGMMInitialization init)
{
self->initialization = init;
}
/** @brief Get KMeans initialization object.
** @param self object
** @return kmeans initialization object.
**/
VlKMeans * vl_gmm_get_kmeans_init_object (VlGMM const * self)
{
return self->kmeansInit;
}
/** @brief Set KMeans initialization object.
** @param self object
** @param kmeans initialization KMeans object.
**/
void vl_gmm_set_kmeans_init_object (VlGMM * self, VlKMeans * kmeans)
{
if (self->kmeansInit && self->kmeansInitIsOwner) {
vl_kmeans_delete(self->kmeansInit) ;
}
self->kmeansInit = kmeans;
self->kmeansInitIsOwner = VL_FALSE;
}
/** @brief Get the lower bound on the diagonal covariance values.
** @param self object
** @return lower bound on covariances.
**/
double const * vl_gmm_get_covariance_lower_bounds (VlGMM const * self)
{
return self->sigmaLowBound;
}
/** @brief Set the lower bounds on diagonal covariance values.
** @param self object.
** @param bounds bounds.
**
** There is one lower bound per dimension. Use ::vl_gmm_set_covariance_lower_bound
** to set all of them to a given scalar.
**/
void vl_gmm_set_covariance_lower_bounds (VlGMM * self, double const * bounds)
{
memcpy(self->sigmaLowBound, bounds, sizeof(double) * self->dimension) ;
}
/** @brief Set the lower bounds on diagonal covariance values.
** @param self object.
** @param bound bound.
**
** While there is one lower bound per dimension, this function sets
** all of them to the specified scalar. Use ::vl_gmm_set_covariance_lower_bounds
** to set them individually.
**/
void vl_gmm_set_covariance_lower_bound (VlGMM * self, double bound)
{
int i ;
for (i = 0 ; i < (signed)self->dimension ; ++i) {
self->sigmaLowBound[i] = bound ;
}
}
/* ---------------------------------------------------------------- */
/* Instantiate shuffle algorithm */
#define VL_SHUFFLE_type vl_uindex
#define VL_SHUFFLE_prefix _vl_gmm
#include "shuffle-def.h"
/* #ifdef VL_GMM_INSTANTITATING */
#endif
/* ---------------------------------------------------------------- */
#ifdef VL_GMM_INSTANTIATING
/* ---------------------------------------------------------------- */
/* ---------------------------------------------------------------- */
/* Posterior assignments */
/* ---------------------------------------------------------------- */
/** @fn vl_get_gmm_data_posterior_f(float*,vl_size,vl_size,float const*,float const*,vl_size,float const*,float const*)
** @brief Get Gaussian modes posterior probabilities
** @param posteriors posterior probabilities (output)/
** @param numClusters number of modes in the GMM model.
** @param numData number of data elements.
** @param priors prior mode probabilities of the GMM model.
** @param means means of the GMM model.
** @param dimension data dimension.
** @param covariances diagonal covariances of the GMM model.
** @param data data.
** @return data log-likelihood.
**
** This is a helper function that does not require a ::VlGMM object
** instance to operate.
**/
double
VL_XCAT(vl_get_gmm_data_posteriors_, SFX)
(TYPE * posteriors,
vl_size numClusters,
vl_size numData,
TYPE const * priors,
TYPE const * means,
vl_size dimension,
TYPE const * covariances,
TYPE const * data)
{
vl_index i_d, i_cl;
vl_size dim;
double LL = 0;
TYPE halfDimLog2Pi = (dimension / 2.0) * log(2.0*VL_PI);
TYPE * logCovariances ;
TYPE * logWeights ;
TYPE * invCovariances ;
#if (FLT == VL_TYPE_FLOAT)
VlFloatVector3ComparisonFunction distFn = vl_get_vector_3_comparison_function_f(VlDistanceMahalanobis) ;
#else
VlDoubleVector3ComparisonFunction distFn = vl_get_vector_3_comparison_function_d(VlDistanceMahalanobis) ;
#endif
logCovariances = vl_malloc(sizeof(TYPE) * numClusters) ;
invCovariances = vl_malloc(sizeof(TYPE) * numClusters * dimension) ;
logWeights = vl_malloc(sizeof(TYPE) * numClusters) ;
#if defined(_OPENMP)
#pragma omp parallel for private(i_cl,dim) num_threads(vl_get_max_threads())
#endif
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++ i_cl) {
TYPE logSigma = 0 ;
if (priors[i_cl] < VL_GMM_MIN_PRIOR) {
logWeights[i_cl] = - (TYPE) VL_INFINITY_D ;
} else {
logWeights[i_cl] = log(priors[i_cl]);
}
for(dim = 0 ; dim < dimension ; ++ dim) {
logSigma += log(covariances[i_cl*dimension + dim]);
invCovariances [i_cl*dimension + dim] = (TYPE) 1.0 / covariances[i_cl*dimension + dim];
}
logCovariances[i_cl] = logSigma;
} /* end of parallel region */
#if defined(_OPENMP)
#pragma omp parallel for private(i_cl,i_d) reduction(+:LL) \
num_threads(vl_get_max_threads())
#endif
for (i_d = 0 ; i_d < (signed)numData ; ++ i_d) {
TYPE clusterPosteriorsSum = 0;
TYPE maxPosterior = (TYPE)(-VL_INFINITY_D) ;
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++ i_cl) {
TYPE p =
logWeights[i_cl]
- halfDimLog2Pi
- 0.5 * logCovariances[i_cl]
- 0.5 * distFn (dimension,
data + i_d * dimension,
means + i_cl * dimension,
invCovariances + i_cl * dimension) ;
posteriors[i_cl + i_d * numClusters] = p ;
if (p > maxPosterior) { maxPosterior = p ; }
}
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
TYPE p = posteriors[i_cl + i_d * numClusters] ;
p = exp(p - maxPosterior) ;
posteriors[i_cl + i_d * numClusters] = p ;
clusterPosteriorsSum += p ;
}
LL += log(clusterPosteriorsSum) + (double) maxPosterior ;
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
posteriors[i_cl + i_d * numClusters] /= clusterPosteriorsSum ;
}
} /* end of parallel region */
vl_free(logCovariances);
vl_free(logWeights);
vl_free(invCovariances);
return LL;
}
/* ---------------------------------------------------------------- */
/* Restarts zero-weighted Gaussians */
/* ---------------------------------------------------------------- */
static void
VL_XCAT(_vl_gmm_maximization_, SFX)
(VlGMM * self,
TYPE * posteriors,
TYPE * priors,
TYPE * covariances,
TYPE * means,
TYPE const * data,
vl_size numData) ;
static vl_size
VL_XCAT(_vl_gmm_restart_empty_modes_, SFX) (VlGMM * self, TYPE const * data)
{
vl_size dimension = self->dimension;
vl_size numClusters = self->numClusters;
vl_index i_cl, j_cl, i_d, d;
vl_size zeroWNum = 0;
TYPE * priors = (TYPE*)self->priors ;
TYPE * means = (TYPE*)self->means ;
TYPE * covariances = (TYPE*)self->covariances ;
TYPE * posteriors = (TYPE*)self->posteriors ;
//VlRand * rand = vl_get_rand() ;
TYPE * mass = vl_calloc(sizeof(TYPE), self->numClusters) ;
if (numClusters <= 1) { return 0 ; }
/* compute statistics */
{
vl_uindex i, k ;
vl_size numNullAssignments = 0 ;
for (i = 0 ; i < self->numData ; ++i) {
for (k = 0 ; k < self->numClusters ; ++k) {
TYPE p = ((TYPE*)self->posteriors)[k + i * self->numClusters] ;
mass[k] += p ;
if (p < VL_GMM_MIN_POSTERIOR) {
numNullAssignments ++ ;
}
}
}
if (self->verbosity) {
VL_PRINTF("gmm: sparsity of data posterior: %.1f%%\n", (double)numNullAssignments / (self->numData * self->numClusters) * 100) ;
}
}
#if 0
/* search for cluster with negligible weight and reassign them to fat clusters */
for (i_cl = 0 ; i_cl < numClusters ; ++i_cl) {
if (priors[i_cl] < 0.00001/numClusters) {
double mass = priors[0] ;
vl_index best = 0 ;
for (j_cl = 1 ; j_cl < numClusters ; ++j_cl) {
if (priors[j_cl] > mass) { mass = priors[j_cl] ; best = j_cl ; }
}
if (j_cl == i_cl) {
/* this should never happen */
continue ;
}
j_cl = best ;
zeroWNum ++ ;
VL_PRINTF("gmm: restarting mode %d by splitting mode %d (with prior %f)\n", i_cl,j_cl,mass) ;
priors[i_cl] = mass/2 ;
priors[j_cl] = mass/2 ;
for (d = 0 ; d < dimension ; ++d) {
TYPE sigma2 = covariances[j_cl*dimension + d] ;
TYPE sigma = VL_XCAT(vl_sqrt_,SFX)(sigma2) ;
means[i_cl*dimension + d] = means[j_cl*dimension + d] + 0.001 * (vl_rand_real1(rand) - 0.5) * sigma ;
covariances[i_cl*dimension + d] = sigma2 ;
}
}
}
#endif
/* search for cluster with negligible weight and reassign them to fat clusters */
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
double size = - VL_INFINITY_D ;
vl_index best = -1 ;
if (mass[i_cl] >= VL_GMM_MIN_POSTERIOR *
VL_MAX(1.0, (double) self->numData / self->numClusters))
{
continue ;
}
if (self->verbosity) {
VL_PRINTF("gmm: mode %d is nearly empty (mass %f)\n", i_cl, mass[i_cl]) ;
}
/*
Search for the Gaussian components that (approximately)
maximally contribute to make the negative log-likelihood of the data
large. Then split the worst offender.
To do so, we approximate the exptected log-likelihood of the GMM:
E[-log(f(x))] = H(f) = - log \int f(x) log f(x)
where the density f(x) = sum_k pk gk(x) is a GMM. This is intractable
but it is easy to approximate if we suppose that supp gk is disjoint with
supp gq for all components k ~= q. In this canse
H(f) ~= sum_k [ - pk log(pk) + pk H(gk) ]
where H(gk) is the entropy of component k taken alone. The entropy of
the latter is given by:
H(gk) = D/2 (1 + log(2pi) + 1/2 sum_{i=0}^D log sigma_i^2
*/
for (j_cl = 0 ; j_cl < (signed)numClusters ; ++j_cl) {
double size_ ;
if (priors[j_cl] < VL_GMM_MIN_PRIOR) { continue ; }
size_ = + 0.5 * dimension * (1.0 + log(2*VL_PI)) ;
for(d = 0 ; d < (signed)dimension ; d++) {
double sigma2 = covariances[j_cl * dimension + d] ;
size_ += 0.5 * log(sigma2) ;
}
size_ = priors[j_cl] * (size_ - log(priors[j_cl])) ;
if (self->verbosity > 1) {
VL_PRINTF("gmm: mode %d: prior %f, mass %f, entropy contribution %f\n",
j_cl, priors[j_cl], mass[j_cl], size_) ;
}
if (size_ > size) {
size = size_ ;
best = j_cl ;
}
}
j_cl = best ;
if (j_cl == i_cl || j_cl < 0) {
if (self->verbosity) {
VL_PRINTF("gmm: mode %d is empty, "
"but no other mode to split could be found\n", i_cl) ;
}
continue ;
}
if (self->verbosity) {
VL_PRINTF("gmm: reinitializing empty mode %d with mode %d (prior %f, mass %f, score %f)\n",
i_cl, j_cl, priors[j_cl], mass[j_cl], size) ;
}
/*
Search for the dimension with maximum variance.
*/
size = - VL_INFINITY_D ;
best = - 1 ;
for(d = 0; d < (signed)dimension; d++) {
double sigma2 = covariances[j_cl * dimension + d] ;
if (sigma2 > size) {
size = sigma2 ;
best = d ;
}
}
/*
Reassign points j_cl (mode to split) to i_cl (empty mode).
*/
{
TYPE mu = means[best + j_cl * self->dimension] ;
for(i_d = 0 ; i_d < (signed)self->numData ; ++ i_d) {
TYPE p = posteriors[j_cl + self->numClusters * i_d] ;
TYPE q = posteriors[i_cl + self->numClusters * i_d] ; /* ~= 0 */
if (data[best + i_d * self->dimension] < mu) {
/* assign this point to i_cl */
posteriors[i_cl + self->numClusters * i_d] = p + q ;
posteriors[j_cl + self->numClusters * i_d] = 0 ;
} else {
/* assign this point to j_cl */
posteriors[i_cl + self->numClusters * i_d] = 0 ;
posteriors[j_cl + self->numClusters * i_d] = p + q ;
}
}
}
/*
Re-estimate.
*/
VL_XCAT(_vl_gmm_maximization_, SFX)
(self,posteriors,priors,covariances,means,data,self->numData) ;
}
return zeroWNum;
}
/* ---------------------------------------------------------------- */
/* Helpers */
/* ---------------------------------------------------------------- */
static void
VL_XCAT(_vl_gmm_apply_bounds_, SFX)(VlGMM * self)
{
vl_uindex dim ;
vl_uindex k ;
vl_size numAdjusted = 0 ;
TYPE * cov = (TYPE*)self->covariances ;
double const * lbs = self->sigmaLowBound ;
for (k = 0 ; k < self->numClusters ; ++k) {
vl_bool adjusted = VL_FALSE ;
for (dim = 0 ; dim < self->dimension ; ++dim) {
if (cov[k * self->dimension + dim] < lbs[dim] ) {
cov[k * self->dimension + dim] = lbs[dim] ;
adjusted = VL_TRUE ;
}
}
if (adjusted) { numAdjusted ++ ; }
}
if (numAdjusted > 0 && self->verbosity > 0) {
VL_PRINT("gmm: detected %d of %d modes with at least one dimension "
"with covariance too small (set to lower bound)\n",
numAdjusted, self->numClusters) ;
}
}
/* ---------------------------------------------------------------- */
/* EM - Maximization step */
/* ---------------------------------------------------------------- */
static void
VL_XCAT(_vl_gmm_maximization_, SFX)
(VlGMM * self,
TYPE * posteriors,
TYPE * priors,
TYPE * covariances,
TYPE * means,
TYPE const * data,
vl_size numData)
{
vl_size numClusters = self->numClusters;
vl_index i_d, i_cl;
vl_size dim ;
TYPE * oldMeans ;
double time = 0 ;
if (self->verbosity > 1) {
VL_PRINTF("gmm: em: entering maximization step\n") ;
time = vl_get_cpu_time() ;
}
oldMeans = vl_malloc(sizeof(TYPE) * self->dimension * numClusters) ;
memcpy(oldMeans, means, sizeof(TYPE) * self->dimension * numClusters) ;
memset(priors, 0, sizeof(TYPE) * numClusters) ;
memset(means, 0, sizeof(TYPE) * self->dimension * numClusters) ;
memset(covariances, 0, sizeof(TYPE) * self->dimension * numClusters) ;
#if defined(_OPENMP)
#pragma omp parallel default(shared) private(i_d, i_cl, dim) \
num_threads(vl_get_max_threads())
#endif
{
TYPE * clusterPosteriorSum_, * means_, * covariances_ ;
#if defined(_OPENMP)
#pragma omp critical
#endif
{
clusterPosteriorSum_ = vl_calloc(sizeof(TYPE), numClusters) ;
means_ = vl_calloc(sizeof(TYPE), self->dimension * numClusters) ;
covariances_ = vl_calloc(sizeof(TYPE), self->dimension * numClusters) ;
}
/*
Accumulate weighted sums and sum of square differences. Once normalized,
these become the means and covariances of each Gaussian mode.
The squared differences will be taken w.r.t. the old means however. In this manner,
one avoids doing two passes across the data. Eventually, these are corrected to account
for the new means properly. In principle, one could set the old means to zero, but
this may cause numerical instabilities (by accumulating large squares).
*/
#if defined(_OPENMP)
#pragma omp for
#endif
for (i_d = 0 ; i_d < (signed)numData ; ++i_d) {
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
TYPE p = posteriors[i_cl + i_d * self->numClusters] ;
vl_bool calculated = VL_FALSE ;
/* skip very small associations for speed */
if (p < VL_GMM_MIN_POSTERIOR / numClusters) { continue ; }
clusterPosteriorSum_ [i_cl] += p ;
#ifndef VL_DISABLE_AVX
if (vl_get_simd_enabled() && vl_cpu_has_avx()) {
VL_XCAT(_vl_weighted_mean_sse2_, SFX)
(self->dimension,
means_+ i_cl * self->dimension,
data + i_d * self->dimension,
p) ;
VL_XCAT(_vl_weighted_sigma_sse2_, SFX)
(self->dimension,
covariances_ + i_cl * self->dimension,
data + i_d * self->dimension,
oldMeans + i_cl * self->dimension,
p) ;
calculated = VL_TRUE;
}
#endif
#ifndef VL_DISABLE_SSE2
if (vl_get_simd_enabled() && vl_cpu_has_sse2() && !calculated) {
VL_XCAT(_vl_weighted_mean_sse2_, SFX)
(self->dimension,
means_+ i_cl * self->dimension,
data + i_d * self->dimension,
p) ;
VL_XCAT(_vl_weighted_sigma_sse2_, SFX)
(self->dimension,
covariances_ + i_cl * self->dimension,
data + i_d * self->dimension,
oldMeans + i_cl * self->dimension,
p) ;
calculated = VL_TRUE;
}
#endif
if(!calculated) {
for (dim = 0 ; dim < self->dimension ; ++dim) {
TYPE x = data[i_d * self->dimension + dim] ;
TYPE mu = oldMeans[i_cl * self->dimension + dim] ;
TYPE diff = x - mu ;
means_ [i_cl * self->dimension + dim] += p * x ;
covariances_ [i_cl * self->dimension + dim] += p * (diff*diff) ;
}
}
}
}
/* accumulate */
#if defined(_OPENMP)
#pragma omp critical
#endif
{
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
priors [i_cl] += clusterPosteriorSum_ [i_cl];
for (dim = 0 ; dim < self->dimension ; ++dim) {
means [i_cl * self->dimension + dim] += means_ [i_cl * self->dimension + dim] ;
covariances [i_cl * self->dimension + dim] += covariances_ [i_cl * self->dimension + dim] ;
}
}
vl_free(means_);
vl_free(covariances_);
vl_free(clusterPosteriorSum_);
}
} /* parallel section */
/* at this stage priors[] contains the total mass of each cluster */
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++ i_cl) {
TYPE mass = priors[i_cl] ;
/* do not update modes that do not recieve mass */
if (mass >= 1e-6 / numClusters) {
for (dim = 0 ; dim < self->dimension ; ++dim) {
means[i_cl * self->dimension + dim] /= mass ;
covariances[i_cl * self->dimension + dim] /= mass ;
}
}
}
/* apply old to new means correction */
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++ i_cl) {
TYPE mass = priors[i_cl] ;
if (mass >= 1e-6 / numClusters) {
for (dim = 0 ; dim < self->dimension ; ++dim) {
TYPE mu = means[i_cl * self->dimension + dim] ;
TYPE oldMu = oldMeans[i_cl * self->dimension + dim] ;
TYPE diff = mu - oldMu ;
covariances[i_cl * self->dimension + dim] -= diff * diff ;
}
}
}
VL_XCAT(_vl_gmm_apply_bounds_,SFX)(self) ;
{
TYPE sum = 0;
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
sum += priors[i_cl] ;
}
sum = VL_MAX(sum, 1e-12) ;
for (i_cl = 0 ; i_cl < (signed)numClusters ; ++i_cl) {
priors[i_cl] /= sum ;
}
}
if (self->verbosity > 1) {
VL_PRINTF("gmm: em: maximization step completed in %.2f s\n",
vl_get_cpu_time() - time) ;
}
vl_free(oldMeans);
}
/* ---------------------------------------------------------------- */
/* EM iterations */
/* ---------------------------------------------------------------- */
static double
VL_XCAT(_vl_gmm_em_, SFX)
(VlGMM * self,
TYPE const * data,
vl_size numData)
{
vl_size iteration, restarted ;
double previousLL = (TYPE)(-VL_INFINITY_D) ;
double LL = (TYPE)(-VL_INFINITY_D) ;
double time = 0 ;
_vl_gmm_prepare_for_data (self, numData) ;
VL_XCAT(_vl_gmm_apply_bounds_,SFX)(self) ;
for (iteration = 0 ; 1 ; ++ iteration) {
double eps ;
/*
Expectation: assign data to Gaussian modes
and compute log-likelihood.
*/
if (self->verbosity > 1) {
VL_PRINTF("gmm: em: entering expectation step\n") ;
time = vl_get_cpu_time() ;
}
LL = VL_XCAT(vl_get_gmm_data_posteriors_,SFX)
(self->posteriors,
self->numClusters,
numData,
self->priors,
self->means,
self->dimension,
self->covariances,
data) ;
if (self->verbosity > 1) {
VL_PRINTF("gmm: em: expectation step completed in %.2f s\n",
vl_get_cpu_time() - time) ;
}
/*
Check the termination conditions.
*/
if (self->verbosity) {
VL_PRINTF("gmm: em: iteration %d: loglikelihood = %f (variation = %f)\n",
iteration, LL, LL - previousLL) ;
}
if (iteration >= self->maxNumIterations) {
if (self->verbosity) {
VL_PRINTF("gmm: em: terminating because "
"the maximum number of iterations "
"(%d) has been reached.\n", self->maxNumIterations) ;
}
break ;
}
eps = vl_abs_d ((LL - previousLL) / (LL));
if ((iteration > 0) && (eps < 0.00001)) {
if (self->verbosity) {
VL_PRINTF("gmm: em: terminating because the algorithm "
"fully converged (log-likelihood variation = %f).\n", eps) ;
}
break ;
}
previousLL = LL ;
/*
Restart empty modes.
*/
if (iteration > 1) {
restarted = VL_XCAT(_vl_gmm_restart_empty_modes_, SFX)
(self, data);
if ((restarted > 0) & (self->verbosity > 0)) {
VL_PRINTF("gmm: em: %d Gaussian modes restarted because "
"they had become empty.\n", restarted);
}
}
/*
Maximization: reestimate the GMM parameters.
*/
VL_XCAT(_vl_gmm_maximization_, SFX)
(self,self->posteriors,self->priors,self->covariances,self->means,data,numData) ;
}
return LL;
}
/* ---------------------------------------------------------------- */
/* Kmeans initialization of mixtures */
/* ---------------------------------------------------------------- */
static void
VL_XCAT(_vl_gmm_init_with_kmeans_, SFX)
(VlGMM * self,
TYPE const * data,
vl_size numData,
VlKMeans * kmeansInit)
{
vl_size i_d ;
vl_uint32 * assignments = vl_malloc(sizeof(vl_uint32) * numData);
_vl_gmm_prepare_for_data (self, numData) ;
memset(self->means,0,sizeof(TYPE) * self->numClusters * self->dimension) ;
memset(self->priors,0,sizeof(TYPE) * self->numClusters) ;
memset(self->covariances,0,sizeof(TYPE) * self->numClusters * self->dimension) ;
memset(self->posteriors,0,sizeof(TYPE) * self->numClusters * numData) ;
/* setup speified KMeans initialization object if any */
if (kmeansInit) { vl_gmm_set_kmeans_init_object (self, kmeansInit) ; }
/* if a KMeans initalization object is still unavailable, create one */
if(self->kmeansInit == NULL) {
vl_size ncomparisons = VL_MAX(numData / 4, 10) ;
vl_size niter = 5 ;
vl_size ntrees = 1 ;
vl_size nrepetitions = 1 ;
VlKMeansAlgorithm algorithm = VlKMeansANN ;
VlKMeansInitialization initialization = VlKMeansRandomSelection ;
VlKMeans * kmeansInitDefault = vl_kmeans_new(self->dataType,VlDistanceL2) ;
vl_kmeans_set_initialization(kmeansInitDefault, initialization);
vl_kmeans_set_max_num_iterations (kmeansInitDefault, niter) ;
vl_kmeans_set_max_num_comparisons (kmeansInitDefault, ncomparisons) ;
vl_kmeans_set_num_trees (kmeansInitDefault, ntrees);
vl_kmeans_set_algorithm (kmeansInitDefault, algorithm);
vl_kmeans_set_num_repetitions(kmeansInitDefault, nrepetitions);
vl_kmeans_set_verbosity (kmeansInitDefault, self->verbosity);
self->kmeansInit = kmeansInitDefault;
self->kmeansInitIsOwner = VL_TRUE ;
}
/* Use k-means to assign data to clusters */
vl_kmeans_cluster (self->kmeansInit, data, self->dimension, numData, self->numClusters);
vl_kmeans_quantize (self->kmeansInit, assignments, NULL, data, numData) ;
/* Transform the k-means assignments in posteriors and estimates the mode parameters */
for(i_d = 0; i_d < numData; i_d++) {
((TYPE*)self->posteriors)[assignments[i_d] + i_d * self->numClusters] = (TYPE) 1.0 ;
}
/* Update cluster parameters */
VL_XCAT(_vl_gmm_maximization_, SFX)
(self,self->posteriors,self->priors,self->covariances,self->means,data,numData);
vl_free(assignments) ;
}
/* ---------------------------------------------------------------- */
/* Random initialization of mixtures */
/* ---------------------------------------------------------------- */
static void
VL_XCAT(_vl_gmm_compute_init_sigma_, SFX)
(VlGMM * self,
TYPE const * data,
TYPE * initSigma,
vl_size dimension,
vl_size numData)
{
vl_size dim;
vl_uindex i;
TYPE * dataMean ;
memset(initSigma,0,sizeof(TYPE)*dimension) ;
if (numData <= 1) return ;
dataMean = vl_malloc(sizeof(TYPE)*dimension);
memset(dataMean,0,sizeof(TYPE)*dimension) ;
/* find mean of the whole dataset */
for(dim = 0 ; dim < dimension ; dim++) {
for(i = 0 ; i < numData ; i++) {
dataMean[dim] += data[i*dimension + dim];
}
dataMean[dim] /= numData;
}
/* compute variance of the whole dataset */
for(dim = 0; dim < dimension; dim++) {
for(i = 0; i < numData; i++) {
TYPE diff = (data[i*self->dimension + dim] - dataMean[dim]) ;
initSigma[dim] += diff*diff ;
}
initSigma[dim] /= numData - 1 ;
}
vl_free(dataMean) ;
}
static void
VL_XCAT(_vl_gmm_init_with_rand_data_, SFX)
(VlGMM * self,
TYPE const * data,
vl_size numData)
{
vl_uindex i, k, dim ;
VlKMeans * kmeans ;
_vl_gmm_prepare_for_data(self, numData) ;
/* initilaize priors of gaussians so they are equal and sum to one */
for (i = 0 ; i < self->numClusters ; ++i) { ((TYPE*)self->priors)[i] = (TYPE) (1.0 / self->numClusters) ; }
/* initialize diagonals of covariance matrices to data covariance */
VL_XCAT(_vl_gmm_compute_init_sigma_, SFX) (self, data, self->covariances, self->dimension, numData);
for (k = 1 ; k < self->numClusters ; ++ k) {
for(dim = 0; dim < self->dimension; dim++) {
*((TYPE*)self->covariances + k * self->dimension + dim) =
*((TYPE*)self->covariances + dim) ;
}
}
/* use kmeans++ initialization to pick points at random */
kmeans = vl_kmeans_new(self->dataType,VlDistanceL2) ;
vl_kmeans_init_centers_plus_plus(kmeans, data, self->dimension, numData, self->numClusters) ;
memcpy(self->means, vl_kmeans_get_centers(kmeans), sizeof(TYPE) * self->dimension * self->numClusters) ;
vl_kmeans_delete(kmeans) ;
}
/* ---------------------------------------------------------------- */
#else /* VL_GMM_INSTANTIATING */
/* ---------------------------------------------------------------- */
#ifndef __DOXYGEN__
#define FLT VL_TYPE_FLOAT
#define TYPE float
#define SFX f
#define VL_GMM_INSTANTIATING
#include "gmm.c"
#define FLT VL_TYPE_DOUBLE
#define TYPE double
#define SFX d
#define VL_GMM_INSTANTIATING
#include "gmm.c"
#endif
/* VL_GMM_INSTANTIATING */
#endif
/* ---------------------------------------------------------------- */
#ifndef VL_GMM_INSTANTIATING
/* ---------------------------------------------------------------- */
/** @brief Create a new GMM object by copy
** @param self object.
** @return new copy.
**
** Most parameters, including the cluster priors, means, and
** covariances are copied. Data posteriors (available after
** initalization or EM) are not; nor is the KMeans object used for
** initialization, if any.
**/
VlGMM *
vl_gmm_new_copy (VlGMM const * self)
{
vl_size size = vl_get_type_size(self->dataType) ;
VlGMM * gmm = vl_gmm_new(self->dataType, self->dimension, self->numClusters);
gmm->initialization = self->initialization;
gmm->maxNumIterations = self->maxNumIterations;
gmm->numRepetitions = self->numRepetitions;
gmm->verbosity = self->verbosity;
gmm->LL = self->LL;
memcpy(gmm->means, self->means, size*self->numClusters*self->dimension);
memcpy(gmm->covariances, self->covariances, size*self->numClusters*self->dimension);
memcpy(gmm->priors, self->priors, size*self->numClusters);
return gmm ;
}
/** @brief Initialize mixture before EM takes place using random initialization
** @param self GMM object instance.
** @param data data points which should be clustered.
** @param numData number of data points.
**/
void
vl_gmm_init_with_rand_data
(VlGMM * self,
void const * data,
vl_size numData)
{
vl_gmm_reset (self) ;
switch (self->dataType) {
case VL_TYPE_FLOAT : _vl_gmm_init_with_rand_data_f (self, (float const *)data, numData) ; break ;
case VL_TYPE_DOUBLE : _vl_gmm_init_with_rand_data_d (self, (double const *)data, numData) ; break ;
default:
abort() ;
}
}
/** @brief Initializes the GMM using KMeans
** @param self GMM object instance.
** @param data data points which should be clustered.
** @param numData number of data points.
** @param kmeansInit KMeans object to use.
**/
void
vl_gmm_init_with_kmeans
(VlGMM * self,
void const * data,
vl_size numData,
VlKMeans * kmeansInit)
{
vl_gmm_reset (self) ;
switch (self->dataType) {
case VL_TYPE_FLOAT :
_vl_gmm_init_with_kmeans_f
(self, (float const *)data, numData, kmeansInit) ;
break ;
case VL_TYPE_DOUBLE :
_vl_gmm_init_with_kmeans_d
(self, (double const *)data, numData, kmeansInit) ;
break ;
default:
abort() ;
}
}
#if 0
#include<fenv.h>
#endif
/** @brief Run GMM clustering - includes initialization and EM
** @param self GMM object instance.
** @param data data points which should be clustered.
** @param numData number of data points.
**/
double vl_gmm_cluster (VlGMM * self,
void const * data,
vl_size numData)
{
void * bestPriors = NULL ;
void * bestMeans = NULL;
void * bestCovariances = NULL;
void * bestPosteriors = NULL;
vl_size size = vl_get_type_size(self->dataType) ;
double bestLL = -VL_INFINITY_D;
vl_uindex repetition;
assert(self->numRepetitions >=1) ;
bestPriors = vl_malloc(size * self->numClusters) ;
bestMeans = vl_malloc(size * self->dimension * self->numClusters) ;
bestCovariances = vl_malloc(size * self->dimension * self->numClusters) ;
bestPosteriors = vl_malloc(size * self->numClusters * numData) ;
#if 0
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
#endif
for (repetition = 0 ; repetition < self->numRepetitions ; ++ repetition) {
double LL ;
double timeRef ;
if (self->verbosity) {
VL_PRINTF("gmm: clustering: starting repetition %d of %d\n", repetition + 1, self->numRepetitions) ;
}
/* initialize a new mixture model */
timeRef = vl_get_cpu_time() ;
switch (self->initialization) {
case VlGMMKMeans : vl_gmm_init_with_kmeans (self, data, numData, NULL) ; break ;
case VlGMMRand : vl_gmm_init_with_rand_data (self, data, numData) ; break ;
case VlGMMCustom : break ;
default: abort() ;
}
if (self->verbosity) {
VL_PRINTF("gmm: model initialized in %.2f s\n",
vl_get_cpu_time() - timeRef) ;
}
/* fit the model to data by running EM */
timeRef = vl_get_cpu_time () ;
LL = vl_gmm_em (self, data, numData) ;
if (self->verbosity) {
VL_PRINTF("gmm: optimization terminated in %.2f s with loglikelihood %f\n",
vl_get_cpu_time() - timeRef, LL) ;
}
if (LL > bestLL || repetition == 0) {
void * temp ;
temp = bestPriors ;
bestPriors = self->priors ;
self->priors = temp ;
temp = bestMeans ;
bestMeans = self->means ;
self->means = temp ;
temp = bestCovariances ;
bestCovariances = self->covariances ;
self->covariances = temp ;
temp = bestPosteriors ;
bestPosteriors = self->posteriors ;
self->posteriors = temp ;
bestLL = LL;
}
}
vl_free (self->priors) ;
vl_free (self->means) ;
vl_free (self->covariances) ;
vl_free (self->posteriors) ;
self->priors = bestPriors ;
self->means = bestMeans ;
self->covariances = bestCovariances ;
self->posteriors = bestPosteriors ;
self->LL = bestLL;
if (self->verbosity) {
VL_PRINTF("gmm: all repetitions terminated with final loglikelihood %f\n", self->LL) ;
}
return bestLL ;
}
/** @brief Invoke the EM algorithm.
** @param self GMM object instance.
** @param data data points which should be clustered.
** @param numData number of data points.
**/
double vl_gmm_em (VlGMM * self, void const * data, vl_size numData)
{
switch (self->dataType) {
case VL_TYPE_FLOAT:
return _vl_gmm_em_f (self, (float const *)data, numData) ; break ;
case VL_TYPE_DOUBLE:
return _vl_gmm_em_d (self, (double const *)data, numData) ; break ;
default:
abort() ;
}
return 0 ;
}
/** @brief Explicitly set the initial means for EM.
** @param self GMM object instance.
** @param means initial values of means.
**/
void
vl_gmm_set_means (VlGMM * self, void const * means)
{
memcpy(self->means,means,
self->dimension * self->numClusters * vl_get_type_size(self->dataType));
}
/** @brief Explicitly set the initial sigma diagonals for EM.
** @param self GMM object instance.
** @param covariances initial values of covariance matrix diagonals.
**/
void vl_gmm_set_covariances (VlGMM * self, void const * covariances)
{
memcpy(self->covariances,covariances,
self->dimension * self->numClusters * vl_get_type_size(self->dataType));
}
/** @brief Explicitly set the initial priors of the gaussians.
** @param self GMM object instance.
** @param priors initial values of the gaussian priors.
**/
void vl_gmm_set_priors (VlGMM * self, void const * priors)
{
memcpy(self->priors,priors,
self->numClusters * vl_get_type_size(self->dataType));
}
/* VL_GMM_INSTANTIATING */
#endif
#undef SFX
#undef TYPE
#undef FLT
#undef VL_GMM_INSTANTIATING
|
SparsifyCollapsingMex.c | #include "mex.h"
#include <omp.h>
#include <math.h>
void splitMatrices(mwIndex startRow, mwIndex endRow,
mwIndex* R_A0 , mwIndex *starts_A0, double *V_A0 ,
mwIndex *R_Aomega , mwIndex *starts_Aomega, double *V_Aomega);
void Sparsify(mwIndex startRow, mwIndex endRow, mwIndex naux,
mwIndex* R_A0 , mwIndex *starts_A0, double *V_A0 ,
mwIndex *R_Aomega , mwIndex *starts_Aomega, double *V_Aomega,
mwIndex *R_RP0 , mwIndex *starts_RP0 , double *V_RP0,
mwIndex *R_R0P , mwIndex *starts_R0P , double *V_R0P,
mwIndex *C_A0_cols, mwIndex *starts_A0_cols,double *V_A0_cols, mwIndex* globalDiagonal);
void SparsifyAki(mwIndex k, mwIndex i, double Aki,
mwIndex* R_A0 , mwIndex *starts_A0 , double *V_A0,
mwIndex *R_RP0 , mwIndex *starts_RP0 , double *V_RP0,
mwIndex *C_R0P , mwIndex *starts_R0P , double *V_R0P,
mwIndex *C_A0_cols, mwIndex *starts_A0_cols, double *V_A0_cols,
mwIndex *intI1I2 , mwIndex *auxI1 , mwIndex *auxI2,
mwIndex *auxm1 , mwIndex *auxm2 , double* thetta, mwIndex* globalDiagonal ,mwIndex naux_list);
int intersect(mwIndex* A, mwIndex* B, mwIndex startA, mwIndex endA,
mwIndex startB, mwIndex endB, mwIndex* ans, mwIndex* iA, mwIndex* iB);
// mwIndex setDiff(mwIndex* A, mwIndex* B, mwIndex startA, mwIndex endA,
// mwIndex startB, mwIndex endB, mwIndex* ans, mwIndex* i);
mwIndex findBinarySearch(mwIndex* A, mwIndex startA, mwIndex endA, mwIndex toFind);
void GenerateDiagonalGlobalIndices(mwIndex startRow, mwIndex endRow,
mwIndex* R_A0, mwIndex* starts_A0, mwIndex* globalDiagonal);
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
//mex -O 'CXXOPTIMFLAGS=-DNDEBUG -O3' -largeArrayDims SparsifyCollapsingMex.c COMPFLAGS="$COMPFLAGS -openmp" LINKFALGS="$LINKFALGS -openmp"
mwIndex id, Nthrds, istart, iend;
mwIndex naux = 0;
// //
mwIndex *R_A0 = mxGetIr(prhs[0]);
mwIndex *starts_A0 = mxGetJc(prhs[0]);
double *V_A0 = mxGetPr(prhs[0]);
//mwIndex nzmax_A0 = mxGetNzmax(prhs[0]);
mwIndex n = mxGetN(prhs[0]);
mwIndex *R_Aomega = mxGetIr(prhs[1]);
mwIndex *starts_Aomega = mxGetJc(prhs[1]);
double *V_Aomega = mxGetPr(prhs[1]);
mwIndex nzmax_Aomega = mxGetNzmax(prhs[1]);
mwIndex *R_RP0 = mxGetIr(prhs[2]);
mwIndex *starts_RP0 = mxGetJc(prhs[2]);
double *V_RP0 = mxGetPr(prhs[2]);
mwIndex *C_R0P = mxGetIr(prhs[3]);
mwIndex *starts_R0P = mxGetJc(prhs[3]);
double *V_R0P = mxGetPr(prhs[3]);
mwIndex *C_A0_cols = mxGetIr(prhs[4]);
mwIndex *starts_A0_cols = mxGetJc(prhs[4]);
double *V_A0_cols = mxGetPr(prhs[4]);
mwIndex* globalDiagonal = (mwIndex*)malloc(n*sizeof(mwIndex));
#pragma omp parallel private(id, Nthrds, istart, iend) num_threads(omp_get_num_procs())
{
//printf("%d",);
id = omp_get_thread_num();
Nthrds = omp_get_num_threads();
istart = id * n / Nthrds;
iend = (id+1) * n / Nthrds;
if (id == Nthrds-1) iend = n;
splitMatrices(istart, iend, R_A0, starts_A0, V_A0, R_Aomega, starts_Aomega, V_Aomega);
#pragma omp barrier
GenerateDiagonalGlobalIndices(0,n,R_A0,starts_A0,globalDiagonal);
#pragma omp barrier
Sparsify(istart,iend,naux, R_A0 , starts_A0, V_A0, R_Aomega, starts_Aomega, V_Aomega,
R_RP0, starts_RP0, V_RP0, C_R0P, starts_R0P, V_R0P,
C_A0_cols, starts_A0_cols, V_A0_cols,globalDiagonal);
#pragma omp barrier
}
free(globalDiagonal);
}
void Sparsify(mwIndex startRow, mwIndex endRow, mwIndex naux,
mwIndex* R_A0 , mwIndex *starts_A0, double *V_A0 ,
mwIndex *R_Aomega , mwIndex *starts_Aomega, double *V_Aomega,
mwIndex *R_RP0 , mwIndex *starts_RP0 , double *V_RP0,
mwIndex *C_R0P , mwIndex *starts_R0P , double *V_R0P,
mwIndex *C_A0_cols, mwIndex *starts_A0_cols,double *V_A0_cols, mwIndex* globalDiagonal){
mwIndex k,i, global_idx, naux_list;
mwIndex *intI1I2, *auxI1, *auxI2, *auxm1, *auxm2;
double *thetta;
double Aki;
for (k = startRow ; k < endRow ;++k){
if ((starts_A0[k+1] - starts_A0[k])>naux){
naux = (starts_A0[k+1] - starts_A0[k]);
}
}
for (k = startRow ; k < endRow ;++k){
if ((starts_A0_cols[k+1] - starts_A0_cols[k])>naux){
naux = (starts_A0_cols[k+1] - starts_A0_cols[k]);
}
}
naux = naux + 5;
naux_list = naux*naux;
intI1I2 = (mwIndex*)malloc(naux*sizeof(mwIndex));
auxI1 = (mwIndex*)malloc(naux*sizeof(mwIndex));
auxI2 = (mwIndex*)malloc(naux*sizeof(mwIndex));
auxm1 = (mwIndex*)malloc(naux_list*sizeof(mwIndex));
auxm2 = (mwIndex*)malloc(naux_list*sizeof(mwIndex));
thetta = (double*)malloc(naux_list*sizeof(double));
for (k = startRow ; k < endRow ;++k){
for (global_idx = starts_Aomega[k] ; global_idx < starts_Aomega[k+1]; ++global_idx){
Aki = V_Aomega[global_idx];
i = R_Aomega[global_idx];
if (Aki!=0){
//printf("Sparsifing (%d,%d,%lf)\n",k,i,Aki);
SparsifyAki(k,i,Aki,R_A0 , starts_A0, V_A0,
R_RP0, starts_RP0, V_RP0, C_R0P, starts_R0P, V_R0P,
C_A0_cols, starts_A0_cols, V_A0_cols,
intI1I2, auxI1, auxI2, auxm1, auxm2, thetta, globalDiagonal,naux_list);
}
}
}
free(intI1I2);
free(auxI1);
free(auxI2);
free(auxm1);
free(auxm2);
free(thetta);
}
void SparsifyAki(mwIndex k, mwIndex i, double Aki,
mwIndex* R_A0 , mwIndex *starts_A0 , double *V_A0,
mwIndex *R_RP0 , mwIndex *starts_RP0 , double *V_RP0,
mwIndex *C_R0P , mwIndex *starts_R0P , double *V_R0P,
mwIndex *C_A0_cols, mwIndex *starts_A0_cols, double *V_A0_cols,
mwIndex *intI1I2 , mwIndex *auxI1 , mwIndex *auxI2,
mwIndex *auxm1 , mwIndex *auxm2 , double* thetta, mwIndex* globalDiagonal ,mwIndex naux_list){
mwIndex m1,m2, it, n_intersect, n_intersect2, m1it, list_it,
global_km2,global_m1i,global_m1m1,global_m2m2,global_m2m1,kk;
mwIndex *tmp_ind=0;
double *tmp_double=0;
double delta,R0Pm1i;
// printf("k:%ld, i:%ld, Aki: %lf\n",k,i,Aki);
// Now we check distance 2 paths between i and k
n_intersect = intersect(C_R0P , R_RP0, starts_R0P[i] , starts_R0P[i+1],
starts_RP0[k], starts_RP0[k+1],intI1I2, auxI1, auxI2);
//printf("n_intersect: %d\n",n_intersect);
if (n_intersect > 0){
delta = 0;
for (it = 0 ; it < n_intersect ; it++){
thetta[it] = fabs(V_R0P[auxI1[it]]*V_RP0[auxI2[it]]);
//printf("mex: V_R0P:%lf; V_RP0: %lf\n",V_R0P[auxI1[it]],V_RP0[auxI2[it]]);
delta += thetta[it];
}
delta = Aki/delta;
for (it = 0 ; it < n_intersect ; it++){
thetta[it] *= delta;
}
for (it = 0 ; it < n_intersect ; it++){
m1 = intI1I2[it];
delta = thetta[it];
// printf("mex: %ld->%ld->%ld:%lf\n",i,m1,k,delta);
// Here: m1==m2
// here we assume that A0 contains R0P and P0R
global_km2 = findBinarySearch(R_A0, starts_A0[k], starts_A0[k+1], m1);
global_m1i = findBinarySearch(R_A0, starts_A0[m1], starts_A0[m1+1], i);
global_m1m1 = globalDiagonal[m1];
// global_m1m1 = findBinarySearch(R_A0, starts_A0[m1], starts_A0[m1+1], m1);
#pragma omp atomic
V_A0[global_km2] += delta;
#pragma omp atomic
V_A0[global_m1i] += delta;
#pragma omp atomic
V_A0[global_m1m1] -= delta;
}
}else{
// Now there is no distance 2 path. We seek distance 3 paths.
list_it = 0;
delta = 0;
for (m1it = starts_R0P[i] ; m1it < starts_R0P[i+1] ; m1it++){
m1 = C_R0P[m1it];
R0Pm1i = V_R0P[m1it];
n_intersect2 = intersect(C_A0_cols , R_RP0, starts_A0_cols[m1] , starts_A0_cols[m1+1],
starts_RP0[k], starts_RP0[k+1],intI1I2, auxI1, auxI2);
for (it = 0 ; it < n_intersect2 ; it++){
auxm1[list_it] = m1;
auxm2[list_it] = intI1I2[it];
thetta[list_it] = fabs(R0Pm1i*V_A0_cols[auxI1[it]]*V_RP0[auxI2[it]]);
delta+=thetta[list_it];
++list_it;
if (list_it == naux_list){
printf("We're out of place in auxiliary arrays, but don't worry - we double naux_list\n");
tmp_ind = (mwIndex*)malloc(2*naux_list*sizeof(mwIndex));
for (kk=0 ; kk<naux_list ; ++kk){
tmp_ind[kk] = auxm1[kk];
}
free(auxm1);
auxm1 = tmp_ind;
tmp_ind = (mwIndex*)malloc(2*naux_list*sizeof(mwIndex));
for (kk=0 ; kk<naux_list ; ++kk){
tmp_ind[kk] = auxm2[kk];
}
free(auxm2);
auxm2 = tmp_ind;
tmp_double = (double*)malloc(2*naux_list*sizeof(double));
for (kk=0 ; kk<naux_list ; ++kk){
tmp_double[kk] = thetta[kk];
}
free(thetta);
thetta = tmp_double;
return;
}
}
}
delta = Aki/delta;
for (it = 0 ; it < list_it ; it++){
thetta[it] *= delta;
}
for (it = 0 ; it < list_it ; it++){
m1 = auxm1[it];
m2 = auxm2[it];
delta = thetta[it];
// printf("mex: %ld->%ld->%ld->%ld:%lf\n",i,m1,m2,k,delta);
global_km2 = findBinarySearch(R_A0, starts_A0[k], starts_A0[k+1], m2);
global_m1i = findBinarySearch(R_A0, starts_A0[m1], starts_A0[m1+1], i);
// global_m1m1 = findBinarySearch(R_A0, starts_A0[m1], starts_A0[m1+1], m1);
// global_m2m2 = findBinarySearch(R_A0, starts_A0[m2], starts_A0[m2+1], m2);
global_m2m2 = globalDiagonal[m2];
global_m1m1 = globalDiagonal[m1];
global_m2m1 = findBinarySearch(R_A0, starts_A0[m2], starts_A0[m2+1], m1);
#pragma omp atomic
V_A0[global_m2m2] -= delta;
#pragma omp atomic
V_A0[global_m2m1] += delta;
#pragma omp atomic
V_A0[global_km2] += delta;
#pragma omp atomic
V_A0[global_m1i] += delta;
#pragma omp atomic
V_A0[global_m1m1] -= delta;
}
}
}
void GenerateDiagonalGlobalIndices(mwIndex startRow, mwIndex endRow,
mwIndex* R_A0, mwIndex* starts_A0, mwIndex* globalDiagonal){
mwIndex k;
for (k = startRow ; k < endRow ;++k){
globalDiagonal[k] = findBinarySearch(R_A0, starts_A0[k], starts_A0[k+1], k);
}
}
void splitMatrices(mwIndex startRow, mwIndex endRow,
mwIndex* R_A0 , mwIndex *starts_A0, double *V_A0 ,
mwIndex *R_Aomega , mwIndex *starts_Aomega, double *V_Aomega){
mwIndex k,global_idx0, global_idx,tmp0, tmpOmega;
// SPLITTING
for (k = startRow ; k < endRow ;++k){
for (global_idx0 = starts_A0[k] ; global_idx0 < starts_A0[k+1] ; ++global_idx0){
V_A0[global_idx0] = 0;
}
global_idx0 = starts_A0[k];
global_idx = starts_Aomega[k];
while (global_idx < starts_Aomega[k+1] && global_idx0 < starts_A0[k+1]){
tmp0 = R_A0[global_idx0];
tmpOmega = R_Aomega[global_idx];
if (tmp0 == tmpOmega){
V_A0[global_idx0] = V_Aomega[global_idx];
V_Aomega[global_idx] = 0;
++global_idx0;
++global_idx;
}else{
global_idx0 += (tmp0 < tmpOmega);
global_idx += (tmp0 > tmpOmega);
}
}
}
}
int intersect(mwIndex* A, mwIndex* B, mwIndex startA, mwIndex endA,
mwIndex startB, mwIndex endB, mwIndex* AB, mwIndex* iA, mwIndex* iB)
{
mwIndex ia = startA, ib = startB;
mwIndex k = 0;
mwIndex tmpA,tmpB;
if (A[startA] > B[endB-1] || A[endA-1] < B[startB]){
return k;
}
while ((ia < endA) && (ib < endB)){
tmpA = A[ia];
tmpB = B[ib];
if (tmpA == tmpB){
AB[k] = tmpA;
iA[k] = ia++;
iB[k] = ib++;
++k;
}else{
ia += tmpA < tmpB;
ib += tmpA > tmpB;
}
}
return k;
}
mwIndex findBinarySearch(mwIndex* A, mwIndex startA, mwIndex endA, mwIndex toFind){
mwIndex i;
for (i = startA ; i < endA ; ++i){
if (A[i]==toFind){
return i;
}
}
printf("INDEX NOT FOUND!!! IMPOSSIBLE - THERE'S A BUG");
return 0;
// mwIndex mid;
// endA = endA-1;
// // continually narrow search until just one element remains
// while (startA < endA)
// {
// mid = (startA+endA)>>1;
// // printf("mid = %ld\n",mid);
// // reduce the search
// if (A[mid] < toFind){
// startA = mid+1;
// // printf("start = %ld\n",startA);
// }else{
// endA = mid;
// // printf("end = %ld\n",endA);
// }
// }
// if ((endA == startA) && (A[startA] == toFind))
// return startA;
// else{
// printf("INDEX NOT FOUND!!! IMPOSSIBLE - THERE'S A BUG");
// return 0;
// }
}
// mwIndex setDiff(mwIndex* A, mwIndex* B, mwIndex startA, mwIndex endA,
// mwIndex startB, mwIndex endB, mwIndex* AB, mwIndex* IA){
// mwIndex ia = startA, ib = startB;
// mwIndex k = 0;
// mwIndex tmpA,tmpB;
// while ((ia < endA) && (ib < endB)){
// tmpA = A[ia];
// tmpB = B[ib];
// if (tmpA < tmpB){
// IA[k] = ++ia;
// AB[k] = tmpA;
// ++k;
// }else{
// ia += tmpA == tmpB;
// ib += tmpA >= tmpB;
// }
// }
// while (ia < endA){
// AB[k] = A[ia];
// IA[k] = ++ia;
// ++k;
// }
// }
// |
ZQ_CNN_MTCNN_NCHWC.h | #ifndef _ZQ_CNN_MTCNN_NCHWC_H_
#define _ZQ_CNN_MTCNN_NCHWC_H_
#pragma once
#include "ZQ_CNN_Net_NCHWC.h"
#include "ZQ_CNN_BBoxUtils.h"
#include <omp.h>
namespace ZQ
{
class ZQ_CNN_MTCNN_NCHWC
{
public:
using string = std::string;
ZQ_CNN_MTCNN_NCHWC()
{
min_size = 60;
thresh[0] = 0.6;
thresh[1] = 0.7;
thresh[2] = 0.7;
nms_thresh[0] = 0.6;
nms_thresh[1] = 0.7;
nms_thresh[2] = 0.7;
width = 0;
height = 0;
factor = 0.709;
pnet_overlap_thresh_count = 4;
pnet_size = 12;
pnet_stride = 2;
special_handle_very_big_face = false;
force_run_pnet_multithread = false;
show_debug_info = false;
limit_r_num = 0;
limit_o_num = 0;
limit_l_num = 0;
}
~ZQ_CNN_MTCNN_NCHWC()
{
}
private:
#if __ARM_NEON
const int BATCH_SIZE = 16;
#else
const int BATCH_SIZE = 64;
#endif
std::vector<ZQ_CNN_Net_NCHWC<ZQ_CNN_Tensor4D_NCHWC4>> pnet, rnet, onet, lnet;
bool has_lnet;
int thread_num;
float thresh[3], nms_thresh[3];
int min_size;
int width, height;
float factor;
int pnet_overlap_thresh_count;
int pnet_size;
int pnet_stride;
int rnet_size;
int onet_size;
int lnet_size;
bool special_handle_very_big_face;
bool do_landmark;
float early_accept_thresh;
float nms_thresh_per_scale;
bool force_run_pnet_multithread;
std::vector<float> scales;
std::vector<ZQ_CNN_Tensor4D_NCHWC4> pnet_images;
ZQ_CNN_Tensor4D_NCHWC4 input, rnet_image, onet_image;
bool show_debug_info;
int limit_r_num;
int limit_o_num;
int limit_l_num;
public:
void TurnOnShowDebugInfo() { show_debug_info = true; }
void TurnOffShowDebugInfo() { show_debug_info = false; }
void SetLimit(int limit_r = 0, int limit_o = 0, int limit_l = 0)
{
limit_r_num = limit_r;
limit_o_num = limit_o;
limit_l_num = limit_l;
}
bool Init(const string& pnet_param, const string& pnet_model, const string& rnet_param, const string& rnet_model,
const string& onet_param, const string& onet_model, int thread_num = 1,
bool has_lnet = false, const string& lnet_param = "", const std::string& lnet_model = "")
{
if (thread_num < 1)
force_run_pnet_multithread = true;
else
force_run_pnet_multithread = false;
thread_num = __max(1, thread_num);
pnet.resize(thread_num);
rnet.resize(thread_num);
onet.resize(thread_num);
this->has_lnet = has_lnet;
if (has_lnet)
{
lnet.resize(thread_num);
}
bool ret = true;
for (int i = 0; i < thread_num; i++)
{
ret = pnet[i].LoadFrom(pnet_param, pnet_model, true, 1e-9, true)
&& rnet[i].LoadFrom(rnet_param, rnet_model, true, 1e-9, true)
&& onet[i].LoadFrom(onet_param, onet_model, true, 1e-9, true);
if (has_lnet && ret)
ret = lnet[i].LoadFrom(lnet_param, lnet_model, true, 1e-9, true);
if (!ret)
break;
}
if (!ret)
{
pnet.clear();
rnet.clear();
onet.clear();
if (has_lnet)
lnet.clear();
this->thread_num = 0;
}
else
this->thread_num = thread_num;
if (show_debug_info)
{
printf("rnet = %.1f M, onet = %.1f M\n", rnet[0].GetNumOfMulAdd() / (1024.0*1024.0),
onet[0].GetNumOfMulAdd() / (1024.0*1024.0));
if (has_lnet)
printf("lnet = %.1f M\n", lnet[0].GetNumOfMulAdd() / (1024.0*1024.0));
}
int C, H, W;
rnet[0].GetInputDim(C, H, W);
rnet_size = H;
onet[0].GetInputDim(C, H, W);
onet_size = H;
if (has_lnet)
{
lnet[0].GetInputDim(C, H, W);
lnet_size = H;
}
return ret;
}
bool InitFromBuffer(
const char* pnet_param, __int64 pnet_param_len, const char* pnet_model, __int64 pnet_model_len,
const char* rnet_param, __int64 rnet_param_len, const char* rnet_model, __int64 rnet_model_len,
const char* onet_param, __int64 onet_param_len, const char* onet_model, __int64 onet_model_len,
int thread_num = 1, bool has_lnet = false,
const char* lnet_param = 0, __int64 lnet_param_len = 0, const char* lnet_model = 0, __int64 lnet_model_len = 0)
{
if (thread_num < 1)
force_run_pnet_multithread = true;
else
force_run_pnet_multithread = false;
thread_num = __max(1, thread_num);
pnet.resize(thread_num);
rnet.resize(thread_num);
onet.resize(thread_num);
this->has_lnet = has_lnet;
if (has_lnet)
lnet.resize(thread_num);
bool ret = true;
for (int i = 0; i < thread_num; i++)
{
ret = pnet[i].LoadFromBuffer(pnet_param, pnet_param_len, pnet_model, pnet_model_len, true, 1e-9, true)
&& rnet[i].LoadFromBuffer(rnet_param, rnet_param_len, rnet_model, rnet_model_len, true, 1e-9, true)
&& onet[i].LoadFromBuffer(onet_param, onet_param_len, onet_model, onet_model_len, true, 1e-9, true);
if (has_lnet && ret)
ret = lnet[i].LoadFromBuffer(lnet_param, lnet_param_len, lnet_model, lnet_model_len, true, 1e-9, true);
if (!ret)
break;
}
if (!ret)
{
pnet.clear();
rnet.clear();
onet.clear();
if (has_lnet)
lnet.clear();
this->thread_num = 0;
}
else
this->thread_num = thread_num;
if (show_debug_info)
{
printf("rnet = %.1f M, onet = %.1f M\n", rnet[0].GetNumOfMulAdd() / (1024.0*1024.0),
onet[0].GetNumOfMulAdd() / (1024.0*1024.0));
if (has_lnet)
printf("lnet = %.1f M\n", lnet[0].GetNumOfMulAdd() / (1024.0*1024.0));
}
int C, H, W;
rnet[0].GetInputDim(C, H, W);
rnet_size = H;
onet[0].GetInputDim(C, H, W);
onet_size = H;
return ret;
}
void SetPara(int w, int h, int min_face_size = 60, float pthresh = 0.6, float rthresh = 0.7, float othresh = 0.7,
float nms_pthresh = 0.6, float nms_rthresh = 0.7, float nms_othresh = 0.7, float scale_factor = 0.709,
int pnet_overlap_thresh_count = 4, int pnet_size = 12, int pnet_stride = 2, bool special_handle_very_big_face = false,
bool do_landmark = true, float early_accept_thresh = 1.00)
{
min_size = __max(pnet_size, min_face_size);
thresh[0] = __max(0.1, pthresh); thresh[1] = __max(0.1, rthresh); thresh[2] = __max(0.1, othresh);
nms_thresh[0] = __max(0.1, nms_pthresh); nms_thresh[1] = __max(0.1, nms_rthresh); nms_thresh[2] = __max(0.1, nms_othresh);
scale_factor = __max(0.5, __min(0.97, scale_factor));
this->pnet_overlap_thresh_count = __max(0, pnet_overlap_thresh_count);
this->pnet_size = pnet_size;
this->pnet_stride = pnet_stride;
this->special_handle_very_big_face = special_handle_very_big_face;
this->do_landmark = do_landmark;
this->early_accept_thresh = early_accept_thresh;
if (pnet_size == 20 && pnet_stride == 4)
nms_thresh_per_scale = 0.45;
else
nms_thresh_per_scale = 0.495;
if (width != w || height != h || factor != scale_factor)
{
scales.clear();
pnet_images.clear();
width = w; height = h;
float minside = __min(width, height);
int MIN_DET_SIZE = pnet_size;
float m = (float)MIN_DET_SIZE / min_size;
minside *= m;
while (minside > MIN_DET_SIZE)
{
scales.push_back(m);
minside *= factor;
m *= factor;
}
minside = __min(width, height);
int count = scales.size();
for (int i = scales.size() - 1; i >= 0; i--)
{
if (ceil(scales[i] * minside) <= pnet_size)
{
count--;
}
}
if (special_handle_very_big_face)
{
if (count > 2)
count--;
scales.resize(count);
if (count > 0)
{
float last_size = ceil(scales[count - 1] * minside);
for (int tmp_size = last_size - 1; tmp_size >= pnet_size + 1; tmp_size -= 2)
{
scales.push_back((float)tmp_size / minside);
count++;
}
}
scales.push_back((float)pnet_size / minside);
count++;
}
else
{
scales.push_back((float)pnet_size / minside);
count++;
}
pnet_images.resize(count);
}
}
bool Find(const unsigned char* bgr_img, int _width, int _height, int _widthStep, std::vector<ZQ_CNN_BBox>& results)
{
double t1 = omp_get_wtime();
std::vector<ZQ_CNN_BBox> firstBbox, secondBbox, thirdBbox;
if (!_Pnet_stage(bgr_img, _width, _height, _widthStep, firstBbox))
return false;
//results = firstBbox;
//return true;
if (limit_r_num > 0)
{
_select(firstBbox, limit_r_num, _width, _height);
}
double t2 = omp_get_wtime();
if (!_Rnet_stage(firstBbox, secondBbox))
return false;
//results = secondBbox;
//return true;
if (limit_o_num > 0)
{
_select(secondBbox, limit_o_num, _width, _height);
}
if (!has_lnet || !do_landmark)
{
double t3 = omp_get_wtime();
if (!_Onet_stage(secondBbox, results))
return false;
double t4 = omp_get_wtime();
if (show_debug_info)
{
printf("final found num: %d\n", (int)results.size());
printf("total cost: %.3f ms (P: %.3f ms, R: %.3f ms, O: %.3f ms)\n",
1000 * (t4 - t1), 1000 * (t2 - t1), 1000 * (t3 - t2), 1000 * (t4 - t3));
}
}
else
{
double t3 = omp_get_wtime();
if (!_Onet_stage(secondBbox, thirdBbox))
return false;
if (limit_l_num > 0)
{
_select(thirdBbox, limit_l_num, _width, _height);
}
double t4 = omp_get_wtime();
if (!_Lnet_stage(thirdBbox, results))
return false;
double t5 = omp_get_wtime();
if (show_debug_info)
{
printf("final found num: %d\n", (int)results.size());
printf("total cost: %.3f ms (P: %.3f ms, R: %.3f ms, O: %.3f ms, L: %.3f ms)\n",
1000 * (t5 - t1), 1000 * (t2 - t1), 1000 * (t3 - t2), 1000 * (t4 - t3), 1000 * (t5 - t4));
}
}
return true;
}
bool Find106(const unsigned char* bgr_img, int _width, int _height, int _widthStep, std::vector<ZQ_CNN_BBox106>& results)
{
double t1 = omp_get_wtime();
std::vector<ZQ_CNN_BBox> firstBbox, secondBbox, thirdBbox;
if (!_Pnet_stage(bgr_img, _width, _height, _widthStep, firstBbox))
return false;
//results = firstBbox;
//return true;
if (limit_r_num > 0)
{
_select(firstBbox, limit_r_num, _width, _height);
}
double t2 = omp_get_wtime();
if (!_Rnet_stage(firstBbox, secondBbox))
return false;
//results = secondBbox;
//return true;
if (limit_o_num > 0)
{
_select(secondBbox, limit_o_num, _width, _height);
}
if (!has_lnet || !do_landmark)
{
return false;
}
double t3 = omp_get_wtime();
if (!_Onet_stage(secondBbox, thirdBbox))
return false;
if (limit_l_num > 0)
{
_select(thirdBbox, limit_l_num, _width, _height);
}
double t4 = omp_get_wtime();
if (!_Lnet106_stage(thirdBbox, results))
return false;
double t5 = omp_get_wtime();
if (show_debug_info)
{
printf("final found num: %d\n", (int)results.size());
printf("total cost: %.3f ms (P: %.3f ms, R: %.3f ms, O: %.3f ms, L: %.3f ms)\n",
1000 * (t5 - t1), 1000 * (t2 - t1), 1000 * (t3 - t2), 1000 * (t4 - t3), 1000 * (t5 - t4));
}
return true;
}
private:
void _compute_Pnet_single_thread(std::vector<std::vector<float> >& maps,
std::vector<int>& mapH, std::vector<int>& mapW)
{
int scale_num = 0;
for (int i = 0; i < scales.size(); i++)
{
int changedH = (int)ceil(height*scales[i]);
int changedW = (int)ceil(width*scales[i]);
if (changedH < pnet_size || changedW < pnet_size)
continue;
scale_num++;
mapH.push_back((changedH - pnet_size) / pnet_stride + 1);
mapW.push_back((changedW - pnet_size) / pnet_stride + 1);
}
maps.resize(scale_num);
for (int i = 0; i < scale_num; i++)
{
maps[i].resize(mapH[i] * mapW[i]);
}
for (int i = 0; i < scale_num; i++)
{
int changedH = (int)ceil(height*scales[i]);
int changedW = (int)ceil(width*scales[i]);
float cur_scale_x = (float)width / changedW;
float cur_scale_y = (float)height / changedH;
double t10 = omp_get_wtime();
if (scales[i] != 1)
{
input.ResizeBilinear(pnet_images[i], changedW, changedH, 0, 0);
}
double t11 = omp_get_wtime();
if (scales[i] != 1)
pnet[0].Forward(pnet_images[i]);
else
pnet[0].Forward(input);
double t12 = omp_get_wtime();
if (show_debug_info)
printf("Pnet [%d]: resolution [%dx%d], resize:%.3f ms, cost:%.3f ms\n",
i, changedW, changedH, 1000 * (t11 - t10), 1000 * (t12 - t11));
const ZQ_CNN_Tensor4D_NCHWC4* score = pnet[0].GetBlobByName("prob1");
//score p
int scoreH = score->GetH();
int scoreW = score->GetW();
int scorePixStep = score->GetAlignSize();
const float *p = score->GetFirstPixelPtr() + 1;
for (int row = 0; row < scoreH; row++)
{
for (int col = 0; col < scoreW; col++)
{
if (row < mapH[i] && col < mapW[i])
maps[i][row*mapW[i] + col] = *p;
p += scorePixStep;
}
}
}
}
void _compute_Pnet_multi_thread(std::vector<std::vector<float> >& maps,
std::vector<int>& mapH, std::vector<int>& mapW)
{
if (thread_num <= 1)
{
for (int i = 0; i < scales.size(); i++)
{
int changedH = (int)ceil(height*scales[i]);
int changedW = (int)ceil(width*scales[i]);
if (changedH < pnet_size || changedW < pnet_size)
continue;
if (scales[i] != 1)
{
input.ResizeBilinear(pnet_images[i], changedW, changedH, 0, 0);
}
}
}
else
{
#pragma omp parallel for num_threads(thread_num) schedule(dynamic, 1)
for (int i = 0; i < scales.size(); i++)
{
int changedH = (int)ceil(height*scales[i]);
int changedW = (int)ceil(width*scales[i]);
if (changedH < pnet_size || changedW < pnet_size)
continue;
if (scales[i] != 1)
{
input.ResizeBilinear(pnet_images[i], changedW, changedH, 0, 0);
}
}
}
int scale_num = 0;
for (int i = 0; i < scales.size(); i++)
{
int changedH = (int)ceil(height*scales[i]);
int changedW = (int)ceil(width*scales[i]);
if (changedH < pnet_size || changedW < pnet_size)
continue;
scale_num++;
mapH.push_back((changedH - pnet_size) / pnet_stride + 1);
mapW.push_back((changedW - pnet_size) / pnet_stride + 1);
}
maps.resize(scale_num);
for (int i = 0; i < scale_num; i++)
{
maps[i].resize(mapH[i] * mapW[i]);
}
std::vector<int> task_rect_off_x;
std::vector<int> task_rect_off_y;
std::vector<int> task_rect_width;
std::vector<int> task_rect_height;
std::vector<float> task_scale;
std::vector<int> task_scale_id;
int stride = pnet_stride;
const int block_size = 64 * stride;
int cellsize = pnet_size;
int border_size = cellsize - stride;
int overlap_border_size = cellsize / stride;
int jump_size = block_size - border_size;
for (int i = 0; i < scales.size(); i++)
{
int changeH = (int)ceil(height*scales[i]);
int changeW = (int)ceil(width*scales[i]);
if (changeH < pnet_size || changeW < pnet_size)
continue;
int block_H_num = 0;
int block_W_num = 0;
int start = 0;
while (start < changeH)
{
block_H_num++;
if (start + block_size >= changeH)
break;
start += jump_size;
}
start = 0;
while (start < changeW)
{
block_W_num++;
if (start + block_size >= changeW)
break;
start += jump_size;
}
for (int s = 0; s < block_H_num; s++)
{
for (int t = 0; t < block_W_num; t++)
{
int rect_off_x = t * jump_size;
int rect_off_y = s * jump_size;
int rect_width = __min(changeW, rect_off_x + block_size) - rect_off_x;
int rect_height = __min(changeH, rect_off_y + block_size) - rect_off_y;
if (rect_width >= cellsize && rect_height >= cellsize)
{
task_rect_off_x.push_back(rect_off_x);
task_rect_off_y.push_back(rect_off_y);
task_rect_width.push_back(rect_width);
task_rect_height.push_back(rect_height);
task_scale.push_back(scales[i]);
task_scale_id.push_back(i);
}
}
}
}
//
int task_num = task_scale.size();
std::vector<ZQ_CNN_Tensor4D_NCHWC4> task_pnet_images(thread_num);
if (thread_num <= 1)
{
for (int i = 0; i < task_num; i++)
{
int thread_id = omp_get_thread_num();
int scale_id = task_scale_id[i];
float cur_scale = task_scale[i];
int i_rect_off_x = task_rect_off_x[i];
int i_rect_off_y = task_rect_off_y[i];
int i_rect_width = task_rect_width[i];
int i_rect_height = task_rect_height[i];
if (scale_id == 0 && scales[0] == 1)
{
if (!input.ROI(task_pnet_images[thread_id],
i_rect_off_x, i_rect_off_y, i_rect_width, i_rect_height, 0, 0))
continue;
}
else
{
if (!pnet_images[scale_id].ROI(task_pnet_images[thread_id],
i_rect_off_x, i_rect_off_y, i_rect_width, i_rect_height, 0, 0))
continue;
}
if (!pnet[thread_id].Forward(task_pnet_images[thread_id]))
continue;
const ZQ_CNN_Tensor4D_NCHWC4* score = pnet[thread_id].GetBlobByName("prob1");
int task_count = 0;
//score p
int scoreH = score->GetH();
int scoreW = score->GetW();
int scorePixStep = score->GetAlignSize();
const float *p = score->GetFirstPixelPtr() + 1;
ZQ_CNN_BBox bbox;
ZQ_CNN_OrderScore order;
for (int row = 0; row < scoreH; row++)
{
for (int col = 0; col < scoreW; col++)
{
int real_row = row + i_rect_off_y / stride;
int real_col = col + i_rect_off_x / stride;
if (real_row < mapH[scale_id] && real_col < mapW[scale_id])
maps[scale_id][real_row*mapW[scale_id] + real_col] = *p;
p += scorePixStep;
}
}
}
}
else
{
#pragma omp parallel for num_threads(thread_num)
for (int i = 0; i < task_num; i++)
{
int thread_id = omp_get_thread_num();
int scale_id = task_scale_id[i];
float cur_scale = task_scale[i];
int i_rect_off_x = task_rect_off_x[i];
int i_rect_off_y = task_rect_off_y[i];
int i_rect_width = task_rect_width[i];
int i_rect_height = task_rect_height[i];
if (scale_id == 0 && scales[0] == 1)
{
if (!input.ROI(task_pnet_images[thread_id],
i_rect_off_x, i_rect_off_y, i_rect_width, i_rect_height, 0, 0))
continue;
}
else
{
if (!pnet_images[scale_id].ROI(task_pnet_images[thread_id],
i_rect_off_x, i_rect_off_y, i_rect_width, i_rect_height, 0, 0))
continue;
}
if (!pnet[thread_id].Forward(task_pnet_images[thread_id]))
continue;
const ZQ_CNN_Tensor4D_NCHWC4* score = pnet[thread_id].GetBlobByName("prob1");
int task_count = 0;
//score p
int scoreH = score->GetH();
int scoreW = score->GetW();
int scorePixStep = score->GetAlignSize();
const float *p = score->GetFirstPixelPtr() + 1;
ZQ_CNN_BBox bbox;
ZQ_CNN_OrderScore order;
for (int row = 0; row < scoreH; row++)
{
for (int col = 0; col < scoreW; col++)
{
int real_row = row + i_rect_off_y / stride;
int real_col = col + i_rect_off_x / stride;
if (real_row < mapH[scale_id] && real_col < mapW[scale_id])
maps[scale_id][real_row*mapW[scale_id] + real_col] = *p;
p += scorePixStep;
}
}
}
}
}
bool _Pnet_stage(const unsigned char* bgr_img, int _width, int _height, int _widthStep, std::vector<ZQ_CNN_BBox>& firstBbox)
{
if (thread_num <= 0)
return false;
double t1 = omp_get_wtime();
firstBbox.clear();
if (width != _width || height != _height)
return false;
if (!input.ConvertFromBGR(bgr_img, width, height, width * 3))
return false;
double t2 = omp_get_wtime();
if (show_debug_info)
printf("convert cost: %.3f ms\n", 1000 * (t2 - t1));
std::vector<std::vector<float> > maps;
std::vector<int> mapH;
std::vector<int> mapW;
if (thread_num == 1 && !force_run_pnet_multithread)
{
pnet[0].TurnOffShowDebugInfo();
//pnet[0].TurnOnShowDebugInfo();
_compute_Pnet_single_thread(maps, mapH, mapW);
}
else
{
_compute_Pnet_multi_thread(maps, mapH, mapW);
}
ZQ_CNN_OrderScore order;
std::vector<std::vector<ZQ_CNN_BBox> > bounding_boxes(scales.size());
std::vector<std::vector<ZQ_CNN_OrderScore> > bounding_scores(scales.size());
const int block_size = 32;
int stride = pnet_stride;
int cellsize = pnet_size;
int border_size = cellsize / stride;
for (int i = 0; i < maps.size(); i++)
{
double t13 = omp_get_wtime();
int changedH = (int)ceil(height*scales[i]);
int changedW = (int)ceil(width*scales[i]);
if (changedH < pnet_size || changedW < pnet_size)
continue;
float cur_scale_x = (float)width / changedW;
float cur_scale_y = (float)height / changedH;
int count = 0;
//score p
int scoreH = mapH[i];
int scoreW = mapW[i];
const float *p = &maps[i][0];
if (scoreW <= block_size && scoreH < block_size)
{
ZQ_CNN_BBox bbox;
ZQ_CNN_OrderScore order;
for (int row = 0; row < scoreH; row++)
{
for (int col = 0; col < scoreW; col++)
{
if (*p > thresh[0])
{
bbox.score = *p;
order.score = *p;
order.oriOrder = count;
bbox.row1 = stride*row;
bbox.col1 = stride*col;
bbox.row2 = stride*row + cellsize;
bbox.col2 = stride*col + cellsize;
bbox.exist = true;
bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1);
bbox.need_check_overlap_count = (row >= border_size && row < scoreH - border_size)
&& (col >= border_size && col < scoreW - border_size);
bounding_boxes[i].push_back(bbox);
bounding_scores[i].push_back(order);
count++;
}
p++;
}
}
int before_count = bounding_boxes[i].size();
ZQ_CNN_BBoxUtils::_nms(bounding_boxes[i], bounding_scores[i], nms_thresh_per_scale, "Union", pnet_overlap_thresh_count);
int after_count = bounding_boxes[i].size();
for (int j = 0; j < after_count; j++)
{
ZQ_CNN_BBox& bbox = bounding_boxes[i][j];
bbox.row1 = round(bbox.row1 *cur_scale_y);
bbox.col1 = round(bbox.col1 *cur_scale_x);
bbox.row2 = round(bbox.row2 *cur_scale_y);
bbox.col2 = round(bbox.col2 *cur_scale_x);
bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1);
}
double t14 = omp_get_wtime();
if (show_debug_info)
printf("nms cost: %.3f ms, (%d-->%d)\n", 1000 * (t14 - t13), before_count, after_count);
}
else
{
int before_count = 0, after_count = 0;
int block_H_num = __max(1, scoreH / block_size);
int block_W_num = __max(1, scoreW / block_size);
int block_num = block_H_num*block_W_num;
int width_per_block = scoreW / block_W_num;
int height_per_block = scoreH / block_H_num;
std::vector<std::vector<ZQ_CNN_BBox> > tmp_bounding_boxes(block_num);
std::vector<std::vector<ZQ_CNN_OrderScore> > tmp_bounding_scores(block_num);
std::vector<int> block_start_w(block_num), block_end_w(block_num);
std::vector<int> block_start_h(block_num), block_end_h(block_num);
for (int bh = 0; bh < block_H_num; bh++)
{
for (int bw = 0; bw < block_W_num; bw++)
{
int bb = bh * block_W_num + bw;
block_start_w[bb] = (bw == 0) ? 0 : (bw*width_per_block - border_size);
block_end_w[bb] = (bw == block_num - 1) ? scoreW : ((bw + 1)*width_per_block);
block_start_h[bb] = (bh == 0) ? 0 : (bh*height_per_block - border_size);
block_end_h[bb] = (bh == block_num - 1) ? scoreH : ((bh + 1)*height_per_block);
}
}
int chunk_size = 1;// ceil((float)block_num / thread_num);
if (thread_num <= 1)
{
for (int bb = 0; bb < block_num; bb++)
{
ZQ_CNN_BBox bbox;
ZQ_CNN_OrderScore order;
int count = 0;
for (int row = block_start_h[bb]; row < block_end_h[bb]; row++)
{
p = &maps[i][0] + row*scoreW + block_start_w[bb];
for (int col = block_start_w[bb]; col < block_end_w[bb]; col++)
{
if (*p > thresh[0])
{
bbox.score = *p;
order.score = *p;
order.oriOrder = count;
bbox.row1 = stride*row;
bbox.col1 = stride*col;
bbox.row2 = stride*row + cellsize;
bbox.col2 = stride*col + cellsize;
bbox.exist = true;
bbox.need_check_overlap_count = (row >= border_size && row < scoreH - border_size)
&& (col >= border_size && col < scoreW - border_size);
bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1);
tmp_bounding_boxes[bb].push_back(bbox);
tmp_bounding_scores[bb].push_back(order);
count++;
}
p++;
}
}
int tmp_before_count = tmp_bounding_boxes[bb].size();
ZQ_CNN_BBoxUtils::_nms(tmp_bounding_boxes[bb], tmp_bounding_scores[bb], nms_thresh_per_scale, "Union", pnet_overlap_thresh_count);
int tmp_after_count = tmp_bounding_boxes[bb].size();
before_count += tmp_before_count;
after_count += tmp_after_count;
}
}
else
{
#pragma omp parallel for schedule(dynamic, chunk_size) num_threads(thread_num)
for (int bb = 0; bb < block_num; bb++)
{
ZQ_CNN_BBox bbox;
ZQ_CNN_OrderScore order;
int count = 0;
for (int row = block_start_h[bb]; row < block_end_h[bb]; row++)
{
const float* p = &maps[i][0] + row*scoreW + block_start_w[bb];
for (int col = block_start_w[bb]; col < block_end_w[bb]; col++)
{
if (*p > thresh[0])
{
bbox.score = *p;
order.score = *p;
order.oriOrder = count;
bbox.row1 = stride*row;
bbox.col1 = stride*col;
bbox.row2 = stride*row + cellsize;
bbox.col2 = stride*col + cellsize;
bbox.exist = true;
bbox.need_check_overlap_count = (row >= border_size && row < scoreH - border_size)
&& (col >= border_size && col < scoreW - border_size);
bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1);
tmp_bounding_boxes[bb].push_back(bbox);
tmp_bounding_scores[bb].push_back(order);
count++;
}
p++;
}
}
int tmp_before_count = tmp_bounding_boxes[bb].size();
ZQ_CNN_BBoxUtils::_nms(tmp_bounding_boxes[bb], tmp_bounding_scores[bb], nms_thresh_per_scale, "Union", pnet_overlap_thresh_count);
int tmp_after_count = tmp_bounding_boxes[bb].size();
before_count += tmp_before_count;
after_count += tmp_after_count;
}
}
count = 0;
for (int bb = 0; bb < block_num; bb++)
{
std::vector<ZQ_CNN_BBox>::iterator it = tmp_bounding_boxes[bb].begin();
for (; it != tmp_bounding_boxes[bb].end(); it++)
{
if ((*it).exist)
{
bounding_boxes[i].push_back(*it);
order.score = (*it).score;
order.oriOrder = count;
bounding_scores[i].push_back(order);
count++;
}
}
}
//ZQ_CNN_BBoxUtils::_nms(bounding_boxes[i], bounding_scores[i], nms_thresh_per_scale, "Union", 0);
after_count = bounding_boxes[i].size();
for (int j = 0; j < after_count; j++)
{
ZQ_CNN_BBox& bbox = bounding_boxes[i][j];
bbox.row1 = round(bbox.row1 *cur_scale_y);
bbox.col1 = round(bbox.col1 *cur_scale_x);
bbox.row2 = round(bbox.row2 *cur_scale_y);
bbox.col2 = round(bbox.col2 *cur_scale_x);
bbox.area = (bbox.row2 - bbox.row1)*(bbox.col2 - bbox.col1);
}
double t14 = omp_get_wtime();
if (show_debug_info)
printf("nms cost: %.3f ms, (%d-->%d)\n", 1000 * (t14 - t13), before_count, after_count);
}
}
std::vector<ZQ_CNN_OrderScore> firstOrderScore;
int count = 0;
for (int i = 0; i < scales.size(); i++)
{
std::vector<ZQ_CNN_BBox>::iterator it = bounding_boxes[i].begin();
for (; it != bounding_boxes[i].end(); it++)
{
if ((*it).exist)
{
firstBbox.push_back(*it);
order.score = (*it).score;
order.oriOrder = count;
firstOrderScore.push_back(order);
count++;
}
}
}
//the first stage's nms
if (count < 1) return false;
double t15 = omp_get_wtime();
ZQ_CNN_BBoxUtils::_nms(firstBbox, firstOrderScore, nms_thresh[0], "Union", 0, 1);
ZQ_CNN_BBoxUtils::_refine_and_square_bbox(firstBbox, width, height, true);
double t16 = omp_get_wtime();
if (show_debug_info)
printf("nms cost: %.3f ms\n", 1000 * (t16 - t15));
if (show_debug_info)
printf("first stage candidate count: %d\n", count);
double t3 = omp_get_wtime();
if (show_debug_info)
printf("stage 1: cost %.3f ms\n", 1000 * (t3 - t2));
return true;
}
bool _Rnet_stage(std::vector<ZQ_CNN_BBox>& firstBbox, std::vector<ZQ_CNN_BBox>& secondBbox)
{
double t3 = omp_get_wtime();
secondBbox.clear();
std::vector<ZQ_CNN_BBox>::iterator it = firstBbox.begin();
std::vector<ZQ_CNN_OrderScore> secondScore;
std::vector<int> src_off_x, src_off_y, src_rect_w, src_rect_h;
int r_count = 0;
for (; it != firstBbox.end(); it++)
{
if ((*it).exist)
{
int off_x = it->col1;
int off_y = it->row1;
int rect_w = it->col2 - off_x;
int rect_h = it->row2 - off_y;
if (/*off_x < 0 || off_x + rect_w > width || off_y < 0 || off_y + rect_h > height ||*/ rect_w <= 0.5*min_size || rect_h <= 0.5*min_size)
{
(*it).exist = false;
continue;
}
else
{
src_off_x.push_back(off_x);
src_off_y.push_back(off_y);
src_rect_w.push_back(rect_w);
src_rect_h.push_back(rect_h);
r_count++;
secondBbox.push_back(*it);
}
}
}
int batch_size = BATCH_SIZE;
int per_num = ceil((float)r_count / thread_num);
int need_thread_num = thread_num;
if (per_num > batch_size)
{
need_thread_num = ceil((float)r_count / batch_size);
per_num = batch_size;
}
std::vector<ZQ_CNN_Tensor4D_NCHWC4> task_rnet_images(need_thread_num);
std::vector<std::vector<int> > task_src_off_x(need_thread_num);
std::vector<std::vector<int> > task_src_off_y(need_thread_num);
std::vector<std::vector<int> > task_src_rect_w(need_thread_num);
std::vector<std::vector<int> > task_src_rect_h(need_thread_num);
std::vector<std::vector<ZQ_CNN_BBox> > task_secondBbox(need_thread_num);
for (int i = 0; i < need_thread_num; i++)
{
int st_id = per_num*i;
int end_id = __min(r_count, per_num*(i + 1));
int cur_num = end_id - st_id;
if (cur_num > 0)
{
task_src_off_x[i].resize(cur_num);
task_src_off_y[i].resize(cur_num);
task_src_rect_w[i].resize(cur_num);
task_src_rect_h[i].resize(cur_num);
task_secondBbox[i].resize(cur_num);
for (int j = 0; j < cur_num; j++)
{
task_src_off_x[i][j] = src_off_x[st_id + j];
task_src_off_y[i][j] = src_off_y[st_id + j];
task_src_rect_w[i][j] = src_rect_w[st_id + j];
task_src_rect_h[i][j] = src_rect_h[st_id + j];
task_secondBbox[i][j] = secondBbox[st_id + j];
}
}
}
if (thread_num <= 1)
{
for (int pp = 0; pp < need_thread_num; pp++)
{
if (task_src_off_x.size() == 0)
continue;
if (!input.ResizeBilinearRect(task_rnet_images[pp], rnet_size, rnet_size, 0, 0,
task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp]))
{
continue;
}
rnet[0].Forward(task_rnet_images[pp]);
const ZQ_CNN_Tensor4D_NCHWC4* score = rnet[0].GetBlobByName("prob1");
const ZQ_CNN_Tensor4D_NCHWC4* location = rnet[0].GetBlobByName("conv5-2");
const float* score_ptr = score->GetFirstPixelPtr();
const float* location_ptr = location->GetFirstPixelPtr();
int score_sliceStep = score->GetSliceStep();
int location_sliceStep = location->GetSliceStep();
int task_count = 0;
for (int i = 0; i < task_secondBbox[pp].size(); i++)
{
if (score_ptr[i*score_sliceStep + 1] > thresh[1])
{
for (int j = 0; j < 4; j++)
task_secondBbox[pp][i].regreCoord[j] = location_ptr[i*location_sliceStep + j];
task_secondBbox[pp][i].area = task_src_rect_w[pp][i] * task_src_rect_h[pp][i];
task_secondBbox[pp][i].score = score_ptr[i*score_sliceStep + 1];
task_count++;
}
else
{
task_secondBbox[pp][i].exist = false;
}
}
if (task_count < 1)
{
task_secondBbox[pp].clear();
continue;
}
for (int i = task_secondBbox[pp].size() - 1; i >= 0; i--)
{
if (!task_secondBbox[pp][i].exist)
task_secondBbox[pp].erase(task_secondBbox[pp].begin() + i);
}
}
}
else
{
#pragma omp parallel for num_threads(thread_num) schedule(dynamic,1)
for (int pp = 0; pp < need_thread_num; pp++)
{
int thread_id = omp_get_thread_num();
if (task_src_off_x.size() == 0)
continue;
if (!input.ResizeBilinearRect(task_rnet_images[pp], rnet_size, rnet_size, 0, 0,
task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp]))
{
continue;
}
rnet[thread_id].Forward(task_rnet_images[pp]);
const ZQ_CNN_Tensor4D_NCHWC4* score = rnet[thread_id].GetBlobByName("prob1");
const ZQ_CNN_Tensor4D_NCHWC4* location = rnet[thread_id].GetBlobByName("conv5-2");
const float* score_ptr = score->GetFirstPixelPtr();
const float* location_ptr = location->GetFirstPixelPtr();
int score_sliceStep = score->GetSliceStep();
int location_sliceStep = location->GetSliceStep();
int task_count = 0;
for (int i = 0; i < task_secondBbox[pp].size(); i++)
{
if (score_ptr[i*score_sliceStep + 1] > thresh[1])
{
for (int j = 0; j < 4; j++)
task_secondBbox[pp][i].regreCoord[j] = location_ptr[i*location_sliceStep + j];
task_secondBbox[pp][i].area = task_src_rect_w[pp][i] * task_src_rect_h[pp][i];
task_secondBbox[pp][i].score = score_ptr[i*score_sliceStep + 1];
task_count++;
}
else
{
task_secondBbox[pp][i].exist = false;
}
}
if (task_count < 1)
{
task_secondBbox[pp].clear();
continue;
}
for (int i = task_secondBbox[pp].size() - 1; i >= 0; i--)
{
if (!task_secondBbox[pp][i].exist)
task_secondBbox[pp].erase(task_secondBbox[pp].begin() + i);
}
}
}
int count = 0;
for (int i = 0; i < need_thread_num; i++)
{
count += task_secondBbox[i].size();
}
secondBbox.resize(count);
secondScore.resize(count);
int id = 0;
for (int i = 0; i < need_thread_num; i++)
{
for (int j = 0; j < task_secondBbox[i].size(); j++)
{
secondBbox[id] = task_secondBbox[i][j];
secondScore[id].score = secondBbox[id].score;
secondScore[id].oriOrder = id;
id++;
}
}
//ZQ_CNN_BBoxUtils::_nms(secondBbox, secondScore, nms_thresh[1], "Union");
ZQ_CNN_BBoxUtils::_nms(secondBbox, secondScore, nms_thresh[1], "Min");
ZQ_CNN_BBoxUtils::_refine_and_square_bbox(secondBbox, width, height, true);
count = secondBbox.size();
double t4 = omp_get_wtime();
if (show_debug_info)
printf("run Rnet [%d] times, candidate after nms: %d \n", r_count, count);
if (show_debug_info)
printf("stage 2: cost %.3f ms\n", 1000 * (t4 - t3));
return true;
}
bool _Onet_stage(std::vector<ZQ_CNN_BBox>& secondBbox, std::vector<ZQ_CNN_BBox>& thirdBbox)
{
double t4 = omp_get_wtime();
thirdBbox.clear();
std::vector<ZQ_CNN_BBox>::iterator it = secondBbox.begin();
std::vector<ZQ_CNN_OrderScore> thirdScore;
std::vector<ZQ_CNN_BBox> early_accept_thirdBbox;
std::vector<int> src_off_x, src_off_y, src_rect_w, src_rect_h;
int o_count = 0;
for (; it != secondBbox.end(); it++)
{
if ((*it).exist)
{
int off_x = it->col1;
int off_y = it->row1;
int rect_w = it->col2 - off_x;
int rect_h = it->row2 - off_y;
if (/*off_x < 0 || off_x + rect_w > width || off_y < 0 || off_y + rect_h > height ||*/ rect_w <= 0.5*min_size || rect_h <= 0.5*min_size)
{
(*it).exist = false;
continue;
}
else
{
if (!do_landmark && it->score > early_accept_thresh)
{
early_accept_thirdBbox.push_back(*it);
}
else
{
src_off_x.push_back(off_x);
src_off_y.push_back(off_y);
src_rect_w.push_back(rect_w);
src_rect_h.push_back(rect_h);
o_count++;
thirdBbox.push_back(*it);
}
}
}
}
int batch_size = BATCH_SIZE;
int per_num = ceil((float)o_count / thread_num);
int need_thread_num = thread_num;
if (per_num > batch_size)
{
need_thread_num = ceil((float)o_count / batch_size);
per_num = batch_size;
}
std::vector<ZQ_CNN_Tensor4D_NCHWC4> task_onet_images(need_thread_num);
std::vector<std::vector<int> > task_src_off_x(need_thread_num);
std::vector<std::vector<int> > task_src_off_y(need_thread_num);
std::vector<std::vector<int> > task_src_rect_w(need_thread_num);
std::vector<std::vector<int> > task_src_rect_h(need_thread_num);
std::vector<std::vector<ZQ_CNN_BBox> > task_thirdBbox(need_thread_num);
for (int i = 0; i < need_thread_num; i++)
{
int st_id = per_num*i;
int end_id = __min(o_count, per_num*(i + 1));
int cur_num = end_id - st_id;
if (cur_num > 0)
{
task_src_off_x[i].resize(cur_num);
task_src_off_y[i].resize(cur_num);
task_src_rect_w[i].resize(cur_num);
task_src_rect_h[i].resize(cur_num);
task_thirdBbox[i].resize(cur_num);
for (int j = 0; j < cur_num; j++)
{
task_src_off_x[i][j] = src_off_x[st_id + j];
task_src_off_y[i][j] = src_off_y[st_id + j];
task_src_rect_w[i][j] = src_rect_w[st_id + j];
task_src_rect_h[i][j] = src_rect_h[st_id + j];
task_thirdBbox[i][j] = thirdBbox[st_id + j];
}
}
}
if (thread_num <= 1)
{
for (int pp = 0; pp < need_thread_num; pp++)
{
if (task_src_off_x.size() == 0)
continue;
if (!input.ResizeBilinearRect(task_onet_images[pp], onet_size, onet_size, 0, 0,
task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp]))
{
continue;
}
double t31 = omp_get_wtime();
onet[0].Forward(task_onet_images[pp]);
double t32 = omp_get_wtime();
const ZQ_CNN_Tensor4D_NCHWC4* score = onet[0].GetBlobByName("prob1");
const ZQ_CNN_Tensor4D_NCHWC4* location = onet[0].GetBlobByName("conv6-2");
const ZQ_CNN_Tensor4D_NCHWC4* keyPoint = onet[0].GetBlobByName("conv6-3");
const float* score_ptr = score->GetFirstPixelPtr();
const float* location_ptr = location->GetFirstPixelPtr();
const float* keyPoint_ptr = 0;
if (keyPoint != 0)
{
keyPoint_ptr = keyPoint->GetFirstPixelPtr();
}
int score_sliceStep = score->GetSliceStep();
int location_sliceStep = location->GetSliceStep();
int keyPoint_sliceStep = 0;
if (keyPoint != 0)
keyPoint_sliceStep = keyPoint->GetSliceStep();
int task_count = 0;
ZQ_CNN_OrderScore order;
for (int i = 0; i < task_thirdBbox[pp].size(); i++)
{
if (score_ptr[i*score_sliceStep + 1] > thresh[2])
{
for (int j = 0; j < 4; j++)
task_thirdBbox[pp][i].regreCoord[j] = location_ptr[i*location_sliceStep + j];
if (keyPoint != 0)
{
for (int num = 0; num < 5; num++)
{
task_thirdBbox[pp][i].ppoint[num] = task_thirdBbox[pp][i].col1 +
(task_thirdBbox[pp][i].col2 - task_thirdBbox[pp][i].col1)*keyPoint_ptr[i*keyPoint_sliceStep + num];
task_thirdBbox[pp][i].ppoint[num + 5] = task_thirdBbox[pp][i].row1 +
(task_thirdBbox[pp][i].row2 - task_thirdBbox[pp][i].row1)*keyPoint_ptr[i*keyPoint_sliceStep + num + 5];
}
}
task_thirdBbox[pp][i].area = task_src_rect_w[pp][i] * task_src_rect_h[pp][i];
task_thirdBbox[pp][i].score = score_ptr[i*score_sliceStep + 1];
task_count++;
}
else
{
task_thirdBbox[pp][i].exist = false;
}
}
if (task_count < 1)
{
task_thirdBbox[pp].clear();
continue;
}
for (int i = task_thirdBbox[pp].size() - 1; i >= 0; i--)
{
if (!task_thirdBbox[pp][i].exist)
task_thirdBbox[pp].erase(task_thirdBbox[pp].begin() + i);
}
}
}
else
{
#pragma omp parallel for num_threads(thread_num) schedule(dynamic,1)
for (int pp = 0; pp < need_thread_num; pp++)
{
int thread_id = omp_get_thread_num();
if (task_src_off_x.size() == 0)
continue;
if (!input.ResizeBilinearRect(task_onet_images[pp], onet_size, onet_size, 0, 0,
task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp]))
{
continue;
}
double t31 = omp_get_wtime();
onet[thread_id].Forward(task_onet_images[pp]);
double t32 = omp_get_wtime();
const ZQ_CNN_Tensor4D_NCHWC4* score = onet[thread_id].GetBlobByName("prob1");
const ZQ_CNN_Tensor4D_NCHWC4* location = onet[thread_id].GetBlobByName("conv6-2");
const ZQ_CNN_Tensor4D_NCHWC4* keyPoint = onet[thread_id].GetBlobByName("conv6-3");
const float* score_ptr = score->GetFirstPixelPtr();
const float* location_ptr = location->GetFirstPixelPtr();
const float* keyPoint_ptr = 0;
if (keyPoint != 0)
keyPoint_ptr = keyPoint->GetFirstPixelPtr();
int score_sliceStep = score->GetSliceStep();
int location_sliceStep = location->GetSliceStep();
int keyPoint_sliceStep = 0;
if (keyPoint != 0)
keyPoint_sliceStep = keyPoint->GetSliceStep();
int task_count = 0;
ZQ_CNN_OrderScore order;
for (int i = 0; i < task_thirdBbox[pp].size(); i++)
{
if (score_ptr[i*score_sliceStep + 1] > thresh[2])
{
for (int j = 0; j < 4; j++)
task_thirdBbox[pp][i].regreCoord[j] = location_ptr[i*location_sliceStep + j];
if (keyPoint != 0)
{
for (int num = 0; num < 5; num++)
{
task_thirdBbox[pp][i].ppoint[num] = task_thirdBbox[pp][i].col1 +
(task_thirdBbox[pp][i].col2 - task_thirdBbox[pp][i].col1)*keyPoint_ptr[i*keyPoint_sliceStep + num];
task_thirdBbox[pp][i].ppoint[num + 5] = task_thirdBbox[pp][i].row1 +
(task_thirdBbox[pp][i].row2 - task_thirdBbox[pp][i].row1)*keyPoint_ptr[i*keyPoint_sliceStep + num + 5];
}
}
task_thirdBbox[pp][i].area = task_src_rect_w[pp][i] * task_src_rect_h[pp][i];
task_thirdBbox[pp][i].score = score_ptr[i*score_sliceStep + 1];
task_count++;
}
else
{
task_thirdBbox[pp][i].exist = false;
}
}
if (task_count < 1)
{
task_thirdBbox[pp].clear();
continue;
}
for (int i = task_thirdBbox[pp].size() - 1; i >= 0; i--)
{
if (!task_thirdBbox[pp][i].exist)
task_thirdBbox[pp].erase(task_thirdBbox[pp].begin() + i);
}
}
}
int count = 0;
for (int i = 0; i < need_thread_num; i++)
{
count += task_thirdBbox[i].size();
}
thirdBbox.resize(count);
thirdScore.resize(count);
int id = 0;
for (int i = 0; i < need_thread_num; i++)
{
for (int j = 0; j < task_thirdBbox[i].size(); j++)
{
thirdBbox[id] = task_thirdBbox[i][j];
thirdScore[id].score = task_thirdBbox[i][j].score;
thirdScore[id].oriOrder = id;
id++;
}
}
ZQ_CNN_OrderScore order;
for (int i = 0; i < early_accept_thirdBbox.size(); i++)
{
order.score = early_accept_thirdBbox[i].score;
order.oriOrder = count++;
thirdScore.push_back(order);
thirdBbox.push_back(early_accept_thirdBbox[i]);
}
ZQ_CNN_BBoxUtils::_refine_and_square_bbox(thirdBbox, width, height, false);
ZQ_CNN_BBoxUtils::_nms(thirdBbox, thirdScore, nms_thresh[2], "Min");
double t5 = omp_get_wtime();
if (show_debug_info)
printf("run Onet [%d] times, candidate before nms: %d \n", o_count, count);
if (show_debug_info)
printf("stage 3: cost %.3f ms\n", 1000 * (t5 - t4));
return true;
}
bool _Lnet_stage(std::vector<ZQ_CNN_BBox>& thirdBbox, std::vector<ZQ_CNN_BBox>& fourthBbox)
{
double t4 = omp_get_wtime();
fourthBbox.clear();
std::vector<ZQ_CNN_BBox>::iterator it = thirdBbox.begin();
std::vector<int> src_off_x, src_off_y, src_rect_w, src_rect_h;
int l_count = 0;
for (; it != thirdBbox.end(); it++)
{
if ((*it).exist)
{
int off_x = it->col1;
int off_y = it->row1;
int rect_w = it->col2 - off_x;
int rect_h = it->row2 - off_y;
if (/*off_x < 0 || off_x + rect_w > width || off_y < 0 || off_y + rect_h > height ||*/ rect_w <= 0.5*min_size || rect_h <= 0.5*min_size)
{
(*it).exist = false;
continue;
}
else
{
l_count++;
fourthBbox.push_back(*it);
}
}
}
std::vector<ZQ_CNN_BBox> copy_fourthBbox = fourthBbox;
ZQ_CNN_BBoxUtils::_square_bbox(copy_fourthBbox, width, height);
for (it = copy_fourthBbox.begin(); it != copy_fourthBbox.end(); ++it)
{
int off_x = it->col1;
int off_y = it->row1;
int rect_w = it->col2 - off_x;
int rect_h = it->row2 - off_y;
src_off_x.push_back(off_x);
src_off_y.push_back(off_y);
src_rect_w.push_back(rect_w);
src_rect_h.push_back(rect_h);
}
int batch_size = BATCH_SIZE;
int per_num = ceil((float)l_count / thread_num);
int need_thread_num = thread_num;
if (per_num > batch_size)
{
need_thread_num = ceil((float)l_count / batch_size);
per_num = batch_size;
}
std::vector<ZQ_CNN_Tensor4D_NCHWC4> task_lnet_images(need_thread_num);
std::vector<std::vector<int> > task_src_off_x(need_thread_num);
std::vector<std::vector<int> > task_src_off_y(need_thread_num);
std::vector<std::vector<int> > task_src_rect_w(need_thread_num);
std::vector<std::vector<int> > task_src_rect_h(need_thread_num);
std::vector<std::vector<ZQ_CNN_BBox> > task_fourthBbox(need_thread_num);
for (int i = 0; i < need_thread_num; i++)
{
int st_id = per_num*i;
int end_id = __min(l_count, per_num*(i + 1));
int cur_num = end_id - st_id;
if (cur_num > 0)
{
task_src_off_x[i].resize(cur_num);
task_src_off_y[i].resize(cur_num);
task_src_rect_w[i].resize(cur_num);
task_src_rect_h[i].resize(cur_num);
task_fourthBbox[i].resize(cur_num);
for (int j = 0; j < cur_num; j++)
{
task_src_off_x[i][j] = src_off_x[st_id + j];
task_src_off_y[i][j] = src_off_y[st_id + j];
task_src_rect_w[i][j] = src_rect_w[st_id + j];
task_src_rect_h[i][j] = src_rect_h[st_id + j];
task_fourthBbox[i][j] = copy_fourthBbox[st_id + j];
}
}
}
if (thread_num <= 1)
{
for (int pp = 0; pp < need_thread_num; pp++)
{
if (task_src_off_x.size() == 0)
continue;
if (!input.ResizeBilinearRect(task_lnet_images[pp], lnet_size, lnet_size, 0, 0,
task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp]))
{
continue;
}
double t31 = omp_get_wtime();
lnet[0].Forward(task_lnet_images[pp]);
double t32 = omp_get_wtime();
const ZQ_CNN_Tensor4D_NCHWC4* keyPoint = lnet[0].GetBlobByName("conv6-3");
const float* keyPoint_ptr = keyPoint->GetFirstPixelPtr();
int keyPoint_sliceStep = keyPoint->GetSliceStep();
for (int i = 0; i < task_fourthBbox[pp].size(); i++)
{
for (int num = 0; num < 5; num++)
{
task_fourthBbox[pp][i].ppoint[num] = task_fourthBbox[pp][i].col1 +
(task_fourthBbox[pp][i].col2 - task_fourthBbox[pp][i].col1)*keyPoint_ptr[i*keyPoint_sliceStep + num];
task_fourthBbox[pp][i].ppoint[num + 5] = task_fourthBbox[pp][i].row1 +
(task_fourthBbox[pp][i].row2 - task_fourthBbox[pp][i].row1)*keyPoint_ptr[i*keyPoint_sliceStep + num + 5];
}
}
}
}
else
{
#pragma omp parallel for num_threads(thread_num) schedule(dynamic,1)
for (int pp = 0; pp < need_thread_num; pp++)
{
int thread_id = omp_get_thread_num();
if (task_src_off_x.size() == 0)
continue;
if (!input.ResizeBilinearRect(task_lnet_images[pp], lnet_size, lnet_size, 0, 0,
task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp]))
{
continue;
}
double t31 = omp_get_wtime();
lnet[thread_id].Forward(task_lnet_images[pp]);
double t32 = omp_get_wtime();
const ZQ_CNN_Tensor4D_NCHWC4* keyPoint = lnet[thread_id].GetBlobByName("conv6-3");
const float* keyPoint_ptr = keyPoint->GetFirstPixelPtr();
int keyPoint_sliceStep = keyPoint->GetSliceStep();
for (int i = 0; i < task_fourthBbox[pp].size(); i++)
{
for (int num = 0; num < 5; num++)
{
task_fourthBbox[pp][i].ppoint[num] = task_fourthBbox[pp][i].col1 +
(task_fourthBbox[pp][i].col2 - task_fourthBbox[pp][i].col1)*keyPoint_ptr[i*keyPoint_sliceStep + num];
task_fourthBbox[pp][i].ppoint[num + 5] = task_fourthBbox[pp][i].row1 +
(task_fourthBbox[pp][i].row2 - task_fourthBbox[pp][i].row1)*keyPoint_ptr[i*keyPoint_sliceStep + num + 5];
}
}
}
}
int count = 0;
for (int i = 0; i < need_thread_num; i++)
{
count += task_fourthBbox[i].size();
}
fourthBbox.resize(count);
int id = 0;
for (int i = 0; i < need_thread_num; i++)
{
for (int j = 0; j < task_fourthBbox[i].size(); j++)
{
memcpy(fourthBbox[id].ppoint, task_fourthBbox[i][j].ppoint, sizeof(float) * 10);
id++;
}
}
double t5 = omp_get_wtime();
if (show_debug_info)
printf("run Lnet [%d] times \n", l_count);
if (show_debug_info)
printf("stage 4: cost %.3f ms\n", 1000 * (t5 - t4));
return true;
}
bool _Lnet106_stage(std::vector<ZQ_CNN_BBox>& thirdBbox, std::vector<ZQ_CNN_BBox106>& resultBbox)
{
double t4 = omp_get_wtime();
std::vector<ZQ_CNN_BBox> fourthBbox;
std::vector<ZQ_CNN_BBox>::iterator it = thirdBbox.begin();
std::vector<int> src_off_x, src_off_y, src_rect_w, src_rect_h;
int l_count = 0;
for (; it != thirdBbox.end(); it++)
{
if ((*it).exist)
{
int off_x = it->col1;
int off_y = it->row1;
int rect_w = it->col2 - off_x;
int rect_h = it->row2 - off_y;
if (/*off_x < 0 || off_x + rect_w > width || off_y < 0 || off_y + rect_h > height ||*/ rect_w <= 0.5*min_size || rect_h <= 0.5*min_size)
{
(*it).exist = false;
continue;
}
else
{
l_count++;
fourthBbox.push_back(*it);
}
}
}
std::vector<ZQ_CNN_BBox> copy_fourthBbox = fourthBbox;
ZQ_CNN_BBoxUtils::_square_bbox(copy_fourthBbox, width, height);
for (it = copy_fourthBbox.begin(); it != copy_fourthBbox.end(); ++it)
{
int off_x = it->col1;
int off_y = it->row1;
int rect_w = it->col2 - off_x;
int rect_h = it->row2 - off_y;
src_off_x.push_back(off_x);
src_off_y.push_back(off_y);
src_rect_w.push_back(rect_w);
src_rect_h.push_back(rect_h);
}
int batch_size = BATCH_SIZE;
int per_num = ceil((float)l_count / thread_num);
int need_thread_num = thread_num;
if (per_num > batch_size)
{
need_thread_num = ceil((float)l_count / batch_size);
per_num = batch_size;
}
std::vector<ZQ_CNN_Tensor4D_NCHWC4> task_lnet_images(need_thread_num);
std::vector<std::vector<int> > task_src_off_x(need_thread_num);
std::vector<std::vector<int> > task_src_off_y(need_thread_num);
std::vector<std::vector<int> > task_src_rect_w(need_thread_num);
std::vector<std::vector<int> > task_src_rect_h(need_thread_num);
std::vector<std::vector<ZQ_CNN_BBox106> > task_fourthBbox(need_thread_num);
for (int i = 0; i < need_thread_num; i++)
{
int st_id = per_num*i;
int end_id = __min(l_count, per_num*(i + 1));
int cur_num = end_id - st_id;
if (cur_num > 0)
{
task_src_off_x[i].resize(cur_num);
task_src_off_y[i].resize(cur_num);
task_src_rect_w[i].resize(cur_num);
task_src_rect_h[i].resize(cur_num);
task_fourthBbox[i].resize(cur_num);
for (int j = 0; j < cur_num; j++)
{
task_src_off_x[i][j] = src_off_x[st_id + j];
task_src_off_y[i][j] = src_off_y[st_id + j];
task_src_rect_w[i][j] = src_rect_w[st_id + j];
task_src_rect_h[i][j] = src_rect_h[st_id + j];
task_fourthBbox[i][j].col1 = copy_fourthBbox[st_id + j].col1;
task_fourthBbox[i][j].col2 = copy_fourthBbox[st_id + j].col2;
task_fourthBbox[i][j].row1 = copy_fourthBbox[st_id + j].row1;
task_fourthBbox[i][j].row2 = copy_fourthBbox[st_id + j].row2;
task_fourthBbox[i][j].area = copy_fourthBbox[st_id + j].area;
task_fourthBbox[i][j].score = copy_fourthBbox[st_id + j].score;
task_fourthBbox[i][j].exist = copy_fourthBbox[st_id + j].exist;
}
}
}
resultBbox.resize(l_count);
for (int i = 0; i < l_count; i++)
{
resultBbox[i].col1 = fourthBbox[i].col1;
resultBbox[i].col2 = fourthBbox[i].col2;
resultBbox[i].row1 = fourthBbox[i].row1;
resultBbox[i].row2 = fourthBbox[i].row2;
resultBbox[i].score = fourthBbox[i].score;
resultBbox[i].exist = fourthBbox[i].exist;
resultBbox[i].area = fourthBbox[i].area;
}
if (thread_num <= 1)
{
for (int pp = 0; pp < need_thread_num; pp++)
{
if (task_src_off_x[pp].size() == 0)
continue;
if (!input.ResizeBilinearRect(task_lnet_images[pp], lnet_size, lnet_size, 0, 0,
task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp]))
{
continue;
}
double t31 = omp_get_wtime();
lnet[0].Forward(task_lnet_images[pp]);
double t32 = omp_get_wtime();
const ZQ_CNN_Tensor4D_NCHWC4* keyPoint = lnet[0].GetBlobByName("conv6-3");
const float* keyPoint_ptr = keyPoint->GetFirstPixelPtr();
int keypoint_num = keyPoint->GetC() / 2;
int keyPoint_sliceStep = keyPoint->GetSliceStep();
for (int i = 0; i < task_fourthBbox[pp].size(); i++)
{
for (int num = 0; num < keypoint_num; num++)
{
task_fourthBbox[pp][i].ppoint[num * 2] = task_fourthBbox[pp][i].col1 +
(task_fourthBbox[pp][i].col2 - task_fourthBbox[pp][i].col1)*keyPoint_ptr[i*keyPoint_sliceStep + num * 2];
task_fourthBbox[pp][i].ppoint[num * 2 + 1] = task_fourthBbox[pp][i].row1 +
(task_fourthBbox[pp][i].row2 - task_fourthBbox[pp][i].row1)*keyPoint_ptr[i*keyPoint_sliceStep + num * 2 + 1];
}
}
}
}
else
{
#pragma omp parallel for num_threads(thread_num)
for (int pp = 0; pp < need_thread_num; pp++)
{
int thread_id = omp_get_thread_num();
if (task_src_off_x.size() == 0)
continue;
if (!input.ResizeBilinearRect(task_lnet_images[pp], lnet_size, lnet_size, 0, 0,
task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp]))
{
continue;
}
double t31 = omp_get_wtime();
lnet[thread_id].Forward(task_lnet_images[pp]);
double t32 = omp_get_wtime();
const ZQ_CNN_Tensor4D_NCHWC4* keyPoint = lnet[thread_id].GetBlobByName("conv6-3");
const float* keyPoint_ptr = keyPoint->GetFirstPixelPtr();
int keypoint_num = keyPoint->GetC() / 2;
int keyPoint_sliceStep = keyPoint->GetSliceStep();
for (int i = 0; i < task_fourthBbox[pp].size(); i++)
{
for (int num = 0; num < keypoint_num; num++)
{
task_fourthBbox[pp][i].ppoint[num * 2] = task_fourthBbox[pp][i].col1 +
(task_fourthBbox[pp][i].col2 - task_fourthBbox[pp][i].col1)*keyPoint_ptr[i*keyPoint_sliceStep + num * 2];
task_fourthBbox[pp][i].ppoint[num * 2 + 1] = task_fourthBbox[pp][i].row1 +
(task_fourthBbox[pp][i].row2 - task_fourthBbox[pp][i].row1)*keyPoint_ptr[i*keyPoint_sliceStep + num * 2 + 1];
}
}
}
}
int count = 0;
for (int i = 0; i < need_thread_num; i++)
{
count += task_fourthBbox[i].size();
}
resultBbox.resize(count);
int id = 0;
for (int i = 0; i < need_thread_num; i++)
{
for (int j = 0; j < task_fourthBbox[i].size(); j++)
{
memcpy(resultBbox[id].ppoint, task_fourthBbox[i][j].ppoint, sizeof(float) * 212);
id++;
}
}
double t5 = omp_get_wtime();
if (show_debug_info)
printf("run Lnet [%d] times \n", l_count);
if (show_debug_info)
printf("stage 4: cost %.3f ms\n", 1000 * (t5 - t4));
return true;
}
void _select(std::vector<ZQ_CNN_BBox>& bbox, int limit_num, int width, int height)
{
int in_num = bbox.size();
if (limit_num >= in_num)
return;
bbox.resize(limit_num);
}
};
}
#endif
|
residual_based_bossak_velocity_scheme.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Jordi Cotela
// Suneth Warnakulasuriya
//
#if !defined(KRATOS_RESIDUAL_BASED_BOSSAK_VELOCITY_SCHEME_H_INCLUDED)
#define KRATOS_RESIDUAL_BASED_BOSSAK_VELOCITY_SCHEME_H_INCLUDED
// System includes
#include <limits>
#include <vector>
// External includes
// Project includes
#include "custom_strategies/relaxed_dof_updater.h"
#include "includes/define.h"
#include "includes/model_part.h"
#include "solving_strategies/schemes/scheme.h"
#include "utilities/time_discretization.h"
namespace Kratos
{
///@name Kratos Classes
///@{
/// A scheme for steady and dynamic equations, using Bossak time integration.
/**
* It can be used for either first- or second-order time derivatives. Elements
* and conditions must provide a specialization of SchemeExtension via
* their data value container, which allows the scheme to operate independently
* of the variable arrangements in the element or condition.
*/
template <class TSparseSpace, class TDenseSpace>
class ResidualBasedBossakVelocityScheme : public Scheme<TSparseSpace, TDenseSpace>
{
public:
///@name Type Definitions
///@{
KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedBossakVelocityScheme);
using BaseType = Scheme<TSparseSpace, TDenseSpace>;
using SystemMatrixType = typename BaseType::TSystemMatrixType;
using SystemVectorType = typename BaseType::TSystemVectorType;
using LocalSystemVectorType = typename BaseType::LocalSystemVectorType;
using LocalSystemMatrixType = typename BaseType::LocalSystemMatrixType;
using DofsArrayType = typename BaseType::DofsArrayType;
using NodeType = ModelPart::NodeType;
using IndexType = std::size_t;
///@}
///@name Life Cycle
///@{
/// Constructor.
ResidualBasedBossakVelocityScheme(
const double AlphaBossak,
const double RelaxationFactor,
const std::vector<Variable<double> const*> rDisplacementVariables,
const std::vector<Variable<double> const*> rVelocityVariables,
const std::vector<Variable<double> const*> rAccelerationVariables,
const std::vector<Variable<double> const*> rDisplacementComponentVariables,
const std::vector<Variable<double> const*> rVelocityComponentVariables,
const std::vector<Variable<double> const*> rAccelerationComponentVariables)
: mAlphaBossak(AlphaBossak),
mUpdateAcceleration(rAccelerationVariables.size() > 0 ||
rAccelerationComponentVariables.size() > 0),
mUpdateDisplacement(rDisplacementVariables.size() > 0 ||
rDisplacementComponentVariables.size() > 0),
mRelaxationFactor(RelaxationFactor),
mDisplacementVariables(rDisplacementVariables),
mVelocityVariables(rVelocityVariables),
mAccelerationVariables(rAccelerationVariables),
mDisplacementComponentVariables(rDisplacementComponentVariables),
mVelocityComponentVariables(rVelocityComponentVariables),
mAccelerationComponentVariables(rAccelerationComponentVariables)
{
KRATOS_INFO("ResidualBasedBossakVelocityScheme")
<< " Using bossak velocity scheme with alpha_bossak = " << std::scientific
<< mAlphaBossak << " [UpdateAcceleration: " << mUpdateAcceleration
<< ", UpdateDisplacement: " << mUpdateDisplacement << "]\n";
// Allocate auxiliary memory.
const int num_threads = OpenMPUtils::GetNumThreads();
mMassMatrix.resize(num_threads);
mDampingMatrix.resize(num_threads);
mValuesVector.resize(num_threads);
mSecondDerivativeValuesVector.resize(num_threads);
mSecondDerivativeValuesVectorOld.resize(num_threads);
}
/// Destructor.
~ResidualBasedBossakVelocityScheme() override = default;
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
void InitializeSolutionStep(ModelPart& rModelPart,
SystemMatrixType& rA,
SystemVectorType& rDx,
SystemVectorType& rb) override
{
KRATOS_TRY;
BaseType::InitializeSolutionStep(rModelPart, rA, rDx, rb);
const double delta_time = rModelPart.GetProcessInfo()[DELTA_TIME];
KRATOS_ERROR_IF(delta_time < std::numeric_limits<double>::epsilon())
<< "detected delta_time = 0 in the Bossak Scheme ... "
"check if the time step is created correctly for "
"the current model part.";
ResidualBasedBossakVelocityScheme::CalculateBossakConstants(
mBossak, mAlphaBossak, delta_time);
#pragma omp critical
{
rModelPart.GetProcessInfo()[BOSSAK_ALPHA] = mBossak.Alpha;
}
KRATOS_CATCH("");
}
void Update(ModelPart& rModelPart,
DofsArrayType& rDofSet,
SystemMatrixType& rA,
SystemVectorType& rDx,
SystemVectorType& rb) override
{
KRATOS_TRY;
mpDofUpdater->UpdateDofs(rDofSet, rDx, mRelaxationFactor);
this->UpdateTimeSchemeVariables(rModelPart);
KRATOS_CATCH("");
}
void CalculateSystemContributions(Element::Pointer pCurrentElement,
LocalSystemMatrixType& rLHS_Contribution,
LocalSystemVectorType& rRHS_Contribution,
Element::EquationIdVectorType& rEquationId,
ProcessInfo& rCurrentProcessInfo) override
{
KRATOS_TRY;
const int k = OpenMPUtils::ThisThread();
(pCurrentElement)->InitializeNonLinearIteration(rCurrentProcessInfo);
(pCurrentElement)->CalculateLocalSystem(rLHS_Contribution, rRHS_Contribution, rCurrentProcessInfo);
(pCurrentElement)->CalculateLocalVelocityContribution(mDampingMatrix[k], rRHS_Contribution, rCurrentProcessInfo);
if (mUpdateAcceleration)
{
(pCurrentElement)->CalculateMassMatrix(mMassMatrix[k], rCurrentProcessInfo);
AddDynamicsToRHS(pCurrentElement, rRHS_Contribution, mDampingMatrix[k],
mMassMatrix[k], rCurrentProcessInfo);
}
AddDynamicsToLHS(rLHS_Contribution, mDampingMatrix[k], mMassMatrix[k],
rCurrentProcessInfo);
(pCurrentElement)->EquationIdVector(rEquationId, rCurrentProcessInfo);
KRATOS_CATCH("");
}
void Calculate_RHS_Contribution(Element::Pointer pCurrentElement,
LocalSystemVectorType& rRHS_Contribution,
Element::EquationIdVectorType& rEquationId,
ProcessInfo& rCurrentProcessInfo) override
{
const int k = OpenMPUtils::ThisThread();
// Initializing the non linear iteration for the current element
(pCurrentElement)->InitializeNonLinearIteration(rCurrentProcessInfo);
// basic operations for the element considered
(pCurrentElement)->CalculateRightHandSide(rRHS_Contribution, rCurrentProcessInfo);
(pCurrentElement)->CalculateLocalVelocityContribution(mDampingMatrix[k], rRHS_Contribution, rCurrentProcessInfo);
(pCurrentElement)->EquationIdVector(rEquationId, rCurrentProcessInfo);
// adding the dynamic contributions (static is already included)
if (mUpdateAcceleration)
{
(pCurrentElement)->CalculateMassMatrix(mMassMatrix[k], rCurrentProcessInfo);
AddDynamicsToRHS(pCurrentElement, rRHS_Contribution, mDampingMatrix[k],
mMassMatrix[k], rCurrentProcessInfo);
}
}
void Condition_CalculateSystemContributions(Condition::Pointer pCurrentCondition,
LocalSystemMatrixType& rLHS_Contribution,
LocalSystemVectorType& rRHS_Contribution,
Condition::EquationIdVectorType& rEquationId,
ProcessInfo& rCurrentProcessInfo) override
{
KRATOS_TRY
const int k = OpenMPUtils::ThisThread();
(pCurrentCondition)->InitializeNonLinearIteration(rCurrentProcessInfo);
(pCurrentCondition)->CalculateLocalSystem(rLHS_Contribution, rRHS_Contribution, rCurrentProcessInfo);
(pCurrentCondition)->CalculateLocalVelocityContribution(mDampingMatrix[k], rRHS_Contribution, rCurrentProcessInfo);
(pCurrentCondition)->EquationIdVector(rEquationId, rCurrentProcessInfo);
if (mUpdateAcceleration)
{
(pCurrentCondition)->CalculateMassMatrix(mMassMatrix[k], rCurrentProcessInfo);
AddDynamicsToRHS(pCurrentCondition, rRHS_Contribution,
mDampingMatrix[k], mMassMatrix[k], rCurrentProcessInfo);
}
AddDynamicsToLHS(rLHS_Contribution, mDampingMatrix[k], mMassMatrix[k],
rCurrentProcessInfo);
KRATOS_CATCH("")
}
void Condition_Calculate_RHS_Contribution(Condition::Pointer pCurrentCondition,
LocalSystemVectorType& rRHS_Contribution,
Element::EquationIdVectorType& rEquationId,
ProcessInfo& rCurrentProcessInfo) override
{
KRATOS_TRY;
const int k = OpenMPUtils::ThisThread();
(pCurrentCondition)->InitializeNonLinearIteration(rCurrentProcessInfo);
(pCurrentCondition)->CalculateRightHandSide(rRHS_Contribution, rCurrentProcessInfo);
(pCurrentCondition)->CalculateLocalVelocityContribution(mDampingMatrix[k], rRHS_Contribution, rCurrentProcessInfo);
(pCurrentCondition)->EquationIdVector(rEquationId, rCurrentProcessInfo);
// adding the dynamic contributions (static is already included)
if (mUpdateAcceleration)
{
(pCurrentCondition)->CalculateMassMatrix(mMassMatrix[k], rCurrentProcessInfo);
AddDynamicsToRHS(pCurrentCondition, rRHS_Contribution,
mDampingMatrix[k], mMassMatrix[k], rCurrentProcessInfo);
}
KRATOS_CATCH("");
}
void Clear() override
{
this->mpDofUpdater->Clear();
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "ResidualBasedBossakVelocityScheme";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << Info();
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
rOStream << Info();
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
struct BossakConstants
{
double Alpha;
double Gamma;
double Beta;
double C0;
double C1;
double C2;
double C3;
double C4;
double C5;
double C6;
};
///@}
///@name Protected member Variables
///@{
std::vector<LocalSystemVectorType> mSecondDerivativeValuesVectorOld;
std::vector<LocalSystemVectorType> mSecondDerivativeValuesVector;
std::vector<LocalSystemVectorType> mValuesVector;
std::vector<LocalSystemMatrixType> mMassMatrix;
std::vector<LocalSystemMatrixType> mDampingMatrix;
const double mAlphaBossak;
bool mUpdateAcceleration;
bool mUpdateDisplacement;
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
//****************************************************************************
/**
Kdyn = am*M + D + a1*K
*/
void AddDynamicsToLHS(LocalSystemMatrixType& rLHS_Contribution,
LocalSystemMatrixType& rDampingMatrix,
LocalSystemMatrixType& rMassMatrix,
ProcessInfo& CurrentProcessInfo)
{
// multipling time scheme factor
rLHS_Contribution *= mBossak.C1;
// adding mass contribution to the dynamic stiffness
if (rMassMatrix.size1() != 0 && mUpdateAcceleration) // if M matrix declared
{
noalias(rLHS_Contribution) += mBossak.C0 * rMassMatrix;
}
// adding damping contribution
if (rDampingMatrix.size1() != 0) // if M matrix declared
{
noalias(rLHS_Contribution) += rDampingMatrix;
}
}
//****************************************************************************
/// Add Bossak contributions from the inertial term to the RHS vector.
/** This essentially performs bdyn = b - M*acc for the current element.
* Note that viscous/pressure contributions to the RHS are expected to be added by the element itself.
* @param[in] rCurrentElement The fluid element we are assembling.
* @param[in/out] rRHS_Contribution The right hand side term where the contribution will be added.
* @param[in] rD The elemental velocity/pressure LHS matrix.
* @param[in] rM The elemental acceleration LHS matrix.
* @param[in] rCurrentProcessInfo ProcessInfo instance for the containing ModelPart.
*/
void AddDynamicsToRHS(Element::Pointer rCurrentElement,
LocalSystemVectorType& rRHS_Contribution,
LocalSystemMatrixType& rDampingMatrix,
LocalSystemMatrixType& rMassMatrix,
ProcessInfo& rCurrentProcessInfo)
{
// adding inertia contribution
if (rMassMatrix.size1() != 0)
{
const int k = OpenMPUtils::ThisThread();
rCurrentElement->GetSecondDerivativesVector(
mSecondDerivativeValuesVector[k], 0);
(mSecondDerivativeValuesVector[k]) *= (1.00 - mBossak.Alpha);
rCurrentElement->GetSecondDerivativesVector(
mSecondDerivativeValuesVectorOld[k], 1);
noalias(mSecondDerivativeValuesVector[k]) +=
mBossak.Alpha * mSecondDerivativeValuesVectorOld[k];
noalias(rRHS_Contribution) -=
prod(rMassMatrix, mSecondDerivativeValuesVector[k]);
}
}
/// Add Bossak contributions from the inertial term to the RHS vector.
/** This essentially performs bdyn = b - M*acc for the current condition.
* Note that viscous/pressure contributions to the RHS are expected to be added by the element condition.
* @param[in] rCurrentCondition The fluid condition we are assembling.
* @param[in/out] rRHS_Contribution The right hand side term where the contribution will be added.
* @param[in] rD The elemental velocity/pressure LHS matrix.
* @param[in] rM The elemental acceleration LHS matrix.
* @param[in] rCurrentProcessInfo ProcessInfo instance for the containing ModelPart.
*/
void AddDynamicsToRHS(Condition::Pointer rCurrentCondition,
LocalSystemVectorType& rRHS_Contribution,
LocalSystemMatrixType& rDampingMatrix,
LocalSystemMatrixType& rMassMatrix,
ProcessInfo& rCurrentProcessInfo)
{
// adding inertia contribution
if (rMassMatrix.size1() != 0)
{
const int k = OpenMPUtils::ThisThread();
rCurrentCondition->GetSecondDerivativesVector(
mSecondDerivativeValuesVector[k], 0);
(mSecondDerivativeValuesVector[k]) *= (1.00 - mBossak.Alpha);
rCurrentCondition->GetSecondDerivativesVector(
mSecondDerivativeValuesVectorOld[k], 1);
noalias(mSecondDerivativeValuesVector[k]) +=
mBossak.Alpha * mSecondDerivativeValuesVectorOld[k];
noalias(rRHS_Contribution) -=
prod(rMassMatrix, mSecondDerivativeValuesVector[k]);
}
}
void UpdateTimeSchemeVariables(ModelPart& rModelPart)
{
KRATOS_TRY;
UpdateAcceleration<Variable<double>>(rModelPart, mVelocityVariables,
mAccelerationVariables);
UpdateAcceleration<Variable<double>>(
rModelPart, mVelocityComponentVariables, mAccelerationComponentVariables);
UpdateDisplacement<Variable<double>>(rModelPart, mDisplacementVariables,
mVelocityVariables, mAccelerationVariables);
UpdateDisplacement<Variable<double>>(
rModelPart, mDisplacementComponentVariables,
mVelocityComponentVariables, mAccelerationComponentVariables);
KRATOS_CATCH("");
}
void UpdateAcceleration(double& rCurrentAcceleration,
const double CurrentVelocity,
const double OldVelocity,
const double OldAcceleration) const
{
rCurrentAcceleration = mBossak.C2 * (CurrentVelocity - OldVelocity) -
mBossak.C3 * OldAcceleration;
}
void UpdateDisplacement(double& rCurrentDisplacement,
const double OldDisplacement,
const double OldVelocity,
const double CurrentAcceleration,
const double OldAcceleration) const
{
rCurrentDisplacement = OldDisplacement + mBossak.C6 * OldVelocity +
mBossak.C4 * OldAcceleration + mBossak.C5 * CurrentAcceleration;
}
static void CalculateBossakConstants(BossakConstants& rBossakConstants,
const double Alpha,
const double DeltaTime)
{
TimeDiscretization::Bossak bossak(Alpha, 0.25, 0.5);
rBossakConstants.Alpha = bossak.GetAlphaM();
rBossakConstants.Gamma = bossak.GetGamma();
rBossakConstants.Beta = bossak.GetBeta();
rBossakConstants.C0 =
(1.0 - rBossakConstants.Alpha) / (rBossakConstants.Gamma * DeltaTime);
rBossakConstants.C1 =
DeltaTime / (rBossakConstants.Beta * rBossakConstants.Gamma);
rBossakConstants.C2 = 1.0 / (rBossakConstants.Gamma * DeltaTime);
rBossakConstants.C3 = (1.0 - rBossakConstants.Gamma) / rBossakConstants.Gamma;
rBossakConstants.C4 =
std::pow(DeltaTime, 2) * (-2.0 * rBossakConstants.Beta + 1.0) / 2.0;
rBossakConstants.C5 = std::pow(DeltaTime, 2) * rBossakConstants.Beta;
rBossakConstants.C6 = DeltaTime;
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
using DofUpdaterType = RelaxedDofUpdater<TSparseSpace>;
using DofUpdaterPointerType = typename DofUpdaterType::UniquePointer;
DofUpdaterPointerType mpDofUpdater = Kratos::make_unique<DofUpdaterType>();
double mRelaxationFactor;
const std::vector<Variable<double> const*> mDisplacementVariables;
const std::vector<Variable<double> const*> mVelocityVariables;
const std::vector<Variable<double> const*> mAccelerationVariables;
const std::vector<Variable<double> const*> mDisplacementComponentVariables;
const std::vector<Variable<double> const*> mVelocityComponentVariables;
const std::vector<Variable<double> const*> mAccelerationComponentVariables;
BossakConstants mBossak;
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
// class to hold all the derivatives for updated target variable
template <class TVariableType>
void UpdateAcceleration(ModelPart& rModelPart,
const std::vector<TVariableType const*>& pVelocityVariables,
const std::vector<TVariableType const*>& pAccelerationVariables)
{
if (!mUpdateAcceleration)
return;
const int number_of_nodes = rModelPart.NumberOfNodes();
#pragma omp parallel for
for (int i_node = 0; i_node < number_of_nodes; ++i_node)
{
NodeType& r_node = *(rModelPart.NodesBegin() + i_node);
for (IndexType i_var = 0; i_var < pAccelerationVariables.size(); ++i_var)
{
double& r_current_acceleration =
r_node.FastGetSolutionStepValue(*pAccelerationVariables[i_var]);
const double old_acceleration = r_node.FastGetSolutionStepValue(
*pAccelerationVariables[i_var], 1);
const double current_velocity =
r_node.FastGetSolutionStepValue(*pVelocityVariables[i_var]);
const double old_velocity =
r_node.FastGetSolutionStepValue(*pVelocityVariables[i_var], 1);
UpdateAcceleration(r_current_acceleration, current_velocity,
old_velocity, old_acceleration);
}
}
}
template <class TVariableType>
void UpdateDisplacement(ModelPart& rModelPart,
const std::vector<TVariableType const*>& pDisplacementVariables,
const std::vector<TVariableType const*>& pVelocityVariables,
const std::vector<TVariableType const*>& pAccelerationVariables)
{
if (!mUpdateDisplacement)
return;
const int number_of_nodes = rModelPart.NumberOfNodes();
#pragma omp parallel for
for (int i_node = 0; i_node < number_of_nodes; ++i_node)
{
NodeType& r_node = *(rModelPart.NodesBegin() + i_node);
for (IndexType i_var = 0; i_var < pDisplacementVariables.size(); ++i_var)
{
double& r_current_displacement =
r_node.FastGetSolutionStepValue(*pDisplacementVariables[i_var]);
const double old_displacement = r_node.FastGetSolutionStepValue(
*pDisplacementVariables[i_var], 1);
const double current_acceleration =
r_node.FastGetSolutionStepValue(*pAccelerationVariables[i_var]);
const double old_acceleration = r_node.FastGetSolutionStepValue(
*pAccelerationVariables[i_var], 1);
const double old_velocity =
r_node.FastGetSolutionStepValue(*pVelocityVariables[i_var], 1);
UpdateDisplacement(r_current_displacement, old_displacement, old_velocity,
current_acceleration, old_acceleration);
}
}
}
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class ResidualBasedBossakVelocityScheme */
///@}
///@name Type Definitions
///@{
///@}
} /* namespace Kratos.*/
#endif /* KRATOS_RESIDUAL_BASED_BOSSAK_VELOCITY_SCHEME_H_INCLUDED defined */
|
residualbased_block_builder_and_solver_with_constraints_elementwise.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Aditya Ghantasala
//
//
#if !defined(KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER_WITH_CONSTRAINTS_ELEMENTWISE)
#define KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER_WITH_CONSTRAINTS_ELEMENTWISE
/* System includes */
#include <unordered_set>
#include <unordered_map>
/* External includes */
/* Project includes */
#include "solving_strategies/builder_and_solvers/residualbased_block_builder_and_solver.h"
#include "includes/master_slave_constraint.h"
#include "utilities/helper_classes_for_constraint_builder.h"
#include "includes/key_hash.h"
#include "containers/pointer_vector_map.h"
#include "containers/pointer_hash_map_set.h"
#include "containers/data_value_container.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise
* @ingroup KratosCore
* @brief Current class provides an implementation for standard builder and solving operations.
* @details The RHS is constituted by the unbalanced loads (residual)
* Degrees of freedom are reordered putting the restrained degrees of freedom at
* the end of the system ordered in reverse order with respect to the DofSet.
* Imposition of the dirichlet conditions is naturally dealt with as the residual already contains
* this information.
* Calculation of the reactions involves a cost very similar to the calculation of the total residual
* @author Aditya Ghantasala
*/
template <class TSparseSpace,
class TDenseSpace,
class TLinearSolver
>
class ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise
: public ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>
{
public:
///@name Type Definitions
///@{
KRATOS_CLASS_POINTER_DEFINITION(ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise);
typedef ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver> BaseType;
typedef typename BaseType::TSchemeType TSchemeType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
typedef typename BaseType::LocalSystemVectorType LocalSystemVectorType;
typedef typename BaseType::LocalSystemMatrixType LocalSystemMatrixType;
typedef typename BaseType::TSystemMatrixPointerType TSystemMatrixPointerType;
typedef typename BaseType::TSystemVectorPointerType TSystemVectorPointerType;
typedef typename BaseType::NodeType NodeType;
typedef typename BaseType::NodesArrayType NodesArrayType;
typedef typename BaseType::ElementsArrayType ElementsArrayType;
typedef typename BaseType::ConditionsArrayType ConditionsArrayType;
typedef typename BaseType::ElementsContainerType ElementsContainerType;
typedef MasterSlaveConstraint MasterSlaveConstraintType;
typedef typename MasterSlaveConstraint::Pointer MasterSlaveConstraintPointerType;
typedef Internals::AuxiliaryGlobalMasterSlaveConstraint AuxiliaryGlobalMasterSlaveConstraintType;
typedef Internals::GlobalMasterSlaveRelationContainerType GlobalMasterSlaveRelationContainerType;
typedef std::vector<IndexType> EquationIdVectorType;
typedef std::vector<IndexType> VectorIndexType;
typedef std::vector<Dof<double>::Pointer> DofsVectorType;
typedef Vector VectorType;
typedef Internals::ConstraintImposer<TSparseSpace, TDenseSpace, TLinearSolver> ConstraintImposerType;
///@}
///@name Life Cycle
///@{
/**
* @brief Default constructor. (with parameters)
*/
explicit ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise(
typename TLinearSolver::Pointer pNewLinearSystemSolver,
Parameters ThisParameters
) : BaseType(pNewLinearSystemSolver)
{
// Validate default parameters
Parameters default_parameters = Parameters(R"(
{
"name" : "ResidualBasedBlockBuilderAndSolverWithConstraints"
})" );
ThisParameters.ValidateAndAssignDefaults(default_parameters);
}
/**
* @brief Default constructor
*/
explicit ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise(
typename TLinearSolver::Pointer pNewLinearSystemSolver)
: BaseType(pNewLinearSystemSolver)
{
}
/** Destructor.
*/
~ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise() override
{
}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
void SetUpSystem(
ModelPart &rModelPart) override
{
BaseType::SetUpSystem(rModelPart);
if(rModelPart.NumberOfMasterSlaveConstraints() > 0)
{
FormulateGlobalMasterSlaveRelations(rModelPart);
}
}
/**
* @brief Function to perform the build of the RHS. The vector could be sized as the total number
* of dofs or as the number of unrestrained ones
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param A The LHS matrix
* @param b The RHS vector
*/
void Build(
typename TSchemeType::Pointer pScheme,
ModelPart &rModelPart,
TSystemMatrixType &A,
TSystemVectorType &b) override
{
if(mGlobalMasterSlaveConstraints.size() > 0)
BuildWithConstraints(pScheme, rModelPart, A, b);
else
BaseType::Build(pScheme, rModelPart, A, b);
}
/**
* @brief Function to perform the building and solving phase at the same time.
* @details It is ideally the fastest and safer function to use when it is possible to solve
* just after building
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
* @param A The LHS matrix
* @param Dx The Unknowns vector
* @param b The RHS vector
*/
void BuildAndSolve(
typename TSchemeType::Pointer pScheme,
ModelPart &rModelPart,
TSystemMatrixType &A,
TSystemVectorType &Dx,
TSystemVectorType &b) override
{
if(mGlobalMasterSlaveConstraints.size() > 0)
BuildAndSolveWithConstraints(pScheme, rModelPart, A, Dx, b);
else
BaseType::BuildAndSolve(pScheme, rModelPart, A, Dx, b);
}
void InitializeSolutionStep(
ModelPart &rModelPart,
TSystemMatrixType &A,
TSystemVectorType &Dx,
TSystemVectorType &b) override
{
KRATOS_TRY
BaseType::InitializeSolutionStep(rModelPart, A, Dx, b);
// Getting process info
const ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
// Computing constraints
const int n_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
auto constraints_begin = rModelPart.MasterSlaveConstraintsBegin();
#pragma omp parallel for schedule(guided, 512) firstprivate(n_constraints, constraints_begin)
for (int k = 0; k < n_constraints; k++)
{
auto it = constraints_begin + k;
it->InitializeSolutionStep(r_process_info); // Here each constraint constructs and stores its T and C matrices. Also its equation ids.
}
KRATOS_CATCH("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise failed to initialize solution step.")
}
void FinalizeSolutionStep(
ModelPart &rModelPart,
TSystemMatrixType &A,
TSystemVectorType &Dx,
TSystemVectorType &b) override
{
KRATOS_TRY
BaseType::FinalizeSolutionStep(rModelPart, A, Dx, b);
// Getting process info
const ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
// Computing constraints
const int n_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
const auto constraints_begin = rModelPart.MasterSlaveConstraintsBegin();
#pragma omp parallel for schedule(guided, 512) firstprivate(n_constraints, constraints_begin)
for (int k = 0; k < n_constraints; k++)
{
auto it = constraints_begin + k;
it->FinalizeSolutionStep(r_process_info);
}
KRATOS_CATCH("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise failed to finalize solution step.")
}
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << Info();
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
rOStream << Info();
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
void ConstructMatrixStructure(
typename TSchemeType::Pointer pScheme,
TSystemMatrixType &A,
ModelPart &rModelPart) override
{
if(mGlobalMasterSlaveConstraints.size() > 0)
ConstructMatrixStructureWithConstraints(pScheme, A, rModelPart);
else
BaseType::ConstructMatrixStructure(pScheme, A, rModelPart);
}
/*
* This function is exactly same as the ConstructMatrixStructure() function in base class except that the function
* has the call to ApplyConstraints function call once the element and conditions compute their equation ids
*/
virtual void ConstructMatrixStructureWithConstraints(
typename TSchemeType::Pointer pScheme,
TSystemMatrixType& A,
ModelPart& rModelPart)
{
//filling with zero the matrix (creating the structure)
Timer::Start("MatrixStructure");
// To Impose constraints
ConstraintImposerType constraint_imposer(mGlobalMasterSlaveConstraints);
// Getting the elements from the model
const int nelements = static_cast<int>(rModelPart.Elements().size());
// Getting the array of the conditions
const int nconditions = static_cast<int>(rModelPart.Conditions().size());
ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo();
ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin();
ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin();
ModelPart::MasterSlaveConstraintContainerType::iterator constraints_begin = rModelPart.MasterSlaveConstraints().begin();
const std::size_t equation_size = BaseType::mEquationSystemSize;
std::vector< LockObject > lock_array(equation_size);
std::vector<std::unordered_set<std::size_t> > indices(equation_size);
#pragma omp parallel for firstprivate(equation_size)
for (int iii = 0; iii < static_cast<int>(equation_size); iii++) {
indices[iii].reserve(40);
}
Element::EquationIdVectorType ids(3, 0);
#pragma omp parallel for firstprivate(nelements, ids, constraint_imposer)
for (int iii=0; iii<nelements; iii++) {
typename ElementsContainerType::iterator i_element = el_begin + iii;
pScheme->EquationId( *(i_element.base()) , ids, CurrentProcessInfo);
constraint_imposer.template ApplyConstraints<Element>(*i_element, ids, CurrentProcessInfo);
for (std::size_t i = 0; i < ids.size(); i++) {
lock_array[ids[i]].SetLock();
auto& row_indices = indices[ids[i]];
row_indices.insert(ids.begin(), ids.end());
lock_array[ids[i]].UnSetLock();
}
}
#pragma omp parallel for firstprivate(nconditions, ids, constraint_imposer)
for (int iii = 0; iii<nconditions; iii++) {
typename ConditionsArrayType::iterator i_condition = cond_begin + iii;
pScheme->Condition_EquationId( *(i_condition.base()), ids, CurrentProcessInfo);
constraint_imposer.template ApplyConstraints<Condition>(*i_condition, ids, CurrentProcessInfo);
for (std::size_t i = 0; i < ids.size(); i++) {
lock_array[ids[i]].SetLock();
auto& row_indices = indices[ids[i]];
row_indices.insert(ids.begin(), ids.end());
lock_array[ids[i]].UnSetLock();
}
}
Element::EquationIdVectorType aux_ids(3, 0);
const int nconstraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
#pragma omp parallel for firstprivate(nconstraints, ids, aux_ids)
for (int iii = 0; iii<nconstraints; iii++) {
ModelPart::MasterSlaveConstraintContainerType::iterator i_constraint = constraints_begin + iii;
i_constraint->EquationIdVector(ids, aux_ids, CurrentProcessInfo);
for (std::size_t i = 0; i < ids.size(); i++) {
lock_array[ids[i]].SetLock();
auto& row_indices = indices[ids[i]];
row_indices.insert(ids.begin(), ids.end());
lock_array[ids[i]].UnSetLock();
}
for (std::size_t i = 0; i < aux_ids.size(); i++) {
lock_array[aux_ids[i]].SetLock();
auto& row_indices = indices[aux_ids[i]];
row_indices.insert(aux_ids.begin(), aux_ids.end());
lock_array[aux_ids[i]].UnSetLock();
}
}
//destroy locks
lock_array = std::vector< LockObject >();
//count the row sizes
unsigned int nnz = 0;
for (unsigned int i = 0; i < indices.size(); i++) {
nnz += indices[i].size();
}
A = boost::numeric::ublas::compressed_matrix<double>(indices.size(), indices.size(), nnz);
double* Avalues = A.value_data().begin();
std::size_t* Arow_indices = A.index1_data().begin();
std::size_t* Acol_indices = A.index2_data().begin();
//filling the index1 vector - DO NOT MAKE PARALLEL THE FOLLOWING LOOP!
Arow_indices[0] = 0;
for (int i = 0; i < static_cast<int>(A.size1()); i++) {
Arow_indices[i+1] = Arow_indices[i] + indices[i].size();
}
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(A.size1()); i++) {
const unsigned int row_begin = Arow_indices[i];
const unsigned int row_end = Arow_indices[i+1];
unsigned int k = row_begin;
for (auto it = indices[i].begin(); it != indices[i].end(); it++) {
Acol_indices[k] = *it;
Avalues[k] = 0.0;
k++;
}
indices[i].clear(); //deallocating the memory
std::sort(&Acol_indices[row_begin], &Acol_indices[row_end]);
}
A.set_filled(indices.size()+1, nnz);
Timer::Stop("MatrixStructure");
}
void BuildAndSolveWithConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart &rModelPart,
TSystemMatrixType &A,
TSystemVectorType &Dx,
TSystemVectorType &b)
{
KRATOS_TRY
const double start_update_constraints = OpenMPUtils::GetCurrentTime();
this->UpdateConstraintsForBuilding(rModelPart);
const double stop_update_constraints = OpenMPUtils::GetCurrentTime();
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Constraints update time : " << stop_update_constraints - start_update_constraints << std::endl;
Timer::Start("Build");
Build(pScheme, rModelPart, A, b);
Timer::Stop("Build");
this->ApplyDirichletConditions(pScheme, rModelPart, A, Dx, b);
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", (this->GetEchoLevel() == 3)) << "Before the solution of the system"
<< "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl;
const double start_solve = OpenMPUtils::GetCurrentTime();
Timer::Start("Solve");
this->SystemSolveWithPhysics(A, Dx, b, rModelPart);
Timer::Stop("Solve");
const double stop_solve = OpenMPUtils::GetCurrentTime();
const double start_reconstruct_slaves = OpenMPUtils::GetCurrentTime();
ReconstructSlaveSolutionAfterSolve(rModelPart, A, Dx, b);
const double stop_reconstruct_slaves = OpenMPUtils::GetCurrentTime();
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Reconstruct slaves time: " << stop_reconstruct_slaves - start_reconstruct_slaves << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "System solve time: " << stop_solve - start_solve << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", (this->GetEchoLevel() == 3)) << "After the solution of the system"
<< "\nSystem Matrix = " << A << "\nUnknowns vector = " << Dx << "\nRHS vector = " << b << std::endl;
KRATOS_CATCH("")
}
/*
* This function is exactly same as the Build() function in base class except that the function
* has the call to ApplyConstraints function call once the LHS or RHS are computed by elements and conditions
*/
void BuildWithConstraints(
typename TSchemeType::Pointer pScheme,
ModelPart &rModelPart,
TSystemMatrixType &A,
TSystemVectorType &b)
{
KRATOS_TRY
KRATOS_ERROR_IF(!pScheme) << "No scheme provided!" << std::endl;
ConstraintImposerType constraint_imposer(mGlobalMasterSlaveConstraints);
// Getting the elements from the model
const int nelements = static_cast<int>(rModelPart.Elements().size());
// Getting the array of the conditions
const int nconditions = static_cast<int>(rModelPart.Conditions().size());
ProcessInfo &CurrentProcessInfo = rModelPart.GetProcessInfo();
const ModelPart::ElementsContainerType::iterator el_begin = rModelPart.ElementsBegin();
const ModelPart::ConditionsContainerType::iterator cond_begin = rModelPart.ConditionsBegin();
//contributions to the system
LocalSystemMatrixType LHS_Contribution = LocalSystemMatrixType(0, 0);
LocalSystemVectorType RHS_Contribution = LocalSystemVectorType(0);
//vector containing the localization in the system of the different
//terms
Element::EquationIdVectorType EquationId;
// assemble all elements
double start_build = OpenMPUtils::GetCurrentTime();
#pragma omp parallel firstprivate(nelements, nconditions, LHS_Contribution, RHS_Contribution, EquationId, constraint_imposer)
{
#pragma omp for schedule(guided, 512) nowait
for (int k = 0; k < nelements; k++)
{
ModelPart::ElementsContainerType::iterator it = el_begin + k;
//detect if the element is active or not. If the user did not make any choice the element
//is active by default
bool element_is_active = true;
if ((it)->IsDefined(ACTIVE))
element_is_active = (it)->Is(ACTIVE);
if (element_is_active)
{
//calculate elemental contribution
pScheme->CalculateSystemContributions(*(it.base()), LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo);
constraint_imposer.template ApplyConstraints<Element>(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo);
//assemble the elemental contribution
#ifdef USE_LOCKS_IN_ASSEMBLY
this->Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, BaseType::mlock_array);
#else
this->Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId);
#endif
// clean local elemental memory
pScheme->CleanMemory(*(it.base()));
}
}
//#pragma omp parallel for firstprivate(nconditions, LHS_Contribution, RHS_Contribution, EquationId ) schedule(dynamic, 1024)
#pragma omp for schedule(guided, 512)
for (int k = 0; k < nconditions; k++)
{
ModelPart::ConditionsContainerType::iterator it = cond_begin + k;
//detect if the element is active or not. If the user did not make any choice the element
//is active by default
bool condition_is_active = true;
if ((it)->IsDefined(ACTIVE))
condition_is_active = (it)->Is(ACTIVE);
if (condition_is_active)
{
//calculate elemental contribution
pScheme->Condition_CalculateSystemContributions(*(it.base()), LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo);
constraint_imposer.template ApplyConstraints<Condition>(*it, LHS_Contribution, RHS_Contribution, EquationId, CurrentProcessInfo);
//assemble the elemental contribution
#ifdef USE_LOCKS_IN_ASSEMBLY
this->Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId, BaseType::mlock_array);
#else
this->Assemble(A, b, LHS_Contribution, RHS_Contribution, EquationId);
#endif
// clean local elemental memory
pScheme->CleanMemory(*(it.base()));
}
}
}
const double stop_build = OpenMPUtils::GetCurrentTime();
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Build time: " << stop_build - start_build << std::endl;
//for (int i = 0; i < A_size; i++)
// omp_destroy_lock(&lock_array[i]);
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", (this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished parallel building" << std::endl;
KRATOS_CATCH("")
}
/**
* @brief Builds the list of the DofSets involved in the problem by "asking" to each element
* and condition its Dofs.
* @details The list of dofs is stores insde the BuilderAndSolver as it is closely connected to the
* way the matrix and RHS are built
* @param pScheme The integration scheme considered
* @param rModelPart The model part of the problem to solve
*/
void SetUpDofSet(
typename TSchemeType::Pointer pScheme,
ModelPart& rModelPart
) override
{
KRATOS_TRY;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", ( this->GetEchoLevel() > 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Setting up the dofs" << std::endl;
//Gets the array of elements from the modeler
ElementsArrayType& pElements = rModelPart.Elements();
const int nelements = static_cast<int>(pElements.size());
Element::DofsVectorType ElementalDofList, AuxiliarDofList;
ProcessInfo& CurrentProcessInfo = rModelPart.GetProcessInfo();
unsigned int nthreads = OpenMPUtils::GetNumThreads();
typedef std::unordered_set < typename NodeType::DofType::Pointer, DofPointerHasher> set_type;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", ( this->GetEchoLevel() > 2)) << "Number of threads" << nthreads << "\n" << std::endl;
set_type dof_global_set;
dof_global_set.reserve(nelements*20);
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", ( this->GetEchoLevel() > 2)) << "Initializing element loop" << std::endl;
#pragma omp parallel firstprivate(nelements, ElementalDofList, AuxiliarDofList)
{
set_type dofs_tmp_set;
dofs_tmp_set.reserve(20000);
#pragma omp for schedule(guided, 512) nowait
for (int i = 0; i < nelements; i++)
{
typename ElementsArrayType::iterator it = pElements.begin() + i;
// gets list of Dof involved on every element
pScheme->GetElementalDofList(*(it.base()), ElementalDofList, CurrentProcessInfo);
dofs_tmp_set.insert(ElementalDofList.begin(), ElementalDofList.end());
}
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", ( this->GetEchoLevel() > 2)) << "Initializing condition loop" << std::endl;
ConditionsArrayType& pConditions = rModelPart.Conditions();
const int nconditions = static_cast<int>(pConditions.size());
#pragma omp for schedule(guided, 512)
for (int i = 0; i < nconditions; i++)
{
typename ConditionsArrayType::iterator it = pConditions.begin() + i;
// gets list of Dof involved on every element
pScheme->GetConditionDofList(*(it.base()), ElementalDofList, CurrentProcessInfo);
dofs_tmp_set.insert(ElementalDofList.begin(), ElementalDofList.end());
}
auto& pConstraints = rModelPart.MasterSlaveConstraints();
const int nconstraints = static_cast<int>(pConstraints.size());
#pragma omp for schedule(guided, 512)
for (int i = 0; i < nconstraints; i++)
{
auto it = pConstraints.begin() + i;
// gets list of Dof involved on every element
it->GetDofList(ElementalDofList, AuxiliarDofList, CurrentProcessInfo);
dofs_tmp_set.insert(ElementalDofList.begin(), ElementalDofList.end());
dofs_tmp_set.insert(AuxiliarDofList.begin(), AuxiliarDofList.end());
}
#pragma omp critical
{
dof_global_set.insert(dofs_tmp_set.begin(), dofs_tmp_set.end());
}
}
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", ( this->GetEchoLevel() > 2)) << "Initializing ordered array filling\n" << std::endl;
DofsArrayType Doftemp;
BaseType::mDofSet = DofsArrayType();
Doftemp.reserve(dof_global_set.size());
for (auto it= dof_global_set.begin(); it!= dof_global_set.end(); it++)
{
Doftemp.push_back( it->get() );
}
Doftemp.Sort();
BaseType::mDofSet = Doftemp;
//Throws an exception if there are no Degrees Of Freedom involved in the analysis
KRATOS_ERROR_IF(BaseType::mDofSet.size() == 0) << "No degrees of freedom!" << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", ( this->GetEchoLevel() > 2)) << "Number of degrees of freedom:" << BaseType::mDofSet.size() << std::endl;
BaseType::mDofSetIsInitialized = true;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", ( this->GetEchoLevel() > 2 && rModelPart.GetCommunicator().MyPID() == 0)) << "Finished setting up the dofs" << std::endl;
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", ( this->GetEchoLevel() > 2)) << "End of setup dof set\n" << std::endl;
#ifdef KRATOS_DEBUG
// If reactions are to be calculated, we check if all the dofs have reactions defined
// This is tobe done only in debug mode
if (BaseType::GetCalculateReactionsFlag()) {
for (auto dof_iterator = BaseType::mDofSet.begin(); dof_iterator != BaseType::mDofSet.end(); ++dof_iterator) {
KRATOS_ERROR_IF_NOT(dof_iterator->HasReaction()) << "Reaction variable not set for the following : " <<std::endl
<< "Node : "<<dof_iterator->Id()<< std::endl
<< "Dof : "<<(*dof_iterator)<<std::endl<<"Not possible to calculate reactions."<<std::endl;
}
}
#endif
KRATOS_CATCH("");
}
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
// This is the set of condenced global constraints.
GlobalMasterSlaveRelationContainerType mGlobalMasterSlaveConstraints; //This can be changed to more efficient implementation later on.
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
/**
* @brief this method condenses the MasterSlaveConstraints which are added on the rModelPart
* into objects of AuxilaryGlobalMasterSlaveRelation. One unique object for each unique slave.
* these will be used in the ApplyConstraints functions later on.
* @param rModelPart The model part of the problem to solve
*/
void FormulateGlobalMasterSlaveRelations(ModelPart& rModelPart)
{
KRATOS_TRY
const double start_formulate = OpenMPUtils::GetCurrentTime();
// First delete the existing ones
mGlobalMasterSlaveConstraints.clear();
// Getting the array of the conditions
const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
// Getting the beginning iterator
const ModelPart::MasterSlaveConstraintContainerType::iterator constraints_begin = rModelPart.MasterSlaveConstraintsBegin();
ProcessInfo &r_current_process_info = rModelPart.GetProcessInfo();
#pragma omp parallel for schedule(guided, 512)
for (int i_constraints = 0; i_constraints < number_of_constraints; i_constraints++)
{
ModelPart::MasterSlaveConstraintContainerType::iterator it = constraints_begin;
std::advance(it, i_constraints);
//detect if the element is active or not. If the user did not make any choice the element
//is active by default
bool constraint_is_active = true;
if ((it)->IsDefined(ACTIVE))
constraint_is_active = (it)->Is(ACTIVE);
if (constraint_is_active)
{
//assemble the Constraint contribution
#pragma omp critical
AssembleConstraint(*it, r_current_process_info);
}
}
const double stop_formulate = OpenMPUtils::GetCurrentTime();
KRATOS_INFO_IF("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise", (this->GetEchoLevel() >= 1 && rModelPart.GetCommunicator().MyPID() == 0)) << "Formulate global constraints time: " << stop_formulate - start_formulate << std::endl;
KRATOS_CATCH("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise::FormulateGlobalMasterSlaveRelations failed ..");
}
/**
* @brief this method assembles the given master slave constraint to the auxiliary global master slave constraints
* @param rMasterSlaveConstraint object of the master slave constraint to be assembled.
* @param rCurrentProcessInfo current process info.
*/
void AssembleConstraint(ModelPart::MasterSlaveConstraintType& rMasterSlaveConstraint, ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
int slave_count = 0;
LocalSystemMatrixType relation_matrix(0,0);
LocalSystemVectorType constant_vector(0);
EquationIdVectorType slave_equation_ids(0);
EquationIdVectorType master_equation_ids(0);
//get the equation Ids of the constraint
rMasterSlaveConstraint.EquationIdVector(slave_equation_ids, master_equation_ids, rCurrentProcessInfo);
//calculate constraint's T and b matrices
rMasterSlaveConstraint.CalculateLocalSystem(relation_matrix, constant_vector, rCurrentProcessInfo);
for (auto slave_equation_id : slave_equation_ids)
{
int master_count = 0;
auto global_constraint = mGlobalMasterSlaveConstraints.find(slave_equation_id);
if (global_constraint == mGlobalMasterSlaveConstraints.end())
{
mGlobalMasterSlaveConstraints[slave_equation_id] = Kratos::make_unique<AuxiliaryGlobalMasterSlaveConstraintType>(slave_equation_id);
}
global_constraint = mGlobalMasterSlaveConstraints.find(slave_equation_id);
for (auto master_equation_id : master_equation_ids)
{
global_constraint->second->AddMaster(master_equation_id, relation_matrix(slave_count, master_count));
master_count++;
}
slave_count++;
}
KRATOS_CATCH("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise::AssembleSlaves failed ...");
}
/**
* @brief this method resets the LHS and RHS values of the AuxilaryGlobalMasterSlaveRelation objects
*/
void ResetConstraintRelations()
{
KRATOS_TRY
const int number_of_constraints = static_cast<int>(mGlobalMasterSlaveConstraints.size());
// Getting the beginning iterator
const GlobalMasterSlaveRelationContainerType::iterator constraints_begin = mGlobalMasterSlaveConstraints.begin();
#pragma omp parallel for schedule(guided, 512)
for (int i_constraints = 0; i_constraints < number_of_constraints; ++i_constraints)
{
//GlobalMasterSlaveRelationContainerType::iterator it = constraints_begin + i_constraints;
GlobalMasterSlaveRelationContainerType::iterator it = constraints_begin;
std::advance(it, i_constraints);
(it->second)->Reset();
}
KRATOS_CATCH("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise::ResetConstraintRelations failed to reset constraint relations..");
}
/**
* @brief this method uses the MasterSlaveConstraints objects in rModelPart to reconstruct the LHS and RHS values
* of the AuxilaryGlobalMasterSlaveRelation objects. That is the value of Slave as LHS and the T*M+C as RHS value
* @param rModelPart The model part of the problem to solve
*/
void UpdateConstraintsForBuilding(ModelPart& rModelPart)
{
KRATOS_TRY
// Reset the constraint equations
ResetConstraintRelations();
// Getting the array of the conditions
const int number_of_constraints = static_cast<int>(rModelPart.MasterSlaveConstraints().size());
// Getting the beginning iterator
const ModelPart::MasterSlaveConstraintContainerType::iterator constraints_begin = rModelPart.MasterSlaveConstraintsBegin();
ProcessInfo &r_current_process_info = rModelPart.GetProcessInfo();
#pragma omp parallel for schedule(guided, 512)
for (int i_constraints = 0; i_constraints < number_of_constraints; i_constraints++)
{
ModelPart::MasterSlaveConstraintContainerType::iterator it = constraints_begin;
std::advance(it, i_constraints);
//detect if the element is active or not. If the user did not make any choice the element
//is active by default
bool constraint_is_active = true;
if ((it)->IsDefined(ACTIVE))
constraint_is_active = (it)->Is(ACTIVE);
if (constraint_is_active)
{
UpdateMasterSlaveConstraint(*it, r_current_process_info);
}
}
KRATOS_CATCH("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise::UpdateConstraintsForBuilding failed ..");
}
/**
* @brief this method uses the MasterSlaveConstraints objects in rModelPart to reconstruct the LHS and RHS values
* of the individual AuxilaryGlobalMasterSlaveRelation object. That is the value of Slave as LHS and the T*M+C as RHS value
* @param rMasterSlaveConstraint The MasterSlaveConstraint which is to be updated
*/
void UpdateMasterSlaveConstraint(ModelPart::MasterSlaveConstraintType& rMasterSlaveConstraint, ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
//contributions to the system
LocalSystemMatrixType relation_matrix(0,0);
LocalSystemVectorType constant_vector(0);
EquationIdVectorType slave_equation_ids(0);
EquationIdVectorType master_equation_ids(0);
//get the equation Ids of the constraint
rMasterSlaveConstraint.EquationIdVector(slave_equation_ids, master_equation_ids, rCurrentProcessInfo);
//calculate constraint's T and b matrices
rMasterSlaveConstraint.CalculateLocalSystem(relation_matrix, constant_vector, rCurrentProcessInfo);
// For calculating the constant
MasterSlaveConstraintType::DofPointerVectorType slave_dofs_vector;
MasterSlaveConstraintType::DofPointerVectorType master_dofs_vector;
rMasterSlaveConstraint.GetDofList(slave_dofs_vector, master_dofs_vector, rCurrentProcessInfo);
int slave_index = 0;
for (auto &slave_dof : slave_dofs_vector)
{
double slave_value_calc = 0.0;
for (IndexType master_index = 0; master_index < master_dofs_vector.size(); master_index++)
{
slave_value_calc += master_dofs_vector[master_index]->GetSolutionStepValue() * relation_matrix(slave_index, master_index);
}
slave_value_calc += constant_vector[slave_index];
auto global_constraint = mGlobalMasterSlaveConstraints.find(slave_dof->EquationId());
global_constraint->second->SetLeftHandSide( slave_dof->GetSolutionStepValue() );
global_constraint->second->UpdateRightHandSide(slave_value_calc);
slave_index++;
}
KRATOS_CATCH("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise::UpdateMasterSlaveConstraint failed ..");
}
/**
* @brief This method reconstructs the slave solution after Solving.
* @param rModelPart Reference to the ModelPart containing the problem.
* @param A System matrix
* @param Dx Vector of results (variations on nodal variables)
* @param b RHS vector (residual)
*/
void ReconstructSlaveSolutionAfterSolve(
ModelPart& rModelPart,
TSystemMatrixType& rA,
TSystemVectorType& rDx,
TSystemVectorType& rb)
{
KRATOS_TRY
const int number_of_constraints = static_cast<int>(mGlobalMasterSlaveConstraints.size());
// Getting the beginning iterator
const GlobalMasterSlaveRelationContainerType::iterator constraints_begin = mGlobalMasterSlaveConstraints.begin();
//contributions to the system
VectorType master_weights_vector;
double constant = 0.0;
IndexType slave_equation_id = 0;
EquationIdVectorType master_equation_ids = EquationIdVectorType(0);
#pragma omp parallel for schedule(guided, 512) firstprivate(slave_equation_id, master_equation_ids, master_weights_vector, constant)
for (int i_constraints = 0; i_constraints < number_of_constraints; i_constraints++)
{
//GlobalMasterSlaveRelationContainerType::iterator it = constraints_begin + i_constraints;
GlobalMasterSlaveRelationContainerType::iterator it = constraints_begin;
std::advance(it, i_constraints);
double slave_dx_value = 0.0;
//get the equation Ids of the constraint
(it->second)->EquationIdsVector(slave_equation_id, master_equation_ids);
//calculate constraint's T and b matrices
(it->second)->CalculateLocalSystem(master_weights_vector, constant);
int master_index = 0;
for (auto &master_equation_id : master_equation_ids)
{
slave_dx_value += TSparseSpace::GetValue(rDx, master_equation_id) * master_weights_vector(master_index);
master_index++;
}
slave_dx_value += constant;
rDx[slave_equation_id] = slave_dx_value; // this access is always unique for an object so no need of special care for openmp
}
KRATOS_CATCH("ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise::ReconstructSlaveSolutionAfterSolve failed ..");
}
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class ResidualBasedBlockBuilderAndSolverWithConstraintsElementWise */
///@}
///@name Type Definitions
///@{
///@}
} /* namespace Kratos.*/
#endif /* KRATOS_RESIDUAL_BASED_BLOCK_BUILDER_AND_SOLVER defined */
|
GB_unop__minv_bool_bool.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__minv_bool_bool
// op(A') function: GB_unop_tran__minv_bool_bool
// C type: bool
// A type: bool
// cast: ;
// unaryop: cij = true
#define GB_ATYPE \
bool
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
;
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = true ;
// casting
#define GB_CAST(z, aij) \
; ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
; ; \
/* Cx [pC] = op (cast (aij)) */ \
; ; \
Cx [pC] = true ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__minv_bool_bool
(
bool *Cx, // Cx and Ax may be aliased
const bool *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (bool), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
; ;
; ;
Cx [p] = true ;
}
#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 ;
; ;
; ;
Cx [p] = true ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__minv_bool_bool
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unaryop__identity_int64_int32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__identity_int64_int32
// op(A') function: GB_tran__identity_int64_int32
// C type: int64_t
// A type: int32_t
// cast: int64_t cij = (int64_t) aij
// unaryop: cij = aij
#define GB_ATYPE \
int32_t
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CASTING(z, x) \
int64_t z = (int64_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT64 || GxB_NO_INT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__identity_int64_int32
(
int64_t *restrict Cx,
const int32_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__identity_int64_int32
(
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
|
tanh_kernel_arm.c | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2020, OPEN AI LAB
* Author: haitao@openailab.com
*/
#include "math.h"
#include <arm_neon.h>
#include "tanh_kernel_arm.h"
#define T_MAX(a, b) ((a) > (b) ? (a) : (b))
#define T_MIN(a, b) ((a) < (b) ? (a) : (b))
static inline float fast_exp(float x)
{
union
{
uint32_t i;
float f;
} v;
v.i = (1 << 23) * (1.4426950409 * x + 126.93490512f);
return v.f;
}
static float exp10_f32(float x)
{
x = 1.0 + x * 0.0009765625f;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
x *= x;
return x;
}
/*
exp(x) = lim(1+x/n)^n // n=10
*/
static inline float32x4_t vexpq10_f32(float32x4_t x)
{
x = vmlaq_n_f32(vdupq_n_f32(1.0f), x, 0.0009765625f); // n = 10
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
x = vmulq_f32(x, x);
return x;
}
static void tanh_kernel(int i, int id, void* data, const float* input, float* output)
{
int step = (( int* )data)[0];
float32x4_t min = vdupq_n_f32(-30.0f);
float32x4_t max = vdupq_n_f32(30.0f);
const float* cur_input = input + id * step;
float* cur_output = output + id * step;
for (int i = 0; i < (step & -4); i += 4)
{
float32x4_t _input = vld1q_f32(cur_input);
_input = vmaxq_f32(_input, min);
_input = vminq_f32(_input, max);
/// float32x4_t positive_exp = vexpq10_f32(_input);
/// float32x4_t negative_exp = vexpq10_f32(vmulq_n_f32(_input, -1.0f));
float32x4_t denominator = vaddq_f32(vexpq10_f32(_input), vexpq10_f32(vmulq_n_f32(_input, -1.0f)));
float32x4_t numerator = vsubq_f32(vexpq10_f32(_input), vexpq10_f32(vmulq_n_f32(_input, -1.0f)));
float32x4_t tmp_recip = vrecpeq_f32(denominator);
tmp_recip = vmulq_f32(vrecpsq_f32(denominator, tmp_recip), tmp_recip);
tmp_recip = vmulq_f32(vrecpsq_f32(denominator, tmp_recip), tmp_recip);
float32x4_t out = vmulq_f32(numerator, tmp_recip);
vst1q_f32(cur_output, out);
cur_input += 4;
cur_output += 4;
}
for (int i = step & ~3; i < step; i++)
{
float tmp = *input++;
tmp = T_MIN(tmp, 30.0f);
tmp = T_MAX(tmp, -30.0f);
*cur_output++ = (exp10_f32(tmp) - exp10_f32(-tmp)) / (exp10_f32(tmp) + exp10_f32(-tmp));
}
}
int tanh_run(struct ir_tensor* output_tensor, struct ir_tensor* input_tensor, int num_thread)
{
float* data = ( float* )input_tensor->data;
float* out_data = ( float* )output_tensor->data;
int chan_num = (input_tensor->dims[0]) * (input_tensor->dims[1]);
int chan_size = (input_tensor->dims[2]) * (input_tensor->dims[3]);
#pragma omp parallel for num_threads(num_thread)
for (int i = 0; i < chan_num; i++)
{
int offset = i * chan_size;
tanh_kernel(0, 0, &chan_size, data + offset, out_data + offset);
}
return 0;
}
|
NeighborhoodGraph.h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#ifndef _SPTAG_COMMON_NG_H_
#define _SPTAG_COMMON_NG_H_
#include "../VectorIndex.h"
#include "CommonUtils.h"
#include "Dataset.h"
#include "FineGrainedLock.h"
#include "QueryResultSet.h"
#include <chrono>
#if defined(GPU)
#include <cuda.h>
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
#include <typeinfo>
#include <cuda_fp16.h>
#include "inc/Core/Common/cuda/KNN.hxx"
#include "inc/Core/Common/cuda/params.h"
#endif
namespace SPTAG
{
namespace COMMON
{
class NeighborhoodGraph
{
public:
NeighborhoodGraph(): m_iTPTNumber(32),
m_iTPTLeafSize(2000),
m_iSamples(1000),
m_numTopDimensionTPTSplit(5),
m_iNeighborhoodSize(32),
m_iNeighborhoodScale(2),
m_iCEFScale(2),
m_iRefineIter(2),
m_iCEF(1000),
m_iAddCEF(500),
m_iMaxCheckForRefineGraph(10000),
m_iGPUGraphType(2),
m_iGPURefineSteps(0),
m_iGPURefineDepth(2),
m_iGPULeafSize(500),
m_iGPUBatches(1),
m_iGPUNum(0)
{}
~NeighborhoodGraph() {}
virtual void InsertNeighbors(VectorIndex* index, const SizeType node, SizeType insertNode, float insertDist) = 0;
virtual void RebuildNeighbors(VectorIndex* index, const SizeType node, SizeType* nodes, const BasicResult* queryResults, const int numResults) = 0;
virtual float GraphAccuracyEstimation(VectorIndex* index, const SizeType samples, const std::unordered_map<SizeType, SizeType>* idmap = nullptr)
{
DimensionType* correct = new DimensionType[samples];
#pragma omp parallel for schedule(dynamic)
for (SizeType i = 0; i < samples; i++)
{
SizeType x = COMMON::Utils::rand(m_iGraphSize);
//int x = i;
COMMON::QueryResultSet<void> query(nullptr, m_iCEF);
for (SizeType y = 0; y < m_iGraphSize; y++)
{
if ((idmap != nullptr && idmap->find(y) != idmap->end())) continue;
float dist = index->ComputeDistance(index->GetSample(x), index->GetSample(y));
query.AddPoint(y, dist);
}
query.SortResult();
SizeType * exact_rng = new SizeType[m_iNeighborhoodSize];
RebuildNeighbors(index, x, exact_rng, query.GetResults(), m_iCEF);
correct[i] = 0;
for (DimensionType j = 0; j < m_iNeighborhoodSize; j++) {
if (exact_rng[j] == -1) {
correct[i] += m_iNeighborhoodSize - j;
break;
}
for (DimensionType k = 0; k < m_iNeighborhoodSize; k++)
if ((m_pNeighborhoodGraph)[x][k] == exact_rng[j]) {
correct[i]++;
break;
}
}
delete[] exact_rng;
}
float acc = 0;
for (SizeType i = 0; i < samples; i++) acc += float(correct[i]);
acc = acc / samples / m_iNeighborhoodSize;
delete[] correct;
return acc;
}
#if defined(GPU)
template <typename T>
void BuildInitKNNGraph(VectorIndex* index, const std::unordered_map<SizeType, SizeType>* idmap)
{
SizeType initSize;
SPTAG::Helper::Convert::ConvertStringTo(index->GetParameter("NumberOfInitialDynamicPivots").c_str(), initSize);
// Build the entire RNG graph, both builds the KNN and refines it to RNG
buildGraph<T>(index, m_iGraphSize, m_iNeighborhoodSize, m_iTPTNumber, (int*)m_pNeighborhoodGraph[0], m_iGPURefineSteps, m_iGPURefineDepth, m_iGPUGraphType, m_iGPULeafSize, initSize, m_iGPUBatches, m_iGPUNum);
if (idmap != nullptr) {
std::unordered_map<SizeType, SizeType>::const_iterator iter;
for (SizeType i = 0; i < m_iGraphSize; i++) {
for (DimensionType j = 0; j < m_iNeighborhoodSize; j++) {
if ((iter = idmap->find(m_pNeighborhoodGraph[i][j])) != idmap->end())
m_pNeighborhoodGraph[i][j] = iter->second;
}
}
}
}
#else
template <typename T>
void PartitionByTptree(VectorIndex* index, std::vector<SizeType>& indices, const SizeType first, const SizeType last,
std::vector<std::pair<SizeType, SizeType>> & leaves)
{
if (last - first <= m_iTPTLeafSize)
{
leaves.emplace_back(first, last);
}
else
{
std::vector<float> Mean(index->GetFeatureDim(), 0);
int iIteration = 100;
SizeType end = min(first + m_iSamples, last);
SizeType count = end - first + 1;
// calculate the mean of each dimension
for (SizeType j = first; j <= end; j++)
{
const T* v = (const T*)index->GetSample(indices[j]);
for (DimensionType k = 0; k < index->GetFeatureDim(); k++)
{
Mean[k] += v[k];
}
}
for (DimensionType k = 0; k < index->GetFeatureDim(); k++)
{
Mean[k] /= count;
}
std::vector<BasicResult> Variance;
Variance.reserve(index->GetFeatureDim());
for (DimensionType j = 0; j < index->GetFeatureDim(); j++)
{
Variance.emplace_back(j, 0.0f);
}
// calculate the variance of each dimension
for (SizeType j = first; j <= end; j++)
{
const T* v = (const T*)index->GetSample(indices[j]);
for (DimensionType k = 0; k < index->GetFeatureDim(); k++)
{
float dist = v[k] - Mean[k];
Variance[k].Dist += dist*dist;
}
}
std::sort(Variance.begin(), Variance.end(), COMMON::Compare);
std::vector<SizeType> indexs(m_numTopDimensionTPTSplit);
std::vector<float> weight(m_numTopDimensionTPTSplit), bestweight(m_numTopDimensionTPTSplit);
float bestvariance = Variance[index->GetFeatureDim() - 1].Dist;
for (int i = 0; i < m_numTopDimensionTPTSplit; i++)
{
indexs[i] = Variance[index->GetFeatureDim() - 1 - i].VID;
bestweight[i] = 0;
}
bestweight[0] = 1;
float bestmean = Mean[indexs[0]];
std::vector<float> Val(count);
for (int i = 0; i < iIteration; i++)
{
float sumweight = 0;
for (int j = 0; j < m_numTopDimensionTPTSplit; j++)
{
weight[j] = float(rand() % 10000) / 5000.0f - 1.0f;
sumweight += weight[j] * weight[j];
}
sumweight = sqrt(sumweight);
for (int j = 0; j < m_numTopDimensionTPTSplit; j++)
{
weight[j] /= sumweight;
}
float mean = 0;
for (SizeType j = 0; j < count; j++)
{
Val[j] = 0;
const T* v = (const T*)index->GetSample(indices[first + j]);
for (int k = 0; k < m_numTopDimensionTPTSplit; k++)
{
Val[j] += weight[k] * v[indexs[k]];
}
mean += Val[j];
}
mean /= count;
float var = 0;
for (SizeType j = 0; j < count; j++)
{
float dist = Val[j] - mean;
var += dist * dist;
}
if (var > bestvariance)
{
bestvariance = var;
bestmean = mean;
for (int j = 0; j < m_numTopDimensionTPTSplit; j++)
{
bestweight[j] = weight[j];
}
}
}
SizeType i = first;
SizeType j = last;
// decide which child one point belongs
while (i <= j)
{
float val = 0;
const T* v = (const T*)index->GetSample(indices[i]);
for (int k = 0; k < m_numTopDimensionTPTSplit; k++)
{
val += bestweight[k] * v[indexs[k]];
}
if (val < bestmean)
{
i++;
}
else
{
std::swap(indices[i], indices[j]);
j--;
}
}
// if all the points in the node are equal,equally split the node into 2
if ((i == first) || (i == last + 1))
{
i = (first + last + 1) / 2;
}
Mean.clear();
Variance.clear();
Val.clear();
indexs.clear();
weight.clear();
bestweight.clear();
PartitionByTptree<T>(index, indices, first, i - 1, leaves);
PartitionByTptree<T>(index, indices, i, last, leaves);
}
}
template <typename T>
void BuildInitKNNGraph(VectorIndex* index, const std::unordered_map<SizeType, SizeType>* idmap)
{
COMMON::Dataset<float> NeighborhoodDists(m_iGraphSize, m_iNeighborhoodSize);
std::vector<std::vector<SizeType>> TptreeDataIndices(m_iTPTNumber, std::vector<SizeType>(m_iGraphSize));
std::vector<std::vector<std::pair<SizeType, SizeType>>> TptreeLeafNodes(m_iTPTNumber, std::vector<std::pair<SizeType, SizeType>>());
for (SizeType i = 0; i < m_iGraphSize; i++)
for (DimensionType j = 0; j < m_iNeighborhoodSize; j++)
(NeighborhoodDists)[i][j] = MaxDist;
auto t1 = std::chrono::high_resolution_clock::now();
LOG(Helper::LogLevel::LL_Info, "Parallel TpTree Partition begin\n");
#pragma omp parallel for schedule(dynamic)
for (int i = 0; i < m_iTPTNumber; i++)
{
Sleep(i * 100); std::srand(clock());
for (SizeType j = 0; j < m_iGraphSize; j++) TptreeDataIndices[i][j] = j;
std::random_shuffle(TptreeDataIndices[i].begin(), TptreeDataIndices[i].end());
PartitionByTptree<T>(index, TptreeDataIndices[i], 0, m_iGraphSize - 1, TptreeLeafNodes[i]);
LOG(Helper::LogLevel::LL_Info, "Finish Getting Leaves for Tree %d\n", i);
}
LOG(Helper::LogLevel::LL_Info, "Parallel TpTree Partition done\n");
auto t2 = std::chrono::high_resolution_clock::now();
LOG(Helper::LogLevel::LL_Info, "Build TPTree time (s): %lld\n", std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count());
for (int i = 0; i < m_iTPTNumber; i++)
{
#pragma omp parallel for schedule(dynamic)
for (SizeType j = 0; j < (SizeType)TptreeLeafNodes[i].size(); j++)
{
SizeType start_index = TptreeLeafNodes[i][j].first;
SizeType end_index = TptreeLeafNodes[i][j].second;
if ((j * 5) % TptreeLeafNodes[i].size() == 0) LOG(Helper::LogLevel::LL_Info, "Processing Tree %d %d%%\n", i, static_cast<int>(j * 1.0 / TptreeLeafNodes[i].size() * 100));
for (SizeType x = start_index; x < end_index; x++)
{
for (SizeType y = x + 1; y <= end_index; y++)
{
SizeType p1 = TptreeDataIndices[i][x];
SizeType p2 = TptreeDataIndices[i][y];
float dist = index->ComputeDistance(index->GetSample(p1), index->GetSample(p2));
if (idmap != nullptr) {
p1 = (idmap->find(p1) == idmap->end()) ? p1 : idmap->at(p1);
p2 = (idmap->find(p2) == idmap->end()) ? p2 : idmap->at(p2);
}
COMMON::Utils::AddNeighbor(p2, dist, (m_pNeighborhoodGraph)[p1], (NeighborhoodDists)[p1], m_iNeighborhoodSize);
COMMON::Utils::AddNeighbor(p1, dist, (m_pNeighborhoodGraph)[p2], (NeighborhoodDists)[p2], m_iNeighborhoodSize);
}
}
}
TptreeDataIndices[i].clear();
TptreeLeafNodes[i].clear();
}
TptreeDataIndices.clear();
TptreeLeafNodes.clear();
auto t3 = std::chrono::high_resolution_clock::now();
LOG(Helper::LogLevel::LL_Info, "Process TPTree time (s): %lld\n", std::chrono::duration_cast<std::chrono::seconds>(t3 - t2).count());
}
#endif
template <typename T>
void BuildGraph(VectorIndex* index, const std::unordered_map<SizeType, SizeType>* idmap = nullptr)
{
LOG(Helper::LogLevel::LL_Info, "build RNG graph!\n");
m_iGraphSize = index->GetNumSamples();
m_iNeighborhoodSize = m_iNeighborhoodSize * m_iNeighborhoodScale;
m_pNeighborhoodGraph.Initialize(m_iGraphSize, m_iNeighborhoodSize);
if (m_iGraphSize < 1000) {
RefineGraph<T>(index, idmap);
LOG(Helper::LogLevel::LL_Info, "Build RNG Graph end!\n");
return;
}
auto t1 = std::chrono::high_resolution_clock::now();
BuildInitKNNGraph<T>(index, idmap);
auto t2 = std::chrono::high_resolution_clock::now();
LOG(Helper::LogLevel::LL_Info, "BuildInitKNNGraph time (s): %lld\n", std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count());
RefineGraph<T>(index, idmap);
if (idmap != nullptr) {
for (auto iter = idmap->begin(); iter != idmap->end(); iter++)
if (iter->first < 0)
{
m_pNeighborhoodGraph[-1 - iter->first][m_iNeighborhoodSize - 1] = -2 - iter->second;
}
}
auto t3 = std::chrono::high_resolution_clock::now();
LOG(Helper::LogLevel::LL_Info, "BuildGraph time (s): %lld\n", std::chrono::duration_cast<std::chrono::seconds>(t3 - t1).count());
}
template <typename T>
void RefineGraph(VectorIndex* index, const std::unordered_map<SizeType, SizeType>* idmap = nullptr)
{
for (int iter = 0; iter < m_iRefineIter - 1; iter++)
{
auto t1 = std::chrono::high_resolution_clock::now();
#pragma omp parallel for schedule(dynamic)
for (SizeType i = 0; i < m_iGraphSize; i++)
{
RefineNode<T>(index, i, false, false, m_iCEF * m_iCEFScale);
if ((i * 5) % m_iGraphSize == 0) LOG(Helper::LogLevel::LL_Info, "Refine %d %d%%\n", iter, static_cast<int>(i * 1.0 / m_iGraphSize * 100));
}
auto t2 = std::chrono::high_resolution_clock::now();
LOG(Helper::LogLevel::LL_Info, "Refine RNG time (s): %lld Graph Acc: %f\n", std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count(), GraphAccuracyEstimation(index, 100, idmap));
}
m_iNeighborhoodSize /= m_iNeighborhoodScale;
if (m_iRefineIter > 0) {
auto t1 = std::chrono::high_resolution_clock::now();
#pragma omp parallel for schedule(dynamic)
for (SizeType i = 0; i < m_iGraphSize; i++)
{
RefineNode<T>(index, i, false, false, m_iCEF);
if ((i * 5) % m_iGraphSize == 0) LOG(Helper::LogLevel::LL_Info, "Refine %d %d%%\n", m_iRefineIter - 1, static_cast<int>(i * 1.0 / m_iGraphSize * 100));
}
auto t2 = std::chrono::high_resolution_clock::now();
LOG(Helper::LogLevel::LL_Info, "Refine RNG time (s): %lld Graph Acc: %f\n", std::chrono::duration_cast<std::chrono::seconds>(t2 - t1).count(), GraphAccuracyEstimation(index, 100, idmap));
}
}
template <typename T>
ErrorCode RefineGraph(VectorIndex* index, std::vector<SizeType>& indices, std::vector<SizeType>& reverseIndices,
std::shared_ptr<Helper::DiskPriorityIO> output, NeighborhoodGraph* newGraph, const std::unordered_map<SizeType, SizeType>* idmap = nullptr)
{
std::shared_ptr<NeighborhoodGraph> tmp;
if (newGraph == nullptr) {
tmp = NeighborhoodGraph::CreateInstance(Type());
newGraph = tmp.get();
}
SizeType R = (SizeType)indices.size();
newGraph->m_pNeighborhoodGraph.Initialize(R, m_iNeighborhoodSize);
newGraph->m_iGraphSize = R;
newGraph->m_iNeighborhoodSize = m_iNeighborhoodSize;
#pragma omp parallel for schedule(dynamic)
for (SizeType i = 0; i < R; i++)
{
if ((i * 5) % R == 0) LOG(Helper::LogLevel::LL_Info, "Refine %d%%\n", static_cast<int>(i * 1.0 / R * 100));
SizeType* outnodes = newGraph->m_pNeighborhoodGraph[i];
COMMON::QueryResultSet<T> query((const T*)index->GetSample(indices[i]), m_iCEF + 1);
index->RefineSearchIndex(query, false);
RebuildNeighbors(index, indices[i], outnodes, query.GetResults(), m_iCEF + 1);
std::unordered_map<SizeType, SizeType>::const_iterator iter;
for (DimensionType j = 0; j < m_iNeighborhoodSize; j++)
{
if (outnodes[j] >= 0 && outnodes[j] < reverseIndices.size()) outnodes[j] = reverseIndices[outnodes[j]];
if (idmap != nullptr && (iter = idmap->find(outnodes[j])) != idmap->end()) outnodes[j] = iter->second;
}
if (idmap != nullptr && (iter = idmap->find(-1 - i)) != idmap->end())
outnodes[m_iNeighborhoodSize - 1] = -2 - iter->second;
}
if (output != nullptr) newGraph->SaveGraph(output);
return ErrorCode::Success;
}
template <typename T>
void RefineNode(VectorIndex* index, const SizeType node, bool updateNeighbors, bool searchDeleted, int CEF)
{
COMMON::QueryResultSet<T> query((const T*)index->GetSample(node), CEF + 1);
index->RefineSearchIndex(query, searchDeleted);
RebuildNeighbors(index, node, m_pNeighborhoodGraph[node], query.GetResults(), CEF + 1);
if (updateNeighbors) {
// update neighbors
for (int j = 0; j <= CEF; j++)
{
BasicResult* item = query.GetResult(j);
if (item->VID < 0) break;
if (item->VID == node) continue;
InsertNeighbors(index, item->VID, node, item->Dist);
}
}
}
inline std::uint64_t BufferSize() const
{
return m_pNeighborhoodGraph.BufferSize();
}
ErrorCode LoadGraph(std::shared_ptr<Helper::DiskPriorityIO> input)
{
ErrorCode ret = ErrorCode::Success;
if ((ret = m_pNeighborhoodGraph.Load(input)) != ErrorCode::Success) return ret;
m_iGraphSize = m_pNeighborhoodGraph.R();
m_iNeighborhoodSize = m_pNeighborhoodGraph.C();
return ret;
}
ErrorCode LoadGraph(std::string sGraphFilename)
{
ErrorCode ret = ErrorCode::Success;
if ((ret = m_pNeighborhoodGraph.Load(sGraphFilename)) != ErrorCode::Success) return ret;
m_iGraphSize = m_pNeighborhoodGraph.R();
m_iNeighborhoodSize = m_pNeighborhoodGraph.C();
return ret;
}
ErrorCode LoadGraph(char* pGraphMemFile)
{
ErrorCode ret = ErrorCode::Success;
if ((ret = m_pNeighborhoodGraph.Load(pGraphMemFile)) != ErrorCode::Success) return ret;
m_iGraphSize = m_pNeighborhoodGraph.R();
m_iNeighborhoodSize = m_pNeighborhoodGraph.C();
return ErrorCode::Success;
}
ErrorCode SaveGraph(std::string sGraphFilename) const
{
return m_pNeighborhoodGraph.Save(sGraphFilename);
}
ErrorCode SaveGraph(std::shared_ptr<Helper::DiskPriorityIO> output) const
{
return m_pNeighborhoodGraph.Save(output);
}
inline ErrorCode AddBatch(SizeType num)
{
ErrorCode ret = m_pNeighborhoodGraph.AddBatch(num);
if (ret != ErrorCode::Success) return ret;
m_iGraphSize += num;
return ErrorCode::Success;
}
inline SizeType* operator[](SizeType index) { return m_pNeighborhoodGraph[index]; }
inline const SizeType* operator[](SizeType index) const { return m_pNeighborhoodGraph[index]; }
void Update(SizeType row, DimensionType col, SizeType val) {
std::lock_guard<std::mutex> lock(m_dataUpdateLock[row]);
m_pNeighborhoodGraph[row][col] = val;
}
inline void SetR(SizeType rows) {
m_pNeighborhoodGraph.SetR(rows);
m_iGraphSize = rows;
}
inline SizeType R() const { return m_iGraphSize; }
inline std::string Type() const { return m_pNeighborhoodGraph.Name(); }
static std::shared_ptr<NeighborhoodGraph> CreateInstance(std::string type);
protected:
// Graph structure
SizeType m_iGraphSize;
COMMON::Dataset<SizeType> m_pNeighborhoodGraph;
FineGrainedLock m_dataUpdateLock;
public:
int m_iTPTNumber, m_iTPTLeafSize, m_iSamples, m_numTopDimensionTPTSplit;
DimensionType m_iNeighborhoodSize;
int m_iNeighborhoodScale, m_iCEFScale, m_iRefineIter, m_iCEF, m_iAddCEF, m_iMaxCheckForRefineGraph, m_iGPUGraphType, m_iGPURefineSteps, m_iGPURefineDepth, m_iGPULeafSize, m_iGPUBatches, m_iGPUNum;
};
}
}
#endif
|
rose_output_dep2.c | // an example of output dependence preventing parallelization
// loop carried vs. non-loop carried output dependence!
#include "omp.h"
void foo()
{
int i;
int x;
int y;
#pragma omp parallel for private (x,y,i)
for (i = 0; i <= 99; i += 1) {
x = i;
y = i;
y = i + 1;
}
}
/*
output dependence carryLevel should be 0? carry level is wrong!!
dep SgExprStatement:x = i;
SgExprStatement:x = i;
1*1 SCALAR_DEP; commonlevel = 1 CarryLevel = 1
SgVarRefExp:x@8:6->SgVarRefExp:x@8:6 == 0;||::
output dependence carryLevel should be 0? carry level is wrong!!
dep SgExprStatement:y = i; SgExprStatement:y = i; 1*1 SCALAR_DEP; commonlevel = 1 CarryLevel = 1 SgVarRefExp:y@9:6->SgVarRefExp:y@9:6 == 0;||::
output dependence carryLevel should be 0? carry level is wrong!!
dep SgExprStatement:y =(i + 1); SgExprStatement:y =(i + 1); 1*1 SCALAR_DEP; commonlevel = 1 CarryLevel = 1 SgVarRefExp:y@10:6->SgVarRefExp:y@10:6 == 0;||::
//--------------
output dependence: non-loop carried, level =1 is correct
dep SgExprStatement:y = i; SgExprStatement:y =(i + 1); 1*1 SCALAR_DEP; commonlevel = 1 CarryLevel = 1 SgVarRefExp:y@9:6->SgVarRefExp:y@10:6 == 0;||::
output dependence: Carry level =0 means loop carried, also look at line number: 10>9
dep SgExprStatement:y =(i + 1); SgExprStatement:y = i; 1*1 SCALAR_BACK_DEP; commonlevel = 1 CarryLevel = 0 SgVarRefExp:y@10:6->SgVarRefExp:y@9:6 <= -1;||::
*/
|
Example_target_update.2.c | /*
* @@name: target_update.2c
* @@type: C
* @@compilable: yes
* @@linkable: no
* @@expect: success
* @@version: omp_4.0
*/
extern void init(float *, float *, int);
extern int maybe_init_again(float *, int);
extern void output(float *, int);
void vec_mult(float *p, float *v1, float *v2, int N)
{
int i;
init(v1, v2, N);
#pragma omp target data map(to: v1[:N], v2[:N]) map(from: p[0:N])
{
int changed;
#pragma omp target
#pragma omp parallel for
for (i=0; i<N; i++)
p[i] = v1[i] * v2[i];
changed = maybe_init_again(v1, N);
#pragma omp target update if (changed) to(v1[:N])
changed = maybe_init_again(v2, N);
#pragma omp target update if (changed) to(v2[:N])
#pragma omp target
#pragma omp parallel for
for (i=0; i<N; i++)
p[i] = p[i] + (v1[i] * v2[i]);
}
output(p, N);
}
|
stencil.c | /*
Copyright (c) 2013, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Intel Corporation nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/*******************************************************************
NAME: Stencil
PURPOSE: This program tests the efficiency with which a space-invariant,
linear, symmetric filter (stencil) can be applied to a square
grid or image.
USAGE: The program takes as input the linear dimension of the grid,
and the number of iterations on the grid
<progname> <#threads><# iterations> <grid size>
The output consists of diagnostics to make sure the
algorithm worked, and of timing statistics.
FUNCTIONS CALLED:
Other than MPI or standard C functions, the following
functions are used in this program:
wtime()
bail_out()
HISTORY: - Written by Rob Van der Wijngaart, November 2006.
- RvdW, August 2013: Removed unrolling pragmas for clarity;
fixed bug in compuation of width of strip assigned to
each rank;
- RvdW, August 2013: added constant to array "in" at end of
each iteration to force refreshing of neighbor data in
parallel versions
- RvdW, October 2014: introduced 2D domain decomposition
- RvdW, October 2014: removed barrier at start of each iteration
- RvdW, October 2014: replaced single rank/single iteration timing
with global timing of all iterations across all ranks
*********************************************************************************/
#include <par-res-kern_general.h>
#include <par-res-kern_mpiomp.h>
#if DOUBLE
#define DTYPE double
#define MPI_DTYPE MPI_DOUBLE
#define EPSILON 1.e-8
#define COEFX 1.0
#define COEFY 1.0
#define FSTR "%lf"
#else
#define DTYPE float
#define MPI_DTYPE MPI_FLOAT
#define EPSILON 0.0001f
#define COEFX 1.0f
#define COEFY 1.0f
#define FSTR "%f"
#endif
/* define shorthand for indexing multi-dimensional arrays with offsets */
#define INDEXIN(i,j) (i+RADIUS+(j+RADIUS)*(width+2*RADIUS))
/* need to add offset of RADIUS to j to account for ghost points */
#define IN(i,j) in[INDEXIN(i-istart,j-jstart)]
#define INDEXOUT(i,j) (i+(j)*(width))
#define OUT(i,j) out[INDEXOUT(i-istart,j-jstart)]
#define WEIGHT(ii,jj) weight[ii+RADIUS][jj+RADIUS]
int main(int argc, char ** argv) {
int Num_procs; /* number of ranks */
int Num_procsx, Num_procsy; /* number of ranks in each coord direction */
int my_ID; /* MPI rank */
int my_IDx, my_IDy; /* coordinates of rank in rank grid */
int right_nbr; /* global rank of right neighboring tile */
int left_nbr; /* global rank of left neighboring tile */
int top_nbr; /* global rank of top neighboring tile */
int bottom_nbr; /* global rank of bottom neighboring tile */
DTYPE *top_buf_out; /* communication buffer */
DTYPE *top_buf_in; /* " " */
DTYPE *bottom_buf_out; /* " " */
DTYPE *bottom_buf_in; /* " " */
DTYPE *right_buf_out; /* " " */
DTYPE *right_buf_in; /* " " */
DTYPE *left_buf_out; /* " " */
DTYPE *left_buf_in; /* " " */
int root = 0;
int n, width, height;/* linear global and local grid dimension */
long nsquare; /* total number of grid points */
int i, j, ii, jj, kk, it, jt, iter, leftover; /* dummies */
int istart, iend; /* bounds of grid tile assigned to calling rank */
int jstart, jend; /* bounds of grid tile assigned to calling rank */
DTYPE norm, /* L1 norm of solution */
local_norm, /* contribution of calling rank to L1 norm */
reference_norm;
DTYPE f_active_points; /* interior of grid with respect to stencil */
DTYPE flops; /* floating point ops per iteration */
int iterations; /* number of times to run the algorithm */
double local_stencil_time,/* timing parameters */
stencil_time,
avgtime;
int stencil_size; /* number of points in stencil */
int nthread_input, /* thread parameters */
nthread;
DTYPE * RESTRICT in; /* input grid values */
DTYPE * RESTRICT out; /* output grid values */
long total_length_in; /* total required length to store input array */
long total_length_out;/* total required length to store output array */
int error=0; /* error flag */
DTYPE weight[2*RADIUS+1][2*RADIUS+1]; /* weights of points in the stencil */
MPI_Request request[8];
/*******************************************************************************
** Initialize the MPI environment
********************************************************************************/
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_ID);
MPI_Comm_size(MPI_COMM_WORLD, &Num_procs);
/*******************************************************************************
** process, test, and broadcast input parameters
********************************************************************************/
if (my_ID == root) {
printf("Parallel Research Kernels version %s\n", PRKVERSION);
printf("MPI+OPENMP stencil execution on 2D grid\n");
#ifndef STAR
printf("ERROR: Compact stencil not supported\n");
error = 1;
goto ENDOFTESTS;
#endif
if (argc != 4){
printf("Usage: %s <#threads><#iterations> <array dimension> \n",
*argv);
error = 1;
goto ENDOFTESTS;
}
/* Take number of threads to request from command line */
nthread_input = atoi(*++argv);
if ((nthread_input < 1) || (nthread_input > MAX_THREADS)) {
printf("ERROR: Invalid number of threads: %d\n", nthread_input);
error = 1;
goto ENDOFTESTS;
}
iterations = atoi(*++argv);
if (iterations < 1){
printf("ERROR: iterations must be >= 1 : %d \n",iterations);
error = 1;
goto ENDOFTESTS;
}
n = atoi(*++argv);
nsquare = (long) n * (long) n;
if (nsquare < Num_procs){
printf("ERROR: grid size %ld must be at least # ranks: %d\n",
nsquare, Num_procs);
error = 1;
goto ENDOFTESTS;
}
if (RADIUS < 0) {
printf("ERROR: Stencil radius %d should be non-negative\n", RADIUS);
error = 1;
goto ENDOFTESTS;
}
if (2*RADIUS +1 > n) {
printf("ERROR: Stencil radius %d exceeds grid size %d\n", RADIUS, n);
error = 1;
goto ENDOFTESTS;
}
ENDOFTESTS:;
}
bail_out(error);
/* determine best way to create a 2D grid of ranks (closest to square) */
factor(Num_procs, &Num_procsx, &Num_procsy);
my_IDx = my_ID%Num_procsx;
my_IDy = my_ID/Num_procsx;
/* compute neighbors; don't worry about dropping off the edges of the grid */
right_nbr = my_ID+1;
left_nbr = my_ID-1;
top_nbr = my_ID+Num_procsx;
bottom_nbr = my_ID-Num_procsx;
MPI_Bcast(&n, 1, MPI_INT, root, MPI_COMM_WORLD);
MPI_Bcast(&iterations, 1, MPI_INT, root, MPI_COMM_WORLD);
MPI_Bcast(&nthread_input, 1, MPI_INT, root, MPI_COMM_WORLD);
omp_set_num_threads(nthread_input);
if (my_ID == root) {
printf("Number of ranks = %d\n", Num_procs);
printf("Number of threads = %d\n", omp_get_max_threads());
printf("Grid size = %d\n", n);
printf("Radius of stencil = %d\n", RADIUS);
printf("Tiles in x/y-direction = %d/%d\n", Num_procsx, Num_procsy);
printf("Type of stencil = star\n");
#if DOUBLE
printf("Data type = double precision\n");
#else
printf("Data type = single precision\n");
#endif
#if LOOPGEN
printf("Script used to expand stencil loop body\n");
#else
printf("Compact representation of stencil loop body\n");
#endif
printf("Number of iterations = %d\n", iterations);
}
/* compute amount of space required for input and solution arrays */
width = n/Num_procsx;
leftover = n%Num_procsx;
if (my_IDx<leftover) {
istart = (width+1) * my_IDx;
iend = istart + width;
}
else {
istart = (width+1) * leftover + width * (my_IDx-leftover);
iend = istart + width - 1;
}
width = iend - istart + 1;
if (width == 0) {
printf("ERROR: rank %d has no work to do\n", my_ID);
error = 1;
}
bail_out(error);
height = n/Num_procsy;
leftover = n%Num_procsy;
if (my_IDy<leftover) {
jstart = (height+1) * my_IDy;
jend = jstart + height;
}
else {
jstart = (height+1) * leftover + height * (my_IDy-leftover);
jend = jstart + height - 1;
}
height = jend - jstart + 1;
if (height == 0) {
printf("ERROR: rank %d has no work to do\n", my_ID);
error = 1;
}
bail_out(error);
if (width < RADIUS || height < RADIUS) {
printf("ERROR: rank %d has work tile smaller then stencil radius\n",
my_ID);
error = 1;
}
bail_out(error);
total_length_in = (width+2*RADIUS)*(height+2*RADIUS)*sizeof(DTYPE);
if (total_length_in/(height+2*RADIUS) != (width+2*RADIUS)*sizeof(DTYPE)) {
printf("ERROR: Space for %d x %d input array cannot be represented\n",
width+2*RADIUS, height+2*RADIUS);
error = 1;
}
bail_out(error);
total_length_out = width*height*sizeof(DTYPE);
in = (DTYPE *) prk_malloc(total_length_in);
out = (DTYPE *) prk_malloc(total_length_out);
if (!in || !out) {
printf("ERROR: rank %d could not allocate space for input/output array\n",
my_ID);
error = 1;
}
bail_out(error);
/* fill the stencil weights to reflect a discrete divergence operator */
for (jj=-RADIUS; jj<=RADIUS; jj++) for (ii=-RADIUS; ii<=RADIUS; ii++)
WEIGHT(ii,jj) = (DTYPE) 0.0;
stencil_size = 4*RADIUS+1;
for (ii=1; ii<=RADIUS; ii++) {
WEIGHT(0, ii) = WEIGHT( ii,0) = (DTYPE) (1.0/(2.0*ii*RADIUS));
WEIGHT(0,-ii) = WEIGHT(-ii,0) = -(DTYPE) (1.0/(2.0*ii*RADIUS));
}
norm = (DTYPE) 0.0;
f_active_points = (DTYPE) (n-2*RADIUS)*(DTYPE) (n-2*RADIUS);
/* intialize the input and output arrays */
#pragma omp parallel for private (i)
for (j=jstart; j<=jend; j++) for (i=istart; i<=iend; i++) {
IN(i,j) = COEFX*i+COEFY*j;
OUT(i,j) = (DTYPE)0.0;
}
/* allocate communication buffers for halo values */
top_buf_out = (DTYPE *) prk_malloc(4*sizeof(DTYPE)*RADIUS*width);
if (!top_buf_out) {
printf("ERROR: Rank %d could not allocated comm buffers for y-direction\n", my_ID);
error = 1;
}
bail_out(error);
top_buf_in = top_buf_out + RADIUS*width;
bottom_buf_out = top_buf_out + 2*RADIUS*width;
bottom_buf_in = top_buf_out + 3*RADIUS*width;
right_buf_out = (DTYPE *) prk_malloc(4*sizeof(DTYPE)*RADIUS*height);
if (!right_buf_out) {
printf("ERROR: Rank %d could not allocated comm buffers for x-direction\n", my_ID);
error = 1;
}
bail_out(error);
right_buf_in = right_buf_out + RADIUS*height;
left_buf_out = right_buf_out + 2*RADIUS*height;
left_buf_in = right_buf_out + 3*RADIUS*height;
for (iter = 0; iter<=iterations; iter++){
/* start timer after a warmup iteration */
if (iter == 1) {
MPI_Barrier(MPI_COMM_WORLD);
local_stencil_time = wtime();
}
/* need to fetch ghost point data from neighbors in y-direction */
if (my_IDy < Num_procsy-1) {
MPI_Irecv(top_buf_in, RADIUS*width, MPI_DTYPE, top_nbr, 101,
MPI_COMM_WORLD, &(request[1]));
for (kk=0,j=jend-RADIUS+1; j<=jend; j++) for (i=istart; i<=iend; i++) {
top_buf_out[kk++]= IN(i,j);
}
MPI_Isend(top_buf_out, RADIUS*width,MPI_DTYPE, top_nbr, 99,
MPI_COMM_WORLD, &(request[0]));
}
if (my_IDy > 0) {
MPI_Irecv(bottom_buf_in,RADIUS*width, MPI_DTYPE, bottom_nbr, 99,
MPI_COMM_WORLD, &(request[3]));
for (kk=0,j=jstart; j<=jstart+RADIUS-1; j++) for (i=istart; i<=iend; i++) {
bottom_buf_out[kk++]= IN(i,j);
}
MPI_Isend(bottom_buf_out, RADIUS*width,MPI_DTYPE, bottom_nbr, 101,
MPI_COMM_WORLD, &(request[2]));
}
if (my_IDy < Num_procsy-1) {
MPI_Wait(&(request[0]), MPI_STATUS_IGNORE);
MPI_Wait(&(request[1]), MPI_STATUS_IGNORE);
for (kk=0,j=jend+1; j<=jend+RADIUS; j++) for (i=istart; i<=iend; i++) {
IN(i,j) = top_buf_in[kk++];
}
}
if (my_IDy > 0) {
MPI_Wait(&(request[2]), MPI_STATUS_IGNORE);
MPI_Wait(&(request[3]), MPI_STATUS_IGNORE);
for (kk=0,j=jstart-RADIUS; j<=jstart-1; j++) for (i=istart; i<=iend; i++) {
IN(i,j) = bottom_buf_in[kk++];
}
}
/* need to fetch ghost point data from neighbors in x-direction */
if (my_IDx < Num_procsx-1) {
MPI_Irecv(right_buf_in, RADIUS*height, MPI_DTYPE, right_nbr, 1010,
MPI_COMM_WORLD, &(request[1+4]));
for (kk=0,j=jstart; j<=jend; j++) for (i=iend-RADIUS+1; i<=iend; i++) {
right_buf_out[kk++]= IN(i,j);
}
MPI_Isend(right_buf_out, RADIUS*height, MPI_DTYPE, right_nbr, 990,
MPI_COMM_WORLD, &(request[0+4]));
}
if (my_IDx > 0) {
MPI_Irecv(left_buf_in, RADIUS*height, MPI_DTYPE, left_nbr, 990,
MPI_COMM_WORLD, &(request[3+4]));
for (kk=0,j=jstart; j<=jend; j++) for (i=istart; i<=istart+RADIUS-1; i++) {
left_buf_out[kk++]= IN(i,j);
}
MPI_Isend(left_buf_out, RADIUS*height, MPI_DTYPE, left_nbr, 1010,
MPI_COMM_WORLD, &(request[2+4]));
}
if (my_IDx < Num_procsx-1) {
MPI_Wait(&(request[0+4]), MPI_STATUS_IGNORE);
MPI_Wait(&(request[1+4]), MPI_STATUS_IGNORE);
for (kk=0,j=jstart; j<=jend; j++) for (i=iend+1; i<=iend+RADIUS; i++) {
IN(i,j) = right_buf_in[kk++];
}
}
if (my_IDx > 0) {
MPI_Wait(&(request[2+4]), MPI_STATUS_IGNORE);
MPI_Wait(&(request[3+4]), MPI_STATUS_IGNORE);
for (kk=0,j=jstart; j<=jend; j++) for (i=istart-RADIUS; i<=istart-1; i++) {
IN(i,j) = left_buf_in[kk++];
}
}
/* Apply the stencil operator */
#pragma omp parallel for private (i, j, ii, jj)
for (j=MAX(jstart,RADIUS); j<=MIN(n-RADIUS-1,jend); j++) {
for (i=MAX(istart,RADIUS); i<=MIN(n-RADIUS-1,iend); i++) {
#if LOOPGEN
#include "loop_body_star.incl"
#else
for (jj=-RADIUS; jj<=RADIUS; jj++) OUT(i,j) += WEIGHT(0,jj)*IN(i,j+jj);
for (ii=-RADIUS; ii<0; ii++) OUT(i,j) += WEIGHT(ii,0)*IN(i+ii,j);
for (ii=1; ii<=RADIUS; ii++) OUT(i,j) += WEIGHT(ii,0)*IN(i+ii,j);
#endif
}
}
#pragma omp parallel for private (i)
/* add constant to solution to force refresh of neighbor data, if any */
for (j=jstart; j<=jend; j++) for (i=istart; i<=iend; i++) IN(i,j)+= 1.0;
}
local_stencil_time = wtime() - local_stencil_time;
MPI_Reduce(&local_stencil_time, &stencil_time, 1, MPI_DOUBLE, MPI_MAX, root,
MPI_COMM_WORLD);
/* compute L1 norm in parallel */
local_norm = (DTYPE) 0.0;
#pragma omp parallel for reduction(+:local_norm) private (i)
for (j=MAX(jstart,RADIUS); j<=MIN(n-RADIUS-1,jend); j++) {
for (i=MAX(istart,RADIUS); i<=MIN(n-RADIUS-1,iend); i++) {
local_norm += (DTYPE)ABS(OUT(i,j));
}
}
MPI_Reduce(&local_norm, &norm, 1, MPI_DTYPE, MPI_SUM, root, MPI_COMM_WORLD);
/*******************************************************************************
** Analyze and output results.
********************************************************************************/
/* verify correctness */
if (my_ID == root) {
norm /= f_active_points;
if (RADIUS > 0) {
reference_norm = (DTYPE) (iterations+1) * (COEFX + COEFY);
}
else {
reference_norm = (DTYPE) 0.0;
}
if (ABS(norm-reference_norm) > EPSILON) {
printf("ERROR: L1 norm = "FSTR", Reference L1 norm = "FSTR"\n",
norm, reference_norm);
error = 1;
}
else {
printf("Solution validates\n");
#if VERBOSE
printf("Reference L1 norm = "FSTR", L1 norm = "FSTR"\n",
reference_norm, norm);
#endif
}
}
bail_out(error);
if (my_ID == root) {
/* flops/stencil: 2 flops (fma) for each point in the stencil,
plus one flop for the update of the input of the array */
flops = (DTYPE) (2*stencil_size+1) * f_active_points;
avgtime = stencil_time/iterations;
printf("Rate (MFlops/s): "FSTR" Avg time (s): %lf\n",
1.0E-06 * flops/avgtime, avgtime);
}
MPI_Finalize();
exit(EXIT_SUCCESS);
}
|
GB_unop__abs_uint8_uint8.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__abs_uint8_uint8)
// op(A') function: GB (_unop_tran__abs_uint8_uint8)
// C type: uint8_t
// A type: uint8_t
// cast: uint8_t cij = aij
// unaryop: cij = aij
#define GB_ATYPE \
uint8_t
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint8_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint8_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint8_t z = aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_UINT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__abs_uint8_uint8)
(
uint8_t *Cx, // Cx and Ax may be aliased
const uint8_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++)
{
uint8_t aij = Ax [p] ;
uint8_t z = aij ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint8_t aij = Ax [p] ;
uint8_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__abs_uint8_uint8)
(
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
|
Sema.h | //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the Sema class, which performs semantic analysis and
// builds ASTs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMA_H
#define LLVM_CLANG_SEMA_SEMA_H
#include "clang/AST/ASTConcept.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Availability.h"
#include "clang/AST/ComparisonCategories.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/LocInfoType.h"
#include "clang/AST/MangleNumberingContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/TypeLoc.h"
#include "clang/APINotes/APINotesManager.h"
#include "clang/AST/TypeOrdering.h"
#include "clang/Basic/BitmaskEnum.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/PragmaKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TemplateKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/CleanupInfo.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <deque>
#include <functional>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
namespace llvm {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
struct InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class ParsedAttr;
class BindingDecl;
class BlockDecl;
class CapturedDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXBindTemporaryExpr;
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDeleteExpr;
class CXXDestructorDecl;
class CXXFieldCollector;
class CXXMemberCallExpr;
class CXXMethodDecl;
class CXXScopeSpec;
class CXXTemporary;
class CXXTryStmt;
class CallExpr;
class ClassTemplateDecl;
class ClassTemplatePartialSpecializationDecl;
class ClassTemplateSpecializationDecl;
class VarTemplatePartialSpecializationDecl;
class CodeCompleteConsumer;
class CodeCompletionAllocator;
class CodeCompletionTUInfo;
class CodeCompletionResult;
class CoroutineBodyStmt;
class Decl;
class DeclAccessPair;
class DeclContext;
class DeclRefExpr;
class DeclaratorDecl;
class DeducedTemplateArgument;
class DependentDiagnostic;
class DesignatedInitExpr;
class Designation;
class EnableIfAttr;
class EnumConstantDecl;
class Expr;
class ExtVectorType;
class FormatAttr;
class FriendDecl;
class FunctionDecl;
class FunctionProtoType;
class FunctionTemplateDecl;
class ImplicitConversionSequence;
typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
class InitListExpr;
class InitializationKind;
class InitializationSequence;
class InitializedEntity;
class IntegerLiteral;
class LabelStmt;
class LambdaExpr;
class LangOptions;
class LocalInstantiationScope;
class LookupResult;
class MacroInfo;
typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
class ModuleLoader;
class MultiLevelTemplateArgumentList;
class NamedDecl;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCCompatibleAliasDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
template <class T> class ObjCList;
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCProtocolDecl;
class OMPThreadPrivateDecl;
class OMPRequiresDecl;
class OMPDeclareReductionDecl;
class OMPDeclareSimdDecl;
class OMPClause;
struct OMPVarListLocTy;
struct OverloadCandidate;
enum class OverloadCandidateParamOrder : char;
enum OverloadCandidateRewriteKind : unsigned;
class OverloadCandidateSet;
class OverloadExpr;
class ParenListExpr;
class ParmVarDecl;
class Preprocessor;
class PseudoDestructorTypeStorage;
class PseudoObjectExpr;
class QualType;
class StandardConversionSequence;
class Stmt;
class StringLiteral;
class SwitchStmt;
class TemplateArgument;
class TemplateArgumentList;
class TemplateArgumentLoc;
class TemplateDecl;
class TemplateInstantiationCallback;
class TemplateParameterList;
class TemplatePartialOrderingContext;
class TemplateTemplateParmDecl;
class Token;
class TypeAliasDecl;
class TypedefDecl;
class TypedefNameDecl;
class TypeLoc;
class TypoCorrectionConsumer;
class UnqualifiedId;
class UnresolvedLookupExpr;
class UnresolvedMemberExpr;
class UnresolvedSetImpl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class ValueDecl;
class VarDecl;
class VarTemplateSpecializationDecl;
class VisibilityAttr;
class VisibleDeclConsumer;
class IndirectFieldDecl;
struct DeductionFailureInfo;
class TemplateSpecCandidateSet;
namespace sema {
class AccessedEntity;
class BlockScopeInfo;
class Capture;
class CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
class SemaPPCallbacks;
class TemplateDeductionInfo;
}
namespace threadSafety {
class BeforeSet;
void threadSafetyCleanup(BeforeSet* Cache);
}
// FIXME: No way to easily map from TemplateTypeParmTypes to
// TemplateTypeParmDecls, so we have this horrible PointerUnion.
typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
/// Describes whether we've seen any nullability information for the given
/// file.
struct FileNullability {
/// The first pointer declarator (of any pointer kind) in the file that does
/// not have a corresponding nullability annotation.
SourceLocation PointerLoc;
/// The end location for the first pointer declarator in the file. Used for
/// placing fix-its.
SourceLocation PointerEndLoc;
/// Which kind of pointer declarator we saw.
uint8_t PointerKind;
/// Whether we saw any type nullability annotations in the given file.
bool SawTypeNullability = false;
};
/// A mapping from file IDs to a record of whether we've seen nullability
/// information in that file.
class FileNullabilityMap {
/// A mapping from file IDs to the nullability information for each file ID.
llvm::DenseMap<FileID, FileNullability> Map;
/// A single-element cache based on the file ID.
struct {
FileID File;
FileNullability Nullability;
} Cache;
public:
FileNullability &operator[](FileID file) {
// Check the single-element cache.
if (file == Cache.File)
return Cache.Nullability;
// It's not in the single-element cache; flush the cache if we have one.
if (!Cache.File.isInvalid()) {
Map[Cache.File] = Cache.Nullability;
}
// Pull this entry into the cache.
Cache.File = file;
Cache.Nullability = Map[file];
return Cache.Nullability;
}
};
/// Keeps track of expected type during expression parsing. The type is tied to
/// a particular token, all functions that update or consume the type take a
/// start location of the token they are looking at as a parameter. This allows
/// to avoid updating the type on hot paths in the parser.
class PreferredTypeBuilder {
public:
PreferredTypeBuilder() = default;
explicit PreferredTypeBuilder(QualType Type) : Type(Type) {}
void enterCondition(Sema &S, SourceLocation Tok);
void enterReturn(Sema &S, SourceLocation Tok);
void enterVariableInit(SourceLocation Tok, Decl *D);
/// Computing a type for the function argument may require running
/// overloading, so we postpone its computation until it is actually needed.
///
/// Clients should be very careful when using this funciton, as it stores a
/// function_ref, clients should make sure all calls to get() with the same
/// location happen while function_ref is alive.
void enterFunctionArgument(SourceLocation Tok,
llvm::function_ref<QualType()> ComputeType);
void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
SourceLocation OpLoc);
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
/// Handles all type casts, including C-style cast, C++ casts, etc.
void enterTypeCast(SourceLocation Tok, QualType CastType);
QualType get(SourceLocation Tok) const {
if (Tok != ExpectedLoc)
return QualType();
if (!Type.isNull())
return Type;
if (ComputeType)
return ComputeType();
return QualType();
}
private:
/// Start position of a token for which we store expected type.
SourceLocation ExpectedLoc;
/// Expected type for a token starting at ExpectedLoc.
QualType Type;
/// A function to compute expected type at ExpectedLoc. It is only considered
/// if Type is null.
llvm::function_ref<QualType()> ComputeType;
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema final {
Sema(const Sema &) = delete;
void operator=(const Sema &) = delete;
/// A key method to reduce duplicate debug info from Sema.
virtual void anchor();
///Source of additional semantic information.
ExternalSemaSource *ExternalSource;
///Whether Sema has generated a multiplexer and has to delete it.
bool isMultiplexExternalSource;
static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
bool isVisibleSlow(const NamedDecl *D);
/// Determine whether two declarations should be linked together, given that
/// the old declaration might not be visible and the new declaration might
/// not have external linkage.
bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
const NamedDecl *New) {
if (isVisible(Old))
return true;
// See comment in below overload for why it's safe to compute the linkage
// of the new declaration here.
if (New->isExternallyDeclarable()) {
assert(Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl");
return true;
}
return false;
}
bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
QualType ResultTy,
ArrayRef<QualType> Args);
public:
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef OpaquePtr<QualType> TypeTy;
OpenCLOptions OpenCLFeatures;
FPOptions FPFeatures;
const LangOptions &LangOpts;
Preprocessor &PP;
ASTContext &Context;
ASTConsumer &Consumer;
DiagnosticsEngine &Diags;
SourceManager &SourceMgr;
api_notes::APINotesManager APINotes;
/// Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// Generally null except when we temporarily switch decl contexts,
/// like in \see ActOnObjCTemporaryExitContainerContext.
DeclContext *OriginalLexicalContext;
/// VAListTagName - The declaration name corresponding to __va_list_tag.
/// This is used as part of a hack to omit that class from ADL results.
DeclarationName VAListTagName;
bool MSStructPragmaOn; // True when \#pragma ms_struct on
/// Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
/// Stack of active SEH __finally scopes. Can be empty.
SmallVector<Scope*, 2> CurrentSEHFinally;
/// Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
/// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
/// `TransformTypos` in order to keep track of any TypoExprs that are created
/// recursively during typo correction and wipe them away if the correction
/// fails.
llvm::SmallVector<TypoExpr *, 2> TypoExprs;
/// pragma clang section kind
enum PragmaClangSectionKind {
PCSK_Invalid = 0,
PCSK_BSS = 1,
PCSK_Data = 2,
PCSK_Rodata = 3,
PCSK_Text = 4,
PCSK_Relro = 5
};
enum PragmaClangSectionAction {
PCSA_Set = 0,
PCSA_Clear = 1
};
struct PragmaClangSection {
std::string SectionName;
bool Valid = false;
SourceLocation PragmaLocation;
void Act(SourceLocation PragmaLocation,
PragmaClangSectionAction Action,
StringLiteral* Name);
};
PragmaClangSection PragmaClangBSSSection;
PragmaClangSection PragmaClangDataSection;
PragmaClangSection PragmaClangRodataSection;
PragmaClangSection PragmaClangRelroSection;
PragmaClangSection PragmaClangTextSection;
enum PragmaMsStackAction {
PSK_Reset = 0x0, // #pragma ()
PSK_Set = 0x1, // #pragma (value)
PSK_Push = 0x2, // #pragma (push[, id])
PSK_Pop = 0x4, // #pragma (pop[, id])
PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
};
template<typename ValueType>
struct PragmaStack {
struct Slot {
llvm::StringRef StackSlotLabel;
ValueType Value;
SourceLocation PragmaLocation;
SourceLocation PragmaPushLocation;
Slot(llvm::StringRef StackSlotLabel, ValueType Value,
SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation),
PragmaPushLocation(PragmaPushLocation) {}
};
void Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
ValueType Value);
// MSVC seems to add artificial slots to #pragma stacks on entering a C++
// method body to restore the stacks on exit, so it works like this:
//
// struct S {
// #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
// void Method {}
// #pragma <name>(pop, InternalPragmaSlot)
// };
//
// It works even with #pragma vtordisp, although MSVC doesn't support
// #pragma vtordisp(push [, id], n)
// syntax.
//
// Push / pop a named sentinel slot.
void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
assert((Action == PSK_Push || Action == PSK_Pop) &&
"Can only push / pop #pragma stack sentinels!");
Act(CurrentPragmaLocation, Action, Label, CurrentValue);
}
// Constructors.
explicit PragmaStack(const ValueType &Default)
: DefaultValue(Default), CurrentValue(Default) {}
bool hasValue() const { return CurrentValue != DefaultValue; }
SmallVector<Slot, 2> Stack;
ValueType DefaultValue; // Value used for PSK_Reset action.
ValueType CurrentValue;
SourceLocation CurrentPragmaLocation;
};
// FIXME: We should serialize / deserialize these if they occur in a PCH (but
// we shouldn't do so if they're in a module).
/// Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
PragmaStack<MSVtorDispMode> VtorDispStack;
// #pragma pack.
// Sentinel to represent when the stack is set to mac68k alignment.
static const unsigned kMac68kAlignmentSentinel = ~0U;
PragmaStack<unsigned> PackStack;
// The current #pragma pack values and locations at each #include.
struct PackIncludeState {
unsigned CurrentValue;
SourceLocation CurrentPragmaLocation;
bool HasNonDefaultValue, ShouldWarnOnInclude;
};
SmallVector<PackIncludeState, 8> PackIncludeStack;
// Segment #pragmas.
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
// RAII object to push / pop sentinel slots for all MS #pragma stacks.
// Actions should be performed only if we enter / exit a C++ method body.
class PragmaStackSentinelRAII {
public:
PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
~PragmaStackSentinelRAII();
private:
Sema &S;
StringRef SlotLabel;
bool ShouldAct;
};
/// A mapping that describes the nullability we've seen in each header file.
FileNullabilityMap NullabilityMap;
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
/// VisContext - Manages the stack for \#pragma GCC visibility.
void *VisContext; // Really a "PragmaVisStack*"
/// This an attribute introduced by \#pragma clang attribute.
struct PragmaAttributeEntry {
SourceLocation Loc;
ParsedAttr *Attribute;
SmallVector<attr::SubjectMatchRule, 4> MatchRules;
bool IsUsed;
};
/// A push'd group of PragmaAttributeEntries.
struct PragmaAttributeGroup {
/// The location of the push attribute.
SourceLocation Loc;
/// The namespace of this push group.
const IdentifierInfo *Namespace;
SmallVector<PragmaAttributeEntry, 2> Entries;
};
SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
/// The declaration that is currently receiving an attribute from the
/// #pragma attribute stack.
const Decl *PragmaAttributeCurrentTargetDecl;
/// This represents the last location of a "#pragma clang optimize off"
/// directive if such a directive has not been closed by an "on" yet. If
/// optimizations are currently "on", this is set to an invalid location.
SourceLocation OptimizeOffPragmaLocation;
/// Flag indicating if Sema is building a recovery call expression.
///
/// This flag is used to avoid building recovery call expressions
/// if Sema is already doing so, which would cause infinite recursions.
bool IsBuildingRecoveryCallExpr;
/// Used to control the generation of ExprWithCleanups.
CleanupInfo Cleanup;
/// ExprCleanupObjects - This is the stack of objects requiring
/// cleanup that are created by the current full expression. The
/// element type here is ExprWithCleanups::Object.
SmallVector<BlockDecl*, 8> ExprCleanupObjects;
/// Store a set of either DeclRefExprs or MemberExprs that contain a reference
/// to a variable (constant) that may or may not be odr-used in this Expr, and
/// we won't know until all lvalue-to-rvalue and discarded value conversions
/// have been applied to all subexpressions of the enclosing full expression.
/// This is cleared at the end of each full expression.
using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>;
MaybeODRUseExprSet MaybeODRUseExprs;
std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
/// Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadExtVectorDecls, 2, 2>
ExtVectorDeclsType;
/// ExtVectorDecls - This is a list all the extended vector types. This allows
/// us to associate a raw vector type with one of the ext_vector type names.
/// This is only necessary for issuing pretty diagnostics.
ExtVectorDeclsType ExtVectorDecls;
/// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
std::unique_ptr<CXXFieldCollector> FieldCollector;
typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
/// Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// Set containing all typedefs that are likely unused.
llvm::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// Delete-expressions to be analyzed at the end of translation unit
///
/// This list contains class members, and locations of delete-expressions
/// that could not be proven as to whether they mismatch with new-expression
/// used in initializer of the field.
typedef std::pair<SourceLocation, bool> DeleteExprLoc;
typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
/// PureVirtualClassDiagSet - a set of class declarations which we have
/// emitted a list of pure virtual functions. Used to prevent emitting the
/// same list more than once.
std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
/// ParsingInitForAutoVars - a set of declarations with auto types for which
/// we are currently parsing the initializer.
llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
/// Look for a locally scoped extern "C" declaration by the given name.
NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
typedef LazyVector<VarDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
TentativeDefinitionsType;
/// All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
/// All the external declarations encoutered and used in the TU.
SmallVector<VarDecl *, 4> ExternalDeclarations;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// The set of file scoped decls seen so far that have not been used
/// and must warn if not used. Only contains the first declaration.
UnusedFileScopedDeclsType UnusedFileScopedDecls;
typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
DelegatingCtorDeclsType;
/// All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// All the overriding functions seen during a class definition
/// that had their exception spec checks delayed, plus the overridden
/// function.
SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
DelayedOverridingExceptionSpecChecks;
/// All the function redeclarations seen during a class definition that had
/// their exception spec checks delayed, plus the prior declaration they
/// should be checked against. Except during error recovery, the new decl
/// should always be a friend declaration, as that's the only valid way to
/// redeclare a special member before its class is complete.
SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
DelayedEquivalentExceptionSpecChecks;
typedef llvm::MapVector<const FunctionDecl *,
std::unique_ptr<LateParsedTemplate>>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// Callback to the parser to parse templated functions when needed.
typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
typedef void LateTemplateParserCleanupCB(void *P);
LateTemplateParserCB *LateTemplateParser;
LateTemplateParserCleanupCB *LateTemplateParserCleanup;
void *OpaqueParser;
void SetLateTemplateParser(LateTemplateParserCB *LTP,
LateTemplateParserCleanupCB *LTPCleanup,
void *P) {
LateTemplateParser = LTP;
LateTemplateParserCleanup = LTPCleanup;
OpaqueParser = P;
}
/// \brief Callback to the parser to parse a type expressed as a string.
std::function<TypeResult(StringRef, StringRef, SourceLocation)>
ParseTypeFromStringCallback;
class DelayedDiagnostics;
class DelayedDiagnosticsState {
sema::DelayedDiagnosticPool *SavedPool;
friend class Sema::DelayedDiagnostics;
};
typedef DelayedDiagnosticsState ParsingDeclState;
typedef DelayedDiagnosticsState ProcessingContextState;
/// A class which encapsulates the logic for delaying diagnostics
/// during parsing and other processing.
class DelayedDiagnostics {
/// The current pool of diagnostics into which delayed
/// diagnostics should go.
sema::DelayedDiagnosticPool *CurPool;
public:
DelayedDiagnostics() : CurPool(nullptr) {}
/// Adds a delayed diagnostic.
void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
/// Determines whether diagnostics should be delayed.
bool shouldDelayDiagnostics() { return CurPool != nullptr; }
/// Returns the current delayed-diagnostics pool.
sema::DelayedDiagnosticPool *getCurrentPool() const {
return CurPool;
}
/// Enter a new scope. Access and deprecation diagnostics will be
/// collected in this pool.
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = &pool;
return state;
}
/// Leave a delayed-diagnostic state that was previously pushed.
/// Do not emit any of the diagnostics. This is performed as part
/// of the bookkeeping of popping a pool "properly".
void popWithoutEmitting(DelayedDiagnosticsState state) {
CurPool = state.SavedPool;
}
/// Enter a new scope where access and deprecation diagnostics are
/// not delayed.
DelayedDiagnosticsState pushUndelayed() {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = nullptr;
return state;
}
/// Undo a previous pushUndelayed().
void popUndelayed(DelayedDiagnosticsState state) {
assert(CurPool == nullptr);
CurPool = state.SavedPool;
}
} DelayedDiagnostics;
/// A RAII object to temporarily push a declaration context.
class ContextRAII {
private:
Sema &S;
DeclContext *SavedContext;
ProcessingContextState SavedContextState;
QualType SavedCXXThisTypeOverride;
public:
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
: S(S), SavedContext(S.CurContext),
SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
{
assert(ContextToPush && "pushing null context");
S.CurContext = ContextToPush;
if (NewThisContext)
S.CXXThisTypeOverride = QualType();
}
void pop() {
if (!SavedContext) return;
S.CurContext = SavedContext;
S.DelayedDiagnostics.popUndelayed(SavedContextState);
S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
SavedContext = nullptr;
}
~ContextRAII() {
pop();
}
};
/// Used to change context to isConstantEvaluated without pushing a heavy
/// ExpressionEvaluationContextRecord object.
bool isConstantEvaluatedOverride;
bool isConstantEvaluated() {
return ExprEvalContexts.back().isConstantEvaluated() ||
isConstantEvaluatedOverride;
}
/// RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
bool PushedCodeSynthesisContext = false;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC) {
S.PushFunctionScope();
S.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
if (auto *FD = dyn_cast<FunctionDecl>(DC))
FD->setWillHaveBody(true);
else
assert(isa<ObjCMethodDecl>(DC));
}
void addContextNote(SourceLocation UseLoc) {
assert(!PushedCodeSynthesisContext);
Sema::CodeSynthesisContext Ctx;
Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
Ctx.PointOfInstantiation = UseLoc;
Ctx.Entity = cast<Decl>(S.CurContext);
S.pushCodeSynthesisContext(Ctx);
PushedCodeSynthesisContext = true;
}
~SynthesizedFunctionScope() {
if (PushedCodeSynthesisContext)
S.popCodeSynthesisContext();
if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
FD->setWillHaveBody(false);
S.PopExpressionEvaluationContext();
S.PopFunctionScopeInfo();
}
};
/// WeakUndeclaredIdentifiers - Identifiers contained in
/// \#pragma weak before declared. rare. may alias another
/// identifier, declared or undeclared
llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
/// ExtnameUndeclaredIdentifiers - Identifiers contained in
/// \#pragma redefine_extname before declared. Used in Solaris system headers
/// to define functions that occur in multiple standards to call the version
/// in the currently selected standard.
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
/// Load weak undeclared identifiers from the external source.
void LoadExternalWeakUndeclaredIdentifiers();
/// WeakTopLevelDecl - Translation-unit scoped declarations generated by
/// \#pragma weak during processing of other Decls.
/// I couldn't figure out a clean way to generate these in-line, so
/// we store them here and handle separately -- which is a hack.
/// It would be best to refactor this.
SmallVector<Decl*,2> WeakTopLevelDecl;
IdentifierResolver IdResolver;
/// Translation Unit Scope - useful to Objective-C actions that need
/// to lookup file scope declarations in the "ordinary" C decl namespace.
/// For example, user-defined classes, built-in "id" type, etc.
Scope *TUScope;
/// The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// The C++ "std::align_val_t" enum class, which is defined by the C++
/// standard library.
LazyDeclPtr StdAlignValT;
/// The C++ "std::experimental" namespace, where the experimental parts
/// of the standard library resides.
NamespaceDecl *StdExperimentalNamespaceCache;
/// The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// The C++ "std::coroutine_traits" template, which is defined in
/// \<coroutine_traits>
ClassTemplateDecl *StdCoroutineTraitsCache;
/// The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// Caches identifiers/selectors for NSFoundation APIs.
std::unique_ptr<NSAPI> NSAPIObj;
/// The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// id<NSCopying> type.
QualType QIDNSCopying;
/// will hold 'respondsToSelector:'
Selector RespondsToSelectorSel;
/// A flag to remember whether the implicit forms of operator new and delete
/// have been declared.
bool GlobalNewDeleteDeclared;
/// A flag to indicate that we're in a context that permits abstract
/// references to fields. This is really a
bool AllowAbstractFieldReference;
/// Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum class ExpressionEvaluationContext {
/// The current expression and its subexpressions occur within an
/// unevaluated operand (C++11 [expr]p7), such as the subexpression of
/// \c sizeof, where the type of the expression may be significant but
/// no code will be generated to evaluate the value of the expression at
/// run time.
Unevaluated,
/// The current expression occurs within a braced-init-list within
/// an unevaluated operand. This is mostly like a regular unevaluated
/// context, except that we still instantiate constexpr functions that are
/// referenced here so that we can perform narrowing checks correctly.
UnevaluatedList,
/// The current expression occurs within a discarded statement.
/// This behaves largely similarly to an unevaluated operand in preventing
/// definitions from being required, but not in other ways.
DiscardedStatement,
/// The current expression occurs within an unevaluated
/// operand that unconditionally permits abstract references to
/// fields, such as a SIZE operator in MS-style inline assembly.
UnevaluatedAbstract,
/// The current context is "potentially evaluated" in C++11 terms,
/// but the expression is evaluated at compile-time (like the values of
/// cases in a switch statement).
ConstantEvaluated,
/// The current expression is potentially evaluated at run time,
/// which means that code may be generated to evaluate the value of the
/// expression at run time.
PotentiallyEvaluated,
/// The current expression is potentially evaluated, but any
/// declarations referenced inside that expression are only used if
/// in fact the current expression is used.
///
/// This value is used when parsing default function arguments, for which
/// we would like to provide diagnostics (e.g., passing non-POD arguments
/// through varargs) but do not want to mark declarations as "referenced"
/// until the default argument is used.
PotentiallyEvaluatedIfUsed
};
/// Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// The expression evaluation context.
ExpressionEvaluationContext Context;
/// Whether the enclosing context needed a cleanup.
CleanupInfo ParentCleanup;
/// Whether we are in a decltype expression.
bool IsDecltype;
/// The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
MaybeODRUseExprSet SavedMaybeODRUseExprs;
/// The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// The declaration that provides context for lambda expressions
/// and block literals if the normal declaration context does not
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
/// If we are processing a decltype type, a set of call expressions
/// for which we have deferred checking the completeness of the return type.
SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
/// If we are processing a decltype type, a set of temporary binding
/// expressions for which we have deferred checking the destructor.
SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
/// Expressions appearing as the LHS of a volatile assignment in this
/// context. We produce a warning for these when popping the context if
/// they are not discarded-value expressions nor unevaluated operands.
SmallVector<Expr*, 2> VolatileAssignmentLHSs;
/// \brief Describes whether we are in an expression constext which we have
/// to handle differently.
enum ExpressionKind {
EK_Decltype, EK_TemplateArgument, EK_Other
} ExprContext;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
CleanupInfo ParentCleanup,
Decl *ManglingContextDecl,
ExpressionKind ExprContext)
: Context(Context), ParentCleanup(ParentCleanup),
NumCleanupObjects(NumCleanupObjects), NumTypos(0),
ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {}
bool isUnevaluated() const {
return Context == ExpressionEvaluationContext::Unevaluated ||
Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
Context == ExpressionEvaluationContext::UnevaluatedList;
}
bool isConstantEvaluated() const {
return Context == ExpressionEvaluationContext::ConstantEvaluated;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// Emit a warning for all pending noderef expressions that we recorded.
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
/// Compute the mangling number context for a lambda expression or
/// block literal. Also return the extra mangling decl if any.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
std::tuple<MangleNumberingContext *, Decl *>
getCurrentMangleNumberContext(const DeclContext *DC);
/// SpecialMemberOverloadResult - The overloading result for a special member
/// function.
///
/// This is basically a wrapper around PointerIntPair. The lowest bits of the
/// integer are used to determine whether overload resolution succeeded.
class SpecialMemberOverloadResult {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult() : Pair() {}
SpecialMemberOverloadResult(CXXMethodDecl *MD)
: Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
void setKind(Kind K) { Pair.setInt(K); }
};
class SpecialMemberOverloadResultEntry
: public llvm::FastFoldingSetNode,
public SpecialMemberOverloadResult {
public:
SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
};
/// A cache of special member function overload resolution results
/// for C++ records.
llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
/// A cache of the flags available in enumerations with the flag_bits
/// attribute.
mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
/// The kind of translation unit we are processing.
///
/// When we're processing a complete translation unit, Sema will perform
/// end-of-translation-unit semantic tasks (such as creating
/// initializers for tentative definitions in C) once parsing has
/// completed. Modules and precompiled headers perform different kinds of
/// checks.
TranslationUnitKind TUKind;
llvm::BumpPtrAllocator BumpAlloc;
/// The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// A mapping from parameters with unparsed default arguments to the
/// set of instantiations of each parameter.
///
/// This mapping is a temporary data structure used when parsing
/// nested class templates or nested classes of class templates,
/// where we might end up instantiating an inner class before the
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
// Contains the locations of the beginning of unparsed default
// argument locations.
llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
/// UndefinedInternals - all the used, undefined objects which require a
/// definition in this translation unit.
llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
/// Determine if VD, which must be a variable or function, is an external
/// symbol that nonetheless can't be referenced from outside this translation
/// unit because its type has no linkage and it's not extern "C".
bool isExternalWithNoLinkageType(ValueDecl *VD);
/// Obtain a sorted list of functions that are undefined but ODR-used.
void getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
/// Retrieves list of suspicious delete-expressions that will be checked at
/// the end of translation unit.
const llvm::MapVector<FieldDecl *, DeleteLocs> &
getMismatchingDeleteExpressions() const;
typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
/// Method Pool - allows efficient lookup when typechecking messages to "id".
/// We need to maintain a list, since selectors can have differing signatures
/// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
/// of selectors are "overloaded").
/// At the head of the list it is recorded whether there were 0, 1, or >= 2
/// methods inside categories with a particular selector.
GlobalMethodPool MethodPool;
/// Method selectors used in a \@selector expression. Used for implementation
/// of -Wselector.
llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
/// List of SourceLocations where 'self' is implicitly retained inside a
/// block.
llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
ImplicitlyRetainedSelfLocs;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
SpecialMemberDecl;
/// The C++ special members which we are currently in the process of
/// declaring. If this process recursively triggers the declaration of the
/// same special member, we should act as if it is not yet declared.
llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
/// Kinds of defaulted comparison operator functions.
enum class DefaultedComparisonKind : unsigned char {
/// This is not a defaultable comparison operator.
None,
/// This is an operator== that should be implemented as a series of
/// subobject comparisons.
Equal,
/// This is an operator<=> that should be implemented as a series of
/// subobject comparisons.
ThreeWay,
/// This is an operator!= that should be implemented as a rewrite in terms
/// of a == comparison.
NotEqual,
/// This is an <, <=, >, or >= that should be implemented as a rewrite in
/// terms of a <=> comparison.
Relational,
};
/// The function definitions which were renamed as part of typo-correction
/// to match their respective declarations. We want to keep track of them
/// to ensure that we don't emit a "redefinition" error if we encounter a
/// correctly named definition after the renamed definition.
llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
/// Stack of types that correspond to the parameter entities that are
/// currently being copy-initialized. Can be empty.
llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
void ReadMethodPool(Selector Sel);
void updateOutOfDateSelector(Selector Sel);
/// Private Helper predicate to check for 'self'.
bool isSelfExpr(Expr *RExpr);
bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
/// Cause the active diagnostic on the DiagosticsEngine to be
/// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
/// should not be used elsewhere.
void EmitCurrentDiagnostic(unsigned DiagID);
/// Records and restores the FP_CONTRACT state on entry/exit of compound
/// statements.
class FPContractStateRAII {
public:
FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {}
~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; }
private:
Sema& S;
FPOptions OldFPFeaturesState;
};
void addImplicitTypedef(StringRef Name, QualType T);
bool WarnedStackExhausted = false;
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// Perform initialization that occurs after the parser has been
/// initialized but before it parses anything.
void Initialize();
const LangOptions &getLangOpts() const { return LangOpts; }
OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
FPOptions &getFPOptions() { return FPFeatures; }
DiagnosticsEngine &getDiagnostics() const { return Diags; }
SourceManager &getSourceManager() const { return SourceMgr; }
Preprocessor &getPreprocessor() const { return PP; }
ASTContext &getASTContext() const { return Context; }
ASTConsumer &getASTConsumer() const { return Consumer; }
ASTMutationListener *getASTMutationListener() const;
ExternalSemaSource* getExternalSource() const { return ExternalSource; }
///Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///
///\param[in] E - A non-null external sema source.
///
void addExternalSource(ExternalSemaSource *E);
void PrintStats() const;
/// Warn that the stack is nearly exhausted.
void warnStackExhausted(SourceLocation Loc);
/// Run some code with "sufficient" stack space. (Currently, at least 256K is
/// guaranteed). Produces a warning if we're low on stack space and allocates
/// more in that case. Use this in code that may recurse deeply (for example,
/// in template instantiation) to avoid stack overflow.
void runWithSufficientStackSpace(SourceLocation Loc,
llvm::function_ref<void()> Fn);
/// Helper class that creates diagnostics with optional
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
/// class that emits diagnostics. SemaDiagnosticBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
class SemaDiagnosticBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
// This is a cunning lie. DiagnosticBuilder actually performs move
// construction in its copy constructor (but due to varied uses, it's not
// possible to conveniently express this as actual move construction). So
// the default copy ctor here is fine, because the base class disables the
// source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op
// in that case anwyay.
SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default;
~SemaDiagnosticBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First flush the underlying
// DiagnosticBuilder data, and clear the diagnostic builder itself so it
// won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
FlushCounts();
Clear();
// Dispatch to Sema to emit the diagnostic.
SemaRef.EmitCurrentDiagnostic(DiagID);
}
/// Teach operator<< to produce an object of the correct type.
template<typename T>
friend const SemaDiagnosticBuilder &operator<<(
const SemaDiagnosticBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
};
/// Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// Get a string to suggest for zero-initialization of a type.
std::string
getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
/// Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
void emitAndClearUnusedLocalTypedefWarnings();
enum TUFragmentKind {
/// The global module fragment, between 'module;' and a module-declaration.
Global,
/// A normal translation unit fragment. For a non-module unit, this is the
/// entire translation unit. Otherwise, it runs from the module-declaration
/// to the private-module-fragment (if any) or the end of the TU (if not).
Normal,
/// The private module fragment, between 'module :private;' and the end of
/// the translation unit.
Private
};
void ActOnStartOfTranslationUnit();
void ActOnEndOfTranslationUnit();
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// This is used to inform Sema what the current TemplateParameterDepth
/// is during Parsing. Currently it is used to pass on the depth
/// when parsing generic lambda 'auto' parameters.
void RecordParsingTemplateParameterDepth(unsigned Depth);
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
RecordDecl *RD, CapturedRegionKind K,
unsigned OpenMPCaptureLevel = 0);
/// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
/// time after they've been popped.
class PoppedFunctionScopeDeleter {
Sema *Self;
public:
explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
void operator()(sema::FunctionScopeInfo *Scope) const;
};
using PoppedFunctionScopePtr =
std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
PoppedFunctionScopePtr
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
QualType BlockType = QualType());
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const;
void setFunctionHasBranchIntoScope();
void setFunctionHasBranchProtectedScope();
void setFunctionHasIndirectGoto();
void PushCompoundScope(bool IsStmtExpr);
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// Get the innermost lambda enclosing the current location, if any. This
/// looks through intervening non-lambda scopes such as local functions and
/// blocks.
sema::LambdaScopeInfo *getEnclosingLambda() const;
/// Retrieve the current lambda scope info, if any.
/// \param IgnoreNonLambdaCapturingScope true if should find the top-most
/// lambda scope info ignoring all inner capturing scopes that are not
/// lambda scopes.
sema::LambdaScopeInfo *
getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
/// Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// Retrieve the current captured region, if any.
sema::CapturedRegionScopeInfo *getCurCapturedRegion();
/// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
void ActOnComment(SourceRange Comment);
//===--------------------------------------------------------------------===//
// Type Analysis / Processing: SemaType.cpp.
//
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
const DeclSpec *DS = nullptr);
QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
const DeclSpec *DS = nullptr);
QualType BuildPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildReferenceType(QualType T, bool LValueRef,
SourceLocation Loc, DeclarationName Entity);
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
Expr *ArraySize, unsigned Quals,
SourceRange Brackets, DeclarationName Entity);
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
QualType BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
SourceLocation AttrLoc);
/// Same as above, but constructs the AddressSpace index if not provided.
QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
SourceLocation AttrLoc);
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
/// Build a function type.
///
/// This routine checks the function type according to C++ rules and
/// under the assumption that the result type and parameter types have
/// just been instantiated from a template. It therefore duplicates
/// some of the behavior of GetTypeForDeclarator, but in a much
/// simpler form that is only suitable for this narrow use case.
///
/// \param T The return type of the function.
///
/// \param ParamTypes The parameter types of the function. This array
/// will be modified to account for adjustments to the types of the
/// function parameters.
///
/// \param Loc The location of the entity whose type involves this
/// function type or, if there is no such entity, the location of the
/// type that will have function type.
///
/// \param Entity The name of the entity that involves the function
/// type, if known.
///
/// \param EPI Extra information about the function type. Usually this will
/// be taken from an existing function with the same prototype.
///
/// \returns A suitable function type, if there are no errors. The
/// unqualified type will always be a FunctionProtoType.
/// Otherwise, returns a NULL type.
QualType BuildFunctionType(QualType T,
MutableArrayRef<QualType> ParamTypes,
SourceLocation Loc, DeclarationName Entity,
const FunctionProtoType::ExtProtoInfo &EPI);
QualType BuildMemberPointerType(QualType T, QualType Class,
SourceLocation Loc,
DeclarationName Entity);
QualType BuildBlockPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildParenType(QualType T);
QualType BuildAtomicType(QualType T, SourceLocation Loc);
QualType BuildReadPipeType(QualType T,
SourceLocation Loc);
QualType BuildWritePipeType(QualType T,
SourceLocation Loc);
TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
/// Package the given type and TSI into a ParsedType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
DeclarationNameInfo GetNameForDeclarator(Declarator &D);
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
static QualType GetTypeFromParser(ParsedType Ty,
TypeSourceInfo **TInfo = nullptr);
CanThrowResult canThrow(const Stmt *E);
const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
const FunctionProtoType *FPT);
void UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI);
bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
bool CheckDistantExceptionSpec(QualType T);
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
bool CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool CheckEquivalentExceptionSpec(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const PartialDiagnostic &NoThrowDiagID,
const FunctionProtoType *Superset,
SourceLocation SuperLoc,
const FunctionProtoType *Subset,
SourceLocation SubLoc);
bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
const PartialDiagnostic &NoteID,
const FunctionProtoType *Target,
SourceLocation TargetLoc,
const FunctionProtoType *Source,
SourceLocation SourceLoc);
TypeResult ActOnTypeName(Scope *S, Declarator &D);
/// The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// Abstract class used to diagnose incomplete types.
struct TypeDiagnoser {
TypeDiagnoser() {}
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
virtual ~TypeDiagnoser() {}
};
static int getPrintable(int I) { return I; }
static unsigned getPrintable(unsigned I) { return I; }
static bool getPrintable(bool B) { return B; }
static const char * getPrintable(const char *S) { return S; }
static StringRef getPrintable(StringRef S) { return S; }
static const std::string &getPrintable(const std::string &S) { return S; }
static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
return II;
}
static DeclarationName getPrintable(DeclarationName N) { return N; }
static QualType getPrintable(QualType T) { return T; }
static SourceRange getPrintable(SourceRange R) { return R; }
static SourceRange getPrintable(SourceLocation L) { return L; }
static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
unsigned DiagID;
std::tuple<const Ts &...> Args;
template <std::size_t... Is>
void emit(const SemaDiagnosticBuilder &DB,
std::index_sequence<Is...>) const {
// Apply all tuple elements to the builder in order.
bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
(void)Dummy;
}
public:
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
: TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
assert(DiagID != 0 && "no diagnostic for type diagnoser");
}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
emit(DB, std::index_sequence_for<Ts...>());
DB << T;
}
};
/// Do a check to make sure \p Name looks like a legal swift_name
/// attribute for the decl \p D. Raise a diagnostic if the name is invalid
/// for the given declaration.
///
/// For a function, this will validate a compound Swift name,
/// e.g. <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>,
/// and the function will output the number of parameter names, and whether
/// this is a single-arg initializer.
///
/// For a type, enum constant, property, or variable declaration, this will
/// validate either a simple identifier, or a qualified
/// <code>context.identifier</code> name.
///
/// \returns true if the name is a valid swift name for \p D, false otherwise.
bool DiagnoseSwiftName(Decl *D, StringRef Name,
SourceLocation ArgLoc,
const IdentifierInfo *AttrName);
private:
/// Methods for marking which expressions involve dereferencing a pointer
/// marked with the 'noderef' attribute. Expressions are checked bottom up as
/// they are parsed, meaning that a noderef pointer may not be accessed. For
/// example, in `&*p` where `p` is a noderef pointer, we will first parse the
/// `*p`, but need to check that `address of` is called on it. This requires
/// keeping a container of all pending expressions and checking if the address
/// of them are eventually taken.
void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
void CheckAddressOfNoDeref(const Expr *E);
void CheckMemberAccessOfNoDeref(const MemberExpr *E);
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
TypeDiagnoser *Diagnoser);
struct ModuleScope {
SourceLocation BeginLoc;
clang::Module *Module = nullptr;
bool ModuleInterface = false;
bool ImplicitGlobalModuleFragment = false;
VisibleModuleSet OuterVisibleModules;
};
/// The modules we're currently parsing.
llvm::SmallVector<ModuleScope, 16> ModuleScopes;
/// Namespace definitions that we will export when they finish.
llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
/// Get the module whose scope we are currently within.
Module *getCurrentModule() const {
return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
}
VisibleModuleSet VisibleModules;
public:
/// Get the module owning an entity.
Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); }
/// Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND);
bool isModuleVisible(const Module *M, bool ModulePrivate = false);
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return !D->isHidden() || isVisibleSlow(D);
}
/// Determine whether any declaration of an entity is visible.
bool
hasVisibleDeclaration(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
}
bool hasVisibleDeclarationSlow(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules);
bool hasVisibleMergedDefinition(NamedDecl *Def);
bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
/// Determine if \p D and \p Suggested have a structurally compatible
/// layout as described in C11 6.2.7/1.
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
/// Determine if \p D has a visible definition. If not, suggest a declaration
/// that should be made visible to expose the definition.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
bool OnlyNeedComplete = false);
bool hasVisibleDefinition(const NamedDecl *D) {
NamedDecl *Hidden;
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
/// Determine if the template parameter \p D has a visible default argument.
bool
hasVisibleDefaultArgument(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is an explicit
/// specialization declaration for a specialization of a template. (For a
/// member specialization, use hasVisibleMemberSpecialization.)
bool hasVisibleExplicitSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if there is a visible declaration of \p D that is a member
/// specialization declaration (as opposed to an instantiated declaration).
bool hasVisibleMemberSpecialization(
const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
/// Determine if \p A and \p B are equivalent internal linkage declarations
/// from different modules, and thus an ambiguity error can be downgraded to
/// an extension warning.
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
const NamedDecl *B);
void diagnoseEquivalentInternalLinkageDeclarations(
SourceLocation Loc, const NamedDecl *D,
ArrayRef<const NamedDecl *> Equiv);
bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
bool isCompleteType(SourceLocation Loc, QualType T) {
return !RequireCompleteTypeImpl(Loc, T, nullptr);
}
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
unsigned DiagID);
template <typename... Ts>
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, Diagnoser);
}
void completeExprArrayBound(Expr *E);
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
bool RequireCompleteExprType(Expr *E, unsigned DiagID);
template <typename... Ts>
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, Diagnoser);
}
bool RequireLiteralType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
template <typename... Ts>
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireLiteralType(Loc, T, Diagnoser);
}
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
const CXXScopeSpec &SS, QualType T,
TagDecl *OwnedTagDecl = nullptr);
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
/// If AsUnevaluated is false, E is treated as though it were an evaluated
/// context, such as when building a type for decltype(auto).
QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
bool AsUnevaluated = true);
QualType BuildUnaryTransformType(QualType BaseType,
UnaryTransformType::UTTKind UKind,
SourceLocation Loc);
//===--------------------------------------------------------------------===//
// Symbol table / Decl tracking callbacks: SemaDecl.cpp.
//
struct SkipBodyInfo {
SkipBodyInfo()
: ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
New(nullptr) {}
bool ShouldSkip;
bool CheckSameAsPrevious;
NamedDecl *Previous;
NamedDecl *New;
};
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
void DiagnoseUseOfUnimplementedSelectors();
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS = nullptr,
bool isClassName = false, bool HasTrailingDot = false,
ParsedType ObjectType = nullptr,
bool IsCtorOrDtorName = false,
bool WantNontrivialTypeSourceInfo = false,
bool IsClassTemplateDeductionContext = true,
IdentifierInfo **CorrectedII = nullptr);
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
void DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool IsTemplateName = false);
/// Attempt to behave like MSVC in situations where lookup of an unqualified
/// type name has failed in a dependent context. In these situations, we
/// automatically form a DependentTypeName that will retry lookup in a related
/// scope during instantiation.
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
SourceLocation NameLoc,
bool IsTemplateTypeArg);
/// Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
/// This name is not a type or template in this context, but might be
/// something else.
NC_Unknown,
/// Classification failed; an error has been produced.
NC_Error,
/// The name has been typo-corrected to a keyword.
NC_Keyword,
/// The name was classified as a type.
NC_Type,
/// The name was classified as a specific non-type, non-template
/// declaration. ActOnNameClassifiedAsNonType should be called to
/// convert the declaration to an expression.
NC_NonType,
/// The name was classified as an ADL-only function name.
/// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
/// result to an expression.
NC_UndeclaredNonType,
/// The name denotes a member of a dependent type that could not be
/// resolved. ActOnNameClassifiedAsDependentNonType should be called to
/// convert the result to an expression.
NC_DependentNonType,
/// The name was classified as a non-type, and an expression representing
/// that name has been formed.
NC_ContextIndependentExpr,
/// The name was classified as a template whose specializations are types.
NC_TypeTemplate,
/// The name was classified as a variable template name.
NC_VarTemplate,
/// The name was classified as a function template name.
NC_FunctionTemplate,
/// The name was classified as an ADL-only function template name.
NC_UndeclaredTemplate,
};
class NameClassification {
NameClassificationKind Kind;
union {
ExprResult Expr;
NamedDecl *NonTypeDecl;
TemplateName Template;
ParsedType Type;
};
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification ContextIndependentExpr(ExprResult E) {
NameClassification Result(NC_ContextIndependentExpr);
Result.Expr = E;
return Result;
}
static NameClassification NonType(NamedDecl *D) {
NameClassification Result(NC_NonType);
Result.NonTypeDecl = D;
return Result;
}
static NameClassification UndeclaredNonType() {
return NameClassification(NC_UndeclaredNonType);
}
static NameClassification DependentNonType() {
return NameClassification(NC_DependentNonType);
}
static NameClassification TypeTemplate(TemplateName Name) {
NameClassification Result(NC_TypeTemplate);
Result.Template = Name;
return Result;
}
static NameClassification VarTemplate(TemplateName Name) {
NameClassification Result(NC_VarTemplate);
Result.Template = Name;
return Result;
}
static NameClassification FunctionTemplate(TemplateName Name) {
NameClassification Result(NC_FunctionTemplate);
Result.Template = Name;
return Result;
}
static NameClassification UndeclaredTemplate(TemplateName Name) {
NameClassification Result(NC_UndeclaredTemplate);
Result.Template = Name;
return Result;
}
NameClassificationKind getKind() const { return Kind; }
ExprResult getExpression() const {
assert(Kind == NC_ContextIndependentExpr);
return Expr;
}
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
NamedDecl *getNonTypeDecl() const {
assert(Kind == NC_NonType);
return NonTypeDecl;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate);
return Template;
}
TemplateNameKind getTemplateNameKind() const {
switch (Kind) {
case NC_TypeTemplate:
return TNK_Type_template;
case NC_FunctionTemplate:
return TNK_Function_template;
case NC_VarTemplate:
return TNK_Var_template;
case NC_UndeclaredTemplate:
return TNK_Undeclared_template;
default:
llvm_unreachable("unsupported name classification.");
}
}
};
/// Perform name lookup on the given name, classifying it based on
/// the results of name lookup and the following token.
///
/// This routine is used by the parser to resolve identifiers and help direct
/// parsing. When the identifier cannot be found, this routine will attempt
/// to correct the typo and classify based on the resulting name.
///
/// \param S The scope in which we're performing name lookup.
///
/// \param SS The nested-name-specifier that precedes the name.
///
/// \param Name The identifier. If typo correction finds an alternative name,
/// this pointer parameter will be updated accordingly.
///
/// \param NameLoc The location of the identifier.
///
/// \param NextToken The token following the identifier. Used to help
/// disambiguate the name.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo *&Name, SourceLocation NameLoc,
const Token &NextToken,
CorrectionCandidateCallback *CCC = nullptr);
/// Act on the result of classifying a name as an undeclared (ADL-only)
/// non-type declaration.
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
SourceLocation NameLoc);
/// Act on the result of classifying a name as an undeclared member of a
/// dependent base class.
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsAddressOfOperand);
/// Act on the result of classifying a name as a specific non-type
/// declaration.
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
NamedDecl *Found,
SourceLocation NameLoc,
const Token &NextToken);
/// Describes the detailed kind of a template name. Used in diagnostics.
enum class TemplateNameKindForDiagnostics {
ClassTemplate,
FunctionTemplate,
VarTemplate,
AliasTemplate,
TemplateTemplateParam,
Concept,
DependentTemplate
};
TemplateNameKindForDiagnostics
getTemplateNameKindForDiagnostics(TemplateName Name);
/// Determine whether it's plausible that E was intended to be a
/// template-name.
bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
if (!getLangOpts().CPlusPlus || E.isInvalid())
return false;
Dependent = false;
if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
return !DRE->hasExplicitTemplateArgs();
if (auto *ME = dyn_cast<MemberExpr>(E.get()))
return !ME->hasExplicitTemplateArgs();
Dependent = true;
if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
return !DSDRE->hasExplicitTemplateArgs();
if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
return !DSME->hasExplicitTemplateArgs();
// Any additional cases recognized here should also be handled by
// diagnoseExprIntendedAsTemplateName.
return false;
}
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
SourceLocation Less,
SourceLocation Greater);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name, SourceLocation Loc,
bool IsTemplateId);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation(),
SourceLocation UnalignedQualLoc = SourceLocation());
void diagnosePointerAuthDisabled(SourceLocation loc, SourceRange range);
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key);
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
const LookupResult &R);
NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
const LookupResult &R);
void CheckShadow(Scope *S, VarDecl *D);
/// Warn if 'E', which is an expression that is about to be modified, refers
/// to a shadowing declaration.
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
private:
/// Map of current shadowing declarations to shadowed declarations. Warn if
/// it looks like the user is trying to modify the shadowing declaration.
llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
public:
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD);
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous);
NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
LookupResult &Previous, bool &Redeclaration);
NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope,
ArrayRef<BindingDecl *> Bindings = None);
NamedDecl *
ActOnDecompositionDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists);
// Returns true if the variable declaration is a redeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
void CheckVariableDeclarationType(VarDecl *NewVD);
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
Expr *Init);
void CheckCompleteVariableDeclaration(VarDecl *VD);
void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
enum class CheckConstexprKind {
/// Diagnose issues that are non-constant or that are extensions.
Diagnose,
/// Identify whether this function satisfies the formal rules for constexpr
/// functions in the current lanugage mode (with no extensions).
CheckValid
};
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
CheckConstexprKind Kind);
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
void FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
// Returns true if the function declaration is a redeclaration
bool CheckFunctionDeclaration(Scope *S,
FunctionDecl *NewFD, LookupResult &Previous,
bool IsMemberSpecialization);
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
QualType NewT, QualType OldT);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
bool IsDefinition);
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
QualType adjustParameterTypeForObjCAutoRefCount(QualType T,
SourceLocation NameLoc,
TypeSourceInfo *TSInfo);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SC);
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
// Contexts where using non-trivial C union types can be disallowed. This is
// passed to err_non_trivial_c_union_in_invalid_context.
enum NonTrivialCUnionContext {
// Function parameter.
NTCUC_FunctionParam,
// Function return.
NTCUC_FunctionReturn,
// Default-initialized object.
NTCUC_DefaultInitializedObject,
// Variable with automatic storage duration.
NTCUC_AutoVar,
// Initializer expression that might copy from another object.
NTCUC_CopyInit,
// Assignment.
NTCUC_Assignment,
// Compound literal.
NTCUC_CompoundLiteral,
// Block capture.
NTCUC_BlockCapture,
// lvalue-to-rvalue conversion of volatile type.
NTCUC_LValueToRValueVolatile,
};
/// Emit diagnostics if the initializer or any of its explicit or
/// implicitly-generated subexpressions require copying or
/// default-initializing a type that is or contains a C union type that is
/// non-trivial to copy or default-initialize.
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
// These flags are passed to checkNonTrivialCUnion.
enum NonTrivialCUnionKind {
NTCUK_Init = 0x1,
NTCUK_Destruct = 0x2,
NTCUK_Copy = 0x4,
};
/// Emit diagnostics if a non-trivial C union type or a struct that contains
/// a non-trivial C union is used in an invalid context.
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
NonTrivialCUnionContext UseContext,
unsigned NonTrivialKind);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
void ActOnUninitializedDecl(Decl *dcl);
void ActOnInitializerError(Decl *Dcl);
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
void ActOnCXXForRangeDecl(Decl *D);
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs,
SourceLocation AttrEnd);
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
void CheckStaticLocalForDllExport(VarDecl *VD);
void FinalizeDeclaration(Decl *D);
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group);
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
/// Should be called on all declarations that might have attached
/// documentation comments.
void ActOnDocumentableDecl(Decl *D);
void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls);
void CheckForFunctionRedefinition(
FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
SkipBodyInfo *SkipBody = nullptr);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
}
/// Determine whether we can delay parsing the body of a function or
/// function template until it is used, assuming we don't care about emitting
/// code for that function.
///
/// This will be \c false if we may need the body of the function in the
/// middle of parsing an expression (where it's impractical to switch to
/// parsing a different function), for instance, if it's constexpr in C++11
/// or has an 'auto' return type in C++14. These cases are essentially bugs.
bool canDelayFunctionBody(const Declarator &D);
/// Determine whether we can skip parsing the body of a function
/// definition, assuming we don't care about analyzing its body or emitting
/// code for that function.
///
/// This will be \c false only if we may need the body of the function in
/// order to parse the rest of the program (for instance, if it is
/// \c constexpr in C++11 or has an 'auto' return type in C++14).
bool canSkipFunctionBody(Decl *D);
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
Decl *ActOnSkippedFunctionBody(Decl *Decl);
void ActOnFinishInlineFunctionDef(FunctionDecl *D);
/// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
/// attribute for which parsing is delayed.
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
/// Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
/// Diagnose whether the size of parameters or return value of a
/// function or obj-c method definition is pass-by-value and larger than a
/// specified threshold.
void
DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
QualType ReturnTy, NamedDecl *D);
void DiagnoseInvalidJumps(Stmt *Body);
Decl *ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation AsmLoc,
SourceLocation RParenLoc);
/// Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
SourceLocation SemiLoc);
enum class ModuleDeclKind {
Interface, ///< 'export module X;'
Implementation, ///< 'module X;'
};
/// The parser has processed a module-declaration that begins the definition
/// of a module interface or implementation.
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
SourceLocation ModuleLoc, ModuleDeclKind MDK,
ModuleIdPath Path, bool IsFirstDecl);
/// The parser has processed a global-module-fragment declaration that begins
/// the definition of the global module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
/// The parser has processed a private-module-fragment declaration that begins
/// the definition of the private module fragment of the current module unit.
/// \param ModuleLoc The location of the 'module' keyword.
/// \param PrivateLoc The location of the 'private' keyword.
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
SourceLocation PrivateLoc);
/// The parser has processed a module import declaration.
///
/// \param StartLoc The location of the first token in the declaration. This
/// could be the location of an '@', 'export', or 'import'.
/// \param ExportLoc The location of the 'export' keyword, if any.
/// \param ImportLoc The location of the 'import' keyword.
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, ModuleIdPath Path);
DeclResult ActOnModuleImport(SourceLocation StartLoc,
SourceLocation ExportLoc,
SourceLocation ImportLoc, Module *M,
ModuleIdPath Path = {});
/// The parser has processed a module import translated from a
/// #include or similar preprocessing directive.
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
/// The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// Create an implicit import of the given module at the given
/// source location, for error recovery, if possible.
///
/// This routine is typically used when an entity found by name lookup
/// is actually hidden within a module that we know about but the user
/// has forgotten to import.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
/// Kinds of missing import. Note, the values of these enumerators correspond
/// to %select values in diagnostics.
enum class MissingImportKind {
Declaration,
Definition,
DefaultArgument,
ExplicitSpecialization,
PartialSpecialization
};
/// Diagnose that the specified declaration needs to be visible but
/// isn't, and suggest a module import that would resolve the problem.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
MissingImportKind MIK, bool Recover = true);
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
SourceLocation DeclLoc, ArrayRef<Module *> Modules,
MissingImportKind MIK, bool Recover);
Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
SourceLocation LBraceLoc);
Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
SourceLocation RBraceLoc);
/// We've found a use of a templated declaration that would trigger an
/// implicit instantiation. Check that any relevant explicit specializations
/// and partial specializations are visible, and diagnose if not.
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
/// We've found a use of a template specialization that would select a
/// partial specialization. Check that the partial specialization is visible,
/// and diagnose if not.
void checkPartialSpecializationVisibility(SourceLocation Loc,
NamedDecl *Spec);
/// Retrieve a suitable printing policy for diagnostics.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// Retrieve a suitable printing policy for diagnostics.
static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
const Preprocessor &PP);
/// Scope actions.
void ActOnPopScope(SourceLocation Loc, Scope *S);
void ActOnTranslationUnitScope(Scope *S);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
RecordDecl *&AnonRecord);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation,
RecordDecl *&AnonRecord);
Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy);
Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record);
/// Common ways to introduce type names without a tag for use in diagnostics.
/// Keep in sync with err_tag_reference_non_tag.
enum NonTagKind {
NTK_NonStruct,
NTK_NonClass,
NTK_NonUnion,
NTK_NonEnum,
NTK_Typedef,
NTK_TypeAlias,
NTK_Template,
NTK_TypeAliasTemplate,
NTK_TemplateTemplateArgument,
};
/// Given a non-tag type declaration, returns an enum useful for indicating
/// what kind of non-tag type this is.
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
bool isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name);
enum TagUseKind {
TUK_Reference, // Reference to a tag: 'struct foo *X;'
TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
TUK_Friend // Friend declaration: 'friend struct foo;'
};
Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc, const ParsedAttributesView &Attr,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
bool &IsDependent, SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, bool IsTemplateParamOrArg,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TempParamLists);
TypeResult ActOnDependentTag(Scope *S,
unsigned TagSpec,
TagUseKind TUK,
const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation TagLoc,
SourceLocation NameLoc);
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl *> &Decls);
Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth);
FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS);
MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
SourceLocation DeclStart, Declarator &D,
Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
const ParsedAttr &MSPropertyAttr);
FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D = nullptr);
bool CheckNontrivialField(FieldDecl *FD);
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
enum TrivialABIHandling {
/// The triviality of a method unaffected by "trivial_abi".
TAH_IgnoreTrivialABI,
/// The triviality of a method affected by "trivial_abi".
TAH_ConsiderTrivialABI
};
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
bool Diagnose = false);
/// For a defaulted function, the kind of defaulted function that it is.
class DefaultedFunctionKind {
CXXSpecialMember SpecialMember : 8;
DefaultedComparisonKind Comparison : 8;
public:
DefaultedFunctionKind()
: SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
}
DefaultedFunctionKind(CXXSpecialMember CSM)
: SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
DefaultedFunctionKind(DefaultedComparisonKind Comp)
: SpecialMember(CXXInvalid), Comparison(Comp) {}
bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
bool isComparison() const {
return Comparison != DefaultedComparisonKind::None;
}
explicit operator bool() const {
return isSpecialMember() || isComparison();
}
CXXSpecialMember asSpecialMember() const { return SpecialMember; }
DefaultedComparisonKind asComparison() const { return Comparison; }
/// Get the index of this function kind for use in diagnostics.
unsigned getDiagnosticIndex() const {
static_assert(CXXInvalid > CXXDestructor,
"invalid should have highest index");
static_assert((unsigned)DefaultedComparisonKind::None == 0,
"none should be equal to zero");
return SpecialMember + (unsigned)Comparison;
}
};
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
return getDefaultedFunctionKind(MD).asSpecialMember();
}
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
return getDefaultedFunctionKind(FD).asComparison();
}
void ActOnLastBitfield(SourceLocation DeclStart,
SmallVectorImpl<Decl *> &AllIvarDecls);
Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind visibility);
// This is used for both record definitions and ObjC interface declarations.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
ArrayRef<Decl *> Fields, SourceLocation LBrac,
SourceLocation RBrac, const ParsedAttributesView &AttrList);
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
/// Perform ODR-like check for C/ObjC when merging tag types from modules.
/// Differently from C++, actually parse the body and reject / error out
/// in case of a structural mismatch.
bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
SkipBodyInfo &SkipBody);
typedef void *SkippedDefinitionContext;
/// Invoked when we enter a tag definition that we're skipping.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
/// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
/// C++ record definition's base-specifiers clause and are starting its
/// member declarations.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
SourceLocation LBraceLoc);
/// ActOnTagFinishDefinition - Invoked once we have finished parsing
/// the definition of a tag (enumeration, class, struct, or union).
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceRange BraceRange);
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
/// Invoked when we must temporarily exit the objective-c container
/// scope for parsing/looking-up C constructs.
///
/// Must be followed by a call to \see ActOnObjCReenterContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
void ActOnObjCReenterContainerContext(DeclContext *DC);
/// ActOnTagDefinitionError - Invoked when there was an unrecoverable
/// error parsing the definition of a tag.
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *val);
bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, bool IsFixed,
const EnumDecl *Prev);
/// Determine whether the body of an anonymous enumeration should be skipped.
/// \param II The name of the first enumerator.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc);
Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
SourceLocation IdLoc, IdentifierInfo *Id,
const ParsedAttributesView &Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
const ParsedAttributesView &Attr);
DeclContext *getContainingDC(DeclContext *DC);
/// Set the current declaration context until it gets popped.
void PushDeclContext(Scope *S, DeclContext *DC);
void PopDeclContext();
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void EnterDeclaratorContext(Scope *S, DeclContext *DC);
void ExitDeclaratorContext(Scope *S);
/// Push the parameters of D, which must be a function, into scope.
void ActOnReenterFunctionContext(Scope* S, Decl* D);
void ActOnExitFunctionContext();
DeclContext *getFunctionLevelDeclContext();
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *getCurFunctionDecl();
/// getCurMethodDecl - If inside of a method body, this returns a pointer to
/// the method decl for the method being parsed. If we're currently
/// in a 'block', this returns the containing context.
ObjCMethodDecl *getCurMethodDecl();
/// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
/// or C function we're in, otherwise return null. If we're currently
/// in a 'block', this returns the containing context.
NamedDecl *getCurFunctionOrMethodDecl();
/// Add this decl to the scope shadowed decl chains.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, allow the declaration to be in the
/// enclosing namespace set of the context, rather than contained
/// directly within it.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false);
/// Finds the scope corresponding to the given decl context, if it
/// happens to be an enclosing scope. Otherwise return NULL.
static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
/// Subroutines of ActOnDeclarator().
TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo);
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
/// Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// Don't merge availability attributes at all.
AMK_None,
/// Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override,
/// Merge availability attributes for an implementation of
/// a protocol requirement.
AMK_ProtocolImplementation,
};
/// Describes the kind of priority given to an availability attribute.
///
/// The sum of priorities deteremines the final priority of the attribute.
/// The final priority determines how the attribute will be merged.
/// An attribute with a lower priority will always remove higher priority
/// attributes for the specified platform when it is being applied. An
/// attribute with a higher priority will not be applied if the declaration
/// already has an availability attribute with a lower priority for the
/// specified platform. The final prirority values are not expected to match
/// the values in this enumeration, but instead should be treated as a plain
/// integer value. This enumeration just names the priority weights that are
/// used to calculate that final vaue.
enum AvailabilityPriority : int {
/// The availability attribute was specified explicitly next to the
/// declaration.
AP_Explicit = 0,
/// The availability attribute was applied using '#pragma clang attribute'.
AP_PragmaClangAttribute = 1,
/// The availability attribute for a specific platform was inferred from
/// an availability attribute for another platform.
AP_InferredFromOtherPlatform = 2
};
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *
mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
IdentifierInfo *Platform, bool Implicit,
VersionTuple Introduced, VersionTuple Deprecated,
VersionTuple Obsoleted, bool IsUnavailable,
StringRef Message, bool IsStrict, StringRef Replacement,
AvailabilityMergeKind AMK, int Priority);
TypeVisibilityAttr *
mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
TypeVisibilityAttr::VisibilityType Vis);
VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
VisibilityAttr::VisibilityType Vis);
UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Uuid);
DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
const AttributeCommonInfo &CI,
bool BestCase,
MSInheritanceModel Model);
FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
IdentifierInfo *Format, int FormatIdx,
int FirstArg);
SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name);
CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
const AttributeCommonInfo &CI,
const IdentifierInfo *Ident);
MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
NoSpeculativeLoadHardeningAttr *
mergeNoSpeculativeLoadHardeningAttr(Decl *D,
const NoSpeculativeLoadHardeningAttr &AL);
SpeculativeLoadHardeningAttr *
mergeSpeculativeLoadHardeningAttr(Decl *D,
const SpeculativeLoadHardeningAttr &AL);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
const AttributeCommonInfo &CI);
SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const AttributeCommonInfo &CI,
StringRef Name, bool Override);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
const InternalLinkageAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL);
CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL);
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
LookupResult &OldDecls);
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
bool MergeTypeWithOld);
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld);
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
void MergeVarDecl(VarDecl *New, LookupResult &Previous);
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
// AssignmentAction - This is used by all the assignment diagnostic functions
// to represent what is actually causing the operation
enum AssignmentAction {
AA_Assigning,
AA_Passing,
AA_Returning,
AA_Converting,
AA_Initializing,
AA_Sending,
AA_Casting,
AA_Passing_CFAudited
};
/// C++ Overloading.
enum OverloadKind {
/// This is a legitimate overload: the existing declarations are
/// functions or function templates with different signatures.
Ovl_Overload,
/// This is not an overload because the signature exactly matches
/// an existing declaration.
Ovl_Match,
/// This is not an overload because the lookup results contain a
/// non-function.
Ovl_NonFunction
};
OverloadKind CheckOverload(Scope *S,
FunctionDecl *New,
const LookupResult &OldDecls,
NamedDecl *&OldDecl,
bool IsForUsingDecl);
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
bool ConsiderCudaAttrs = true);
ImplicitConversionSequence
TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion);
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
bool IsComplexPromotion(QualType FromType, QualType ToType);
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType);
bool IsBlockPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType);
bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
const FunctionProtoType *NewType,
unsigned *ArgPos = nullptr);
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
QualType FromType, QualType ToType);
void maybeExtendBlockObject(ExprResult &E);
CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
bool CheckPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath& BasePath,
bool IgnoreBaseAccess,
bool Diagnose = true);
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType &ConvertedType);
bool CheckMemberPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath &BasePath,
bool IgnoreBaseAccess);
bool IsQualificationConversion(QualType FromType, QualType ToType,
bool CStyle, bool &ObjCLifetimeConversion);
bool IsFunctionConversion(QualType FromType, QualType ToType,
QualType &ResultTy);
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const VarDecl *NRVOCandidate,
QualType ResultType,
Expr *Value,
bool AllowNRVO = true);
bool CanPerformAggregateInitializationForOverloadResolution(
const InitializedEntity &Entity, InitListExpr *From);
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList = false,
bool AllowExplicit = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
CXXMethodDecl *Method);
/// Check that the lifetime of the initializer (and its subobjects) is
/// sufficient for initializing the entity, and perform lifetime extension
/// (when permitted) if not.
void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
ExprResult PerformContextuallyConvertToBool(Expr *From);
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
/// Contexts in which a converted constant expression is required.
enum CCEKind {
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator.
CCEK_ConstexprIf, ///< Condition in a constexpr if statement.
CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE);
/// Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
class ContextualImplicitConverter {
public:
bool Suppress;
bool SuppressConversion;
ContextualImplicitConverter(bool Suppress = false,
bool SuppressConversion = false)
: Suppress(Suppress), SuppressConversion(SuppressConversion) {}
/// Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// Emits a diagnostic when we picked a conversion function
/// (for cases when we are not allowed to pick a conversion function).
virtual SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
virtual ~ContextualImplicitConverter() {}
};
class ICEConvertDiagnoser : public ContextualImplicitConverter {
bool AllowScopedEnumerations;
public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,
bool Suppress, bool SuppressConversion)
: ContextualImplicitConverter(Suppress, SuppressConversion),
AllowScopedEnumerations(AllowScopedEnumerations) {}
/// Match an integral or (possibly scoped) enumeration type.
bool match(QualType T) override;
SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
return diagnoseNotInt(S, Loc, T);
}
/// Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
};
/// Perform a contextual implicit conversion.
ExprResult PerformContextualImplicitConversion(
SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
enum ObjCSubscriptKind {
OS_Array,
OS_Dictionary,
OS_Error
};
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
// Note that LK_String is intentionally after the other literals, as
// this is used for diagnostics logic.
enum ObjCLiteralKind {
LK_Array,
LK_Dictionary,
LK_Numeric,
LK_Boxed,
LK_String,
LK_Block,
LK_None
};
ObjCLiteralKind CheckLiteralKind(Expr *FromE);
ExprResult PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member);
// Members have to be NamespaceDecl* or TranslationUnitDecl*.
// TODO: make this is a typesafe union.
typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
using ADLCallKind = CallExpr::ADLCallKind;
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = true,
bool AllowExplicitConversion = false,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
ConversionSequenceList EarlyConversions = None,
OverloadCandidateParamOrder PO = {});
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool FirstArgumentIsBase = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false,
OverloadCandidateParamOrder PO = {});
void AddMethodCandidate(CXXMethodDecl *Method,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
ConversionSequenceList EarlyConversions = None,
OverloadCandidateParamOrder PO = {});
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
OverloadCandidateParamOrder PO = {});
void AddTemplateOverloadCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
bool PartialOverloading = false, bool AllowExplicit = true,
ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
OverloadCandidateParamOrder PO = {});
bool CheckNonDependentConversions(
FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
ConversionSequenceList &Conversions, bool SuppressUserConversions,
CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
Expr::Classification ObjectClassification = {},
OverloadCandidateParamOrder PO = {});
void AddConversionCandidate(
CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddTemplateConversionCandidate(
FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
bool AllowExplicit, bool AllowResultConversion = true);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddNonMemberOperatorCandidates(
const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
OverloadCandidateParamOrder PO = {});
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddArgumentDependentLookupCandidates(DeclarationName Name,
SourceLocation Loc,
ArrayRef<Expr *> Args,
TemplateArgumentListInfo *ExplicitTemplateArgs,
OverloadCandidateSet& CandidateSet,
bool PartialOverloading = false);
// Emit as a 'note' the specific overload candidate
void NoteOverloadCandidate(
NamedDecl *Found, FunctionDecl *Fn,
OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
QualType DestType = QualType(), bool TakingAddress = false);
// Emit as a series of 'note's all template and non-templates identified by
// the expression Expr
void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
bool TakingAddress = false);
/// Check the enable_if expressions on the given function. Returns the first
/// failing attribute, or NULL if they were all successful.
EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
bool MissingImplicitThis = false);
/// Find the failed Boolean condition within a given Boolean
/// constant expression, and describe it with a string.
std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// non-ArgDependent DiagnoseIfAttrs.
///
/// Argument-dependent diagnose_if attributes should be checked each time a
/// function is used as a direct callee of a function call.
///
/// Returns true if any errors were emitted.
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
const Expr *ThisArg,
ArrayRef<const Expr *> Args,
SourceLocation Loc);
/// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
/// ArgDependent DiagnoseIfAttrs.
///
/// Argument-independent diagnose_if attributes should be checked on every use
/// of a function.
///
/// Returns true if any errors were emitted.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
SourceLocation Loc);
/// Returns whether the given function's address can be taken or not,
/// optionally emitting a diagnostic if the address can't be taken.
///
/// Returns false if taking the address of the function is illegal.
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
bool Complain = false,
SourceLocation Loc = SourceLocation());
// [PossiblyAFunctionType] --> [Return]
// NonFunctionType --> NonFunctionType
// R (A) --> R(A)
// R (*)(A) --> R (A)
// R (&)(A) --> R (A)
// R (S::*)(A) --> R (A)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
QualType TargetType,
bool Complain,
DeclAccessPair &Found,
bool *pHadMultipleCandidates = nullptr);
FunctionDecl *
resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
DeclAccessPair &FoundResult);
bool resolveAndFixAddressOfOnlyViableOverloadCandidate(
ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
bool Complain = false,
DeclAccessPair *Found = nullptr);
bool ResolveAndFixSingleFunctionTemplateSpecialization(
ExprResult &SrcExpr,
bool DoFunctionPointerConverion = false,
bool Complain = false,
SourceRange OpRangeForComplaining = SourceRange(),
QualType DestTypeForComplaining = QualType(),
unsigned DiagIDForComplaining = 0);
Expr *FixOverloadedFunctionReference(Expr *E,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
ExprResult FixOverloadedFunctionReference(ExprResult,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
// An enum used to represent the different possible results of building a
// range-based for loop.
enum ForRangeStatus {
FRS_Success,
FRS_NoViableFunction,
FRS_DiagnosticIssued
};
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
SourceLocation RangeLoc,
const DeclarationNameInfo &NameInfo,
LookupResult &MemberLookup,
OverloadCandidateSet *CandidateSet,
Expr *Range, ExprResult *CallExpr);
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
UnresolvedLookupExpr *ULE,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
Expr *ExecConfig,
bool AllowTypoCorrection=true,
bool CalleesAddressIsTaken=false);
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
MultiExprArg Args, SourceLocation RParenLoc,
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
UnaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *input, bool RequiresADL = true);
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
OverloadedOperatorKind Op,
const UnresolvedSetImpl &Fns,
ArrayRef<Expr *> Args, bool RequiresADL = true);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
BinaryOperatorKind Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS,
bool RequiresADL = true,
bool AllowRewrittenCandidates = true,
FunctionDecl *DefaultedFn = nullptr);
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS,
FunctionDecl *DefaultedFn);
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
SourceLocation RLoc,
Expr *Base,Expr *Idx);
ExprResult
BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool *NoArrowOperatorFound = nullptr);
/// CheckCallReturnType - Checks that a call expression's return type is
/// complete. Returns true on failure. The location passed in is the location
/// that best represents the call.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD);
/// Helpers for dealing with blocks and functions.
bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
bool CheckParameterNames);
void CheckCXXDefaultArguments(FunctionDecl *FD);
void CheckExtraCXXDefaultArguments(Declarator &D);
Scope *getNonFieldDeclScope(Scope *S);
/// \name Name lookup
///
/// These routines provide name lookup that is used during semantic
/// analysis to resolve the various kinds of names (identifiers,
/// overloaded operator names, constructor names, etc.) into zero or
/// more declarations within a particular scope. The major entry
/// points are LookupName, which performs unqualified name lookup,
/// and LookupQualifiedName, which performs qualified name lookup.
///
/// All name lookup is performed based on some specific criteria,
/// which specify what names will be visible to name lookup and how
/// far name lookup should work. These criteria are important both
/// for capturing language semantics (certain lookups will ignore
/// certain names, for example) and for performance, since name
/// lookup is often a bottleneck in the compilation of C++. Name
/// lookup criteria is specified via the LookupCriteria enumeration.
///
/// The results of name lookup can vary based on the kind of name
/// lookup performed, the current language, and the translation
/// unit. In C, for example, name lookup will either return nothing
/// (no entity found) or a single declaration. In C++, name lookup
/// can additionally refer to a set of overloaded functions or
/// result in an ambiguity. All of the possible results of name
/// lookup are captured by the LookupResult class, which provides
/// the ability to distinguish among them.
//@{
/// Describes the kind of name lookup to perform.
enum LookupNameKind {
/// Ordinary name lookup, which finds ordinary names (functions,
/// variables, typedefs, etc.) in C and most kinds of names
/// (functions, variables, members, types, etc.) in C++.
LookupOrdinaryName = 0,
/// Tag name lookup, which finds the names of enums, classes,
/// structs, and unions.
LookupTagName,
/// Label name lookup.
LookupLabel,
/// Member name lookup, which finds the names of
/// class/struct/union members.
LookupMemberName,
/// Look up of an operator name (e.g., operator+) for use with
/// operator overloading. This lookup is similar to ordinary name
/// lookup, but will ignore any declarations that are class members.
LookupOperatorName,
/// Look up of a name that precedes the '::' scope resolution
/// operator in C++. This lookup completely ignores operator, object,
/// function, and enumerator names (C++ [basic.lookup.qual]p1).
LookupNestedNameSpecifierName,
/// Look up a namespace name within a C++ using directive or
/// namespace alias definition, ignoring non-namespace names (C++
/// [basic.lookup.udir]p1).
LookupNamespaceName,
/// Look up all declarations in a scope with the given name,
/// including resolved using declarations. This is appropriate
/// for checking redeclarations for a using declaration.
LookupUsingDeclName,
/// Look up an ordinary name that is going to be redeclared as a
/// name with linkage. This lookup ignores any declarations that
/// are outside of the current scope unless they have linkage. See
/// C99 6.2.2p4-5 and C++ [basic.link]p6.
LookupRedeclarationWithLinkage,
/// Look up a friend of a local class. This lookup does not look
/// outside the innermost non-class scope. See C++11 [class.friend]p11.
LookupLocalFriendName,
/// Look up the name of an Objective-C protocol.
LookupObjCProtocolName,
/// Look up implicit 'self' parameter of an objective-c method.
LookupObjCImplicitSelfParam,
/// Look up the name of an OpenMP user-defined reduction operation.
LookupOMPReductionName,
/// Look up the name of an OpenMP user-defined mapper.
LookupOMPMapperName,
/// Look up any declaration with any name.
LookupAnyName
};
/// Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists and is visible.
ForVisibleRedeclaration,
/// The lookup results will be used for redeclaration of a name
/// with external linkage; non-visible lookup results with external linkage
/// may also be found.
ForExternalRedeclaration
};
RedeclarationKind forRedeclarationInCurContext() {
// A declaration with an owning module for linkage can never link against
// anything that is not visible. We don't need to check linkage here; if
// the context has internal linkage, redeclaration lookup won't find things
// from other TUs, and we can't safely compute linkage yet in general.
if (cast<Decl>(CurContext)
->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
return ForVisibleRedeclaration;
return ForExternalRedeclaration;
}
/// The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// The lookup resulted in an error.
LOLR_Error,
/// The lookup found no match but no diagnostic was issued.
LOLR_ErrorNoDiagnostic,
/// The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// The lookup found an overload set of literal operator templates,
/// which expect the characters of the spelling of the literal token to be
/// passed as a non-type template argument pack.
LOLR_Template,
/// The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
LOLR_StringTemplate
};
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
CXXSpecialMember SM,
bool ConstArg,
bool VolatileArg,
bool RValueThis,
bool ConstThis,
bool VolatileThis);
typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
TypoRecoveryCallback;
private:
bool CppLookupName(LookupResult &R, Scope *S);
struct TypoExprState {
std::unique_ptr<TypoCorrectionConsumer> Consumer;
TypoDiagnosticGenerator DiagHandler;
TypoRecoveryCallback RecoveryHandler;
TypoExprState();
TypoExprState(TypoExprState &&other) noexcept;
TypoExprState &operator=(TypoExprState &&other) noexcept;
};
/// The set of unhandled TypoExprs and their associated state.
llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC);
// The set of known/encountered (unique, canonicalized) NamespaceDecls.
//
// The boolean value will be true to indicate that the namespace was loaded
// from an AST/PCH file, or false otherwise.
llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
/// Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// Helper for CorrectTypo and CorrectTypoDelayed used to create and
/// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
/// should be skipped entirely.
std::unique_ptr<TypoCorrectionConsumer>
makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// Look up a name, looking for a single declaration. Return
/// null if the results were absent, ambiguous, or overloaded.
///
/// It is preferable to use the elaborated form and explicitly handle
/// ambiguity and overloaded.
NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
SourceLocation Loc,
LookupNameKind NameKind,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupBuiltin(LookupResult &R);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
bool InUnqualifiedLookup = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
CXXScopeSpec &SS);
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
bool AllowBuiltinCreation = false,
bool EnteringContext = false);
ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
QualType T1, QualType T2,
UnresolvedSetImpl &Functions);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
SourceLocation GnuLabelLoc = SourceLocation());
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
ArrayRef<QualType> ArgTys,
bool AllowRaw,
bool AllowTemplate,
bool AllowStringTemplate,
bool DiagnoseMissing);
bool isKnownName(StringRef name);
/// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
enum class FunctionEmissionStatus {
Emitted,
CUDADiscarded, // Discarded due to CUDA/HIP hostness
OMPDiscarded, // Discarded due to OpenMP hostness
TemplateDiscarded, // Discarded due to uninstantiated templates
Unknown,
};
FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl);
// Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool LoadExternal = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true,
bool IncludeDependentBases = false,
bool LoadExternal = true);
enum CorrectTypoKind {
CTK_NonError, // CorrectTypo used in a non error recovery situation.
CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
};
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr,
bool RecordFailure = true);
TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// Process any TypoExprs in the given Expr and its children,
/// generating diagnostics as appropriate and returning a new Expr if there
/// were typos that were all successfully corrected and ExprError if one or
/// more typos could not be corrected.
///
/// \param E The Expr to check for TypoExprs.
///
/// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
/// initializer.
///
/// \param Filter A function applied to a newly rebuilt Expr to determine if
/// it is an acceptable/usable result from a single combination of typo
/// corrections. As long as the filter returns ExprError, different
/// combinations of corrections will be tried until all are exhausted.
ExprResult
CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; });
ExprResult
CorrectDelayedTyposInExpr(Expr *E,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(E, nullptr, Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; }) {
return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
}
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
bool ErrorRecovery = true);
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
const PartialDiagnostic &PrevNote,
bool ErrorRecovery = true);
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
void DiagnoseAmbiguousLookup(LookupResult &Result);
//@}
ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool TypoCorrection = false);
NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc);
NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
Scope *S);
void AddKnownFunctionAttributes(FunctionDecl *FD);
// More parsing and symbol table subroutines.
void ProcessPragmaWeak(Scope *S, Decl *D);
// Decl attributes - this routine is the top level dispatcher.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
// Helper for delayed processing of attributes.
void ProcessDeclAttributeDelayed(Decl *D,
const ParsedAttributesView &AttrList);
void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const ParsedAttributesView &AttrList);
void checkUnusedDeclAttributes(Declarator &D);
/// Map any API notes provided for this declaration to attributes on the
/// declaration.
///
/// Triggered by declaration-attribute processing.
void ProcessAPINotes(Decl *D);
/// Determine if type T is a valid subject for a nonnull and similar
/// attributes. By default, we look through references (the behavior used by
/// nonnull), but if the second parameter is true, then we treat a reference
/// type as valid.
bool isValidPointerAttrType(QualType T, bool RefOkay = false);
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckAttrTarget(const ParsedAttr &CurrAttr);
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceModel SemanticSpelling);
void CheckAlignasUnderalignment(Decl *D);
/// Adjust the calling convention of a method to be the ABI default if it
/// wasn't specified explicitly. This handles method types formed from
/// function type typedefs and typename template arguments.
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
SourceLocation Loc);
// Check if there is an explicit attribute, but only look through parens.
// The intent is to look for an attribute on the current declarator, but not
// one that came from a typedef.
bool hasExplicitCallingConv(QualType T);
/// Get the outermost AttributedType node that sets a calling convention.
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
/// Check whether a nullability type specifier can be added to the given
/// type through some means not written in source (e.g. API notes).
///
/// \param type The type to which the nullability specifier will be
/// added. On success, this type will be updated appropriately.
///
/// \param nullability The nullability specifier to add.
///
/// \param diagLoc The location to use for diagnostics.
///
/// \param allowArrayTypes Whether to accept nullability specifiers on an
/// array type (e.g., because it will decay to a pointer).
///
/// \param overrideExisting Whether to override an existing, locally-specified
/// nullability specifier rather than complaining about the conflict.
///
/// \returns true if nullability cannot be applied, false otherwise.
bool checkImplicitNullabilityTypeSpecifier(QualType &type,
NullabilityKind nullability,
SourceLocation diagLoc,
bool allowArrayTypes,
bool overrideExisting);
/// Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt,
const ParsedAttributesView &Attrs,
SourceRange Range);
void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl);
/// WarnExactTypedMethods - This routine issues a warning if method
/// implementation declaration matches exactly that of its declaration.
void WarnExactTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
/// CheckImplementationIvars - This routine checks if the instance variables
/// listed in the implelementation match those listed in the interface.
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **Fields, unsigned nIvars,
SourceLocation Loc);
/// ImplMethodsVsClassMethods - This is main routine to warn if any method
/// remains unimplemented in the class or category \@implementation.
void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool IncompleteImpl = false);
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// Diagnose any null-resettable synthesized setters.
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
ObjCInterfaceDecl *IDecl,
SourceLocation AtEnd);
void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
ObjCMethodDecl *Method, ObjCIvarDecl *IV);
/// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
/// backs the property is not used in the property's accessor.
void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD);
/// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
/// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
/// It also returns ivar's property on success.
ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const;
/// Called by ActOnProperty to handle \@property declarations in
/// class extensions.
ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
unsigned &Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
/// handle creating the ObjcPropertyDecl for a category or \@interface.
ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
ObjCContainerDecl *CDecl,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
SourceLocation GetterNameLoc,
Selector SetterSel,
SourceLocation SetterNameLoc,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
/// AtomicPropertySetterGetterRules - This routine enforces the rule (via
/// warning) when atomic property has one but not the other user-declared
/// setter or getter.
void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
ObjCInterfaceDecl* IDecl);
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
void DiagnoseMissingDesignatedInitOverrides(
const ObjCImplementationDecl *ImplD,
const ObjCInterfaceDecl *IFD);
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
enum MethodMatchStrategy {
MMS_loose,
MMS_strict
};
/// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
/// true, or false, accordingly.
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
const ObjCMethodDecl *PrevMethod,
MethodMatchStrategy strategy = MMS_strict);
/// MatchAllMethodDeclarations - Check methods declaraed in interface or
/// or protocol against those declared in their implementations.
void MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl=false);
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
/// category matches with those implemented in its primary class and
/// warns each time an exact match is found.
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
/// Add the given method to the list of globally-known methods.
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
/// Returns default addr space for method qualifiers.
LangAS getDefaultCXXMethodAddrSpace() const;
private:
/// AddMethodToGlobalPool - Add an instance or factory method to the global
/// pool. See descriptoin of AddInstanceMethodToGlobalPool.
void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
/// LookupMethodInGlobalPool - Returns the instance or factory method and
/// optionally warns if there are multiple signatures.
ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance);
public:
/// - Returns instance or factory methods in global method pool for
/// given selector. It checks the desired kind first, if none is found, and
/// parameter checkTheOther is set, it then checks the other kind. If no such
/// method or only one method is found, function returns false; otherwise, it
/// returns true.
bool
CollectMultipleMethodsInGlobalPool(Selector Sel,
SmallVectorImpl<ObjCMethodDecl*>& Methods,
bool InstanceFirst, bool CheckTheOther,
const ObjCObjectType *TypeBound = nullptr);
bool
AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
SourceRange R, bool receiverIdOrClass,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
void
DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass);
private:
/// - Returns a selector which best matches given argument list or
/// nullptr if none could be found
ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
bool IsInstance,
SmallVectorImpl<ObjCMethodDecl*>& Methods);
/// Record the typo correction failure and return an empty correction.
TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
bool RecordFailure = true) {
if (RecordFailure)
TypoCorrectionFailures[Typo].insert(TypoLoc);
return TypoCorrection();
}
public:
/// AddInstanceMethodToGlobalPool - All instance methods in a translation
/// unit are added to a global pool. This allows us to efficiently associate
/// a selector with a method declaraation for purposes of typechecking
/// messages sent to "id" (where the class of the object is unknown).
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/true);
}
/// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/false);
}
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
/// pool.
void AddAnyMethodToGlobalPool(Decl *D);
/// LookupInstanceMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/true);
}
/// LookupFactoryMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/false);
}
const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType=QualType());
/// LookupImplementedMethodInGlobalPool - Returns the method which has an
/// implementation.
ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
/// initialization.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars);
//===--------------------------------------------------------------------===//
// Statement Parsing Callbacks: SemaStmt.cpp.
public:
class FullExprArg {
public:
FullExprArg() : E(nullptr) { }
FullExprArg(Sema &actions) : E(nullptr) { }
ExprResult release() {
return E;
}
Expr *get() const { return E; }
Expr *operator->() {
return E;
}
private:
// FIXME: No need to make the entire Sema class a friend when it's just
// Sema::MakeFullExpr that needs access to the constructor below.
friend class Sema;
explicit FullExprArg(Expr *expr) : E(expr) {}
Expr *E;
};
FullExprArg MakeFullExpr(Expr *Arg) {
return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
}
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
return FullExprArg(
ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
StmtResult ActOnExprStmtError();
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt(bool IsStmtExpr);
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
S.ActOnStartOfCompoundStmt(IsStmtExpr);
}
~CompoundScopeRAII() {
S.ActOnFinishOfCompoundStmt();
}
private:
Sema &S;
};
/// An RAII helper that pops function a function scope on exit.
struct FunctionScopeRAII {
Sema &S;
bool Active;
FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAII() {
if (Active)
S.PopFunctionScopeInfo();
}
void disable() { Active = false; }
};
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
StmtResult ActOnForEachLValueExpr(Expr *E);
ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
SourceLocation DotDotDotLoc, ExprResult RHS,
SourceLocation ColonLoc);
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
SourceLocation ColonLoc,
Stmt *SubStmt, Scope *CurScope);
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
SourceLocation ColonLoc, Stmt *SubStmt);
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
ArrayRef<const Attr*> Attrs,
Stmt *SubStmt);
class ConditionResult;
StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
Stmt *InitStmt,
ConditionResult Cond, Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
Stmt *InitStmt,
ConditionResult Cond);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
Stmt *Body);
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
SourceLocation WhileLoc, SourceLocation CondLParen,
Expr *Cond, SourceLocation CondRParen);
StmtResult ActOnForStmt(SourceLocation ForLoc,
SourceLocation LParenLoc,
Stmt *First,
ConditionResult Second,
FullExprArg Third,
SourceLocation RParenLoc,
Stmt *Body);
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection);
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc);
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
enum BuildForRangeKind {
/// Initial building of a for-range statement.
BFRK_Build,
/// Instantiation or recovery rebuild of a for-range statement. Don't
/// attempt any typo-correction.
BFRK_Rebuild,
/// Determining whether a for-range statement could be built. Avoid any
/// unnecessary or irreversible actions.
BFRK_Check
};
StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
Stmt *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation CoawaitLoc,
Stmt *InitStmt,
SourceLocation ColonLoc,
Stmt *RangeDecl, Stmt *Begin, Stmt *End,
Expr *Cond, Expr *Inc,
Stmt *LoopVarDecl,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl);
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
SourceLocation StarLoc,
Expr *DestExp);
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind, unsigned NumParams);
typedef std::pair<StringRef, QualType> CapturedParamNameType;
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind,
ArrayRef<CapturedParamNameType> Params,
unsigned OpenMPCaptureLevel = 0);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
enum CopyElisionSemanticsKind {
CES_Strict = 0,
CES_AllowParameters = 1,
CES_AllowDifferentTypes = 2,
CES_AllowExceptionVariables = 4,
CES_FormerDefault = (CES_AllowParameters),
CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes),
CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes |
CES_AllowExceptionVariables),
};
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
CopyElisionSemanticsKind CESK);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
CopyElisionSemanticsKind CESK);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg Constraints, MultiExprArg Exprs,
Expr *AsmString, MultiExprArg Clobbers,
unsigned NumLabels,
SourceLocation RParenLoc);
void FillInlineAsmIdentifierInfo(Expr *Res,
llvm::InlineAsmIdentifierInfo &Info);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
SourceLocation AsmLoc);
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc);
LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate);
VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Invalid = false);
Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
Decl *Parm, Stmt *Body);
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg Catch, Stmt *Finally);
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope);
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand);
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SynchExpr,
Stmt *SynchBody);
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id);
Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
Decl *ExDecl, Stmt *HandlerBlock);
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
ArrayRef<Stmt *> Handlers);
StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
Expr *FilterExpr,
Stmt *Block);
void ActOnStartSEHFinallyBlock();
void ActOnAbortSEHFinallyBlock();
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
/// If it's a file scoped decl that must warn if not used, keep track
/// of it.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
/// DiagnoseUnusedExprResult - If the statement passed in is an expression
/// whose result is unused, warn.
void DiagnoseUnusedExprResult(const Stmt *S);
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
void DiagnoseUnusedDecl(const NamedDecl *ND);
/// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
/// statement as a \p Body, and it is located on the same line.
///
/// This helps prevent bugs due to typos, such as:
/// if (condition);
/// do_stuff();
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID);
/// Warn if a for/while loop statement \p S, which is followed by
/// \p PossibleBody, has a suspicious null statement as a body.
void DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody);
/// Warn if a value is moved to itself.
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc);
/// Warn if we're implicitly casting from a _Nullable pointer type to a
/// _Nonnull one.
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
SourceLocation Loc);
/// Warn when implicitly casting 0 to nullptr.
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
return DelayedDiagnostics.push(pool);
}
void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
typedef ProcessingContextState ParsingClassState;
ParsingClassState PushParsingClass() {
ParsingClassDepth++;
return DelayedDiagnostics.pushUndelayed();
}
void PopParsingClass(ParsingClassState state) {
ParsingClassDepth--;
DelayedDiagnostics.popUndelayed(state);
}
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass,
bool ObjCPropertyAccess,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReceiver = nullptr);
bool makeUnavailableInSystemHeader(SourceLocation loc,
UnavailableAttr::ImplicitReason reason);
/// Issue any -Wunguarded-availability warnings in \c FD
void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
//===--------------------------------------------------------------------===//
// Expression Parsing Callbacks: SemaExpr.cpp.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
bool ObjCPropertyAccess = false,
bool AvoidPartialAvailabilityChecks = false,
ObjCInterfaceDecl *ClassReciever = nullptr);
void NoteDeletedFunction(FunctionDecl *FD);
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(
ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
ExpressionEvaluationContextRecord::ExpressionKind Type =
ExpressionEvaluationContextRecord::EK_Other);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
ExprResult CheckUnevaluatedOperand(Expr *E);
void CheckUnusedVolatileAssignment(Expr *E);
ExprResult ActOnConstantExpression(ExprResult Res);
// Functions for marking a declaration referenced. These functions also
// contain the relevant logic for marking if a reference to a function or
// variable is an odr-use (in the C++11 sense). There are separate variants
// for expressions referring to a decl; these exist because odr-use marking
// needs to be delayed for some constant variables when we build one of the
// named expressions.
//
// MightBeOdrUse indicates whether the use could possibly be an odr-use, and
// should usually be true. This only needs to be set to false if the lack of
// odr-use cannot be determined from the current context (for instance,
// because the name denotes a virtual function and was written without an
// explicit nested-name-specifier).
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool MightBeOdrUse = true);
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
void MarkMemberReferenced(MemberExpr *E);
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
unsigned CapturingScopeIndex);
ExprResult CheckLValueToRValueConversionOperand(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// Try to capture the given variable.
///
/// \param Var The variable to capture.
///
/// \param Loc The location at which the capture occurs.
///
/// \param Kind The kind of capture, which may be implicit (for either a
/// block or a lambda), or explicit by-value or by-reference (for a lambda).
///
/// \param EllipsisLoc The location of the ellipsis, if one is provided in
/// an explicit lambda capture.
///
/// \param BuildAndDiagnose Whether we are actually supposed to add the
/// captures or diagnose errors. If false, this routine merely check whether
/// the capture can occur without performing the capture itself or complaining
/// if the variable cannot be captured.
///
/// \param CaptureType Will be set to the type of the field used to capture
/// this variable in the innermost block or lambda. Only valid when the
/// variable can be captured.
///
/// \param DeclRefType Will be set to the type of a reference to the capture
/// from within the current scope. Only valid when the variable can be
/// captured.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// variables that may or may not be used in certain specializations of
/// a nested generic lambda.
///
/// \returns true if an error occurred (i.e., the variable cannot be
/// captured) and false if the capture succeeded.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const unsigned *const FunctionScopeIndexToStopAt);
/// Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// Given a variable, determine the type that a reference to that
/// variable will have in the given scope.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
/// Mark all of the declarations referenced within a particular AST node as
/// referenced. Used when template instantiation instantiates a non-dependent
/// type -- entities referenced by the type are now referenced.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
void MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables = false);
/// Try to recover by turning the given expression into a
/// call. Returns true if recovery was attempted or an error was
/// emitted; this may also leave the ExprResult invalid.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain = false,
bool (*IsPlausibleResult)(QualType) = nullptr);
/// Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// Conditionally issue a diagnostic based on the current
/// evaluation context.
///
/// \param Statement If Statement is non-null, delay reporting the
/// diagnostic until the function body is parsed, and then do a basic
/// reachability analysis to determine if the statement is reachable.
/// If it is unreachable, the diagnostic will not be emitted.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD);
/// Similar, but diagnostic is only produced if all the specified statements
/// are reachable.
bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
const PartialDiagnostic &PD);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
CorrectionCandidateCallback *CCC = nullptr,
bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
void DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
CorrectionCandidateCallback &CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
IdentifierInfo *II);
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
IdentifierInfo *II,
bool AllowBuiltinCreation=false);
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool isAddressOfOperand,
const TemplateArgumentListInfo *TemplateArgs);
/// If \p D cannot be odr-used in the current expression evaluation context,
/// return a reason explaining why. Otherwise, return NOUR_None.
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
DeclRefExpr *
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
NestedNameSpecifierLoc NNS,
NamedDecl *FoundD = nullptr,
SourceLocation TemplateKWLoc = SourceLocation(),
const TemplateArgumentListInfo *TemplateArgs = nullptr);
ExprResult
BuildAnonymousStructUnionMemberReference(
const CXXScopeSpec &SS,
SourceLocation nameLoc,
IndirectFieldDecl *indirectField,
DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool IsDefiniteInstance,
const Scope *S);
bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen);
ExprResult
BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, const Scope *S,
TypeSourceInfo **RecoveryTSI = nullptr);
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R,
bool NeedsADL,
bool AcceptInvalidDecl = false);
ExprResult BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr,
bool AcceptInvalidDecl = false);
ExprResult BuildLiteralOperatorCall(LookupResult &R,
DeclarationNameInfo &SuffixInfo,
ArrayRef<Expr *> Args,
SourceLocation LitEndLoc,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
ExprResult BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentKind IK);
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
ExprResult ActOnCharacterConstant(const Token &Tok,
Scope *UDLScope = nullptr);
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
ExprResult ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val);
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz").
ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
Scope *UDLScope = nullptr);
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs);
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs);
// Binary/Unary Operators. 'Tok' is the token for the operator.
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
Expr *InputExpr);
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input);
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input);
bool isQualifiedMemberAccess(Expr *E);
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R);
ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind);
ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
bool IsType, void *TyOrEx,
SourceRange ArgRange);
ExprResult CheckPlaceholderExpr(Expr *E);
bool CheckVecStepExpr(Expr *E);
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind);
ExprResult ActOnSizeofParameterPackExpr(Scope *S,
SourceLocation OpLoc,
IdentifierInfo &Name,
SourceLocation NameLoc,
SourceLocation RParenLoc);
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input);
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
Expr *LowerBound, SourceLocation ColonLoc,
Expr *Length, SourceLocation RBLoc);
// This struct is for use by ActOnMemberAccess to allow
// BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
// changing the access operator from a '.' to a '->' (to see if that is the
// change needed to fix an error about an unknown member, e.g. when the class
// defines a custom operator->).
struct ActOnMemberAccessExtraArgs {
Scope *S;
UnqualifiedId &Id;
Decl *ObjCImpDecl;
};
ExprResult BuildMemberReferenceExpr(
Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult
BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
bool IsArrow, const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
const Scope *S,
bool SuppressQualifierCheck = false,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
SourceLocation OpLoc,
const CXXScopeSpec &SS, FieldDecl *Field,
DeclAccessPair FoundDecl,
const DeclarationNameInfo &MemberNameInfo);
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
const CXXScopeSpec &SS,
const LookupResult &R);
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Member,
Decl *ObjCImpDecl);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
MemberExpr *
BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
ValueDecl *Member, DeclAccessPair FoundDecl,
bool HadMultipleCandidates,
const DeclarationNameInfo &MemberNameInfo, QualType Ty,
ExprValueKind VK, ExprObjectKind OK,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool ExecConfig = false);
void CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr);
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr);
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
bool IsExecConfig = false);
enum class AtomicArgumentOrder { API, AST };
ExprResult
BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
SourceLocation RParenLoc, MultiExprArg Args,
AtomicExpr::AtomicOp Op,
AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
ExprResult
BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
Expr *Config = nullptr, bool IsExecConfig = false,
ADLCallKind UsesADL = ADLCallKind::NotADL);
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc);
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr);
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
TypeSourceInfo *Ty,
SourceLocation RParenLoc,
Expr *Op);
CastKind PrepareScalarCast(ExprResult &src, QualType destType);
/// Build an altivec or OpenCL literal.
ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo);
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc,
Expr *InitExpr);
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
TypeSourceInfo *TInfo,
SourceLocation RParenLoc,
Expr *LiteralExpr);
ExprResult ActOnInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult BuildInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult ActOnDesignatedInitializer(Designation &Desig,
SourceLocation EqualOrColonLoc,
bool GNUSyntax,
ExprResult Init);
private:
static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
public:
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl);
void ActOnStartStmtExpr();
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc); // "({..})"
// Handle the final expression in a statement expression.
ExprResult ActOnStmtExprResult(ExprResult E);
void ActOnStmtExprError();
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
struct OffsetOfComponent {
SourceLocation LocStart, LocEnd;
bool isBrackets; // true if [expr], false if .ident
union {
IdentifierInfo *IdentInfo;
Expr *E;
} U;
};
/// __builtin_offsetof(type, a.b[123][456].c)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
ExprResult ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
ArrayRef<OffsetOfComponent> Components,
SourceLocation RParenLoc);
// __builtin_choose_expr(constExpr, expr1, expr2)
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr, SourceLocation RPLoc);
// __builtin_va_arg(expr, type)
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc);
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
TypeSourceInfo *TInfo, SourceLocation RPLoc);
// __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
// __builtin_COLUMN()
ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc,
SourceLocation RPLoc);
// Build a potentially resolved SourceLocExpr.
ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
SourceLocation BuiltinLoc, SourceLocation RPLoc,
DeclContext *ParentContext);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// The symbol exists.
IER_Exists,
/// The symbol does not exist.
IER_DoesNotExist,
/// The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// An error occurred.
IER_Error
};
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
const DeclarationNameInfo &TargetNameInfo);
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
bool IsIfExists, CXXScopeSpec &SS,
UnqualifiedId &Name);
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
Stmt *Nested);
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
CXXScopeSpec &SS, UnqualifiedId &Name,
Stmt *Nested);
//===------------------------- "Block" Extension ------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is
/// started.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockArguments - This callback allows processing of block arguments.
/// If there are no arguments, this is still invoked.
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope);
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
Scope *CurScope);
//===---------------------------- Clang Extensions ----------------------===//
/// __builtin_convertvector(...)
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- OpenCL Features -----------------------===//
/// __builtin_astype(...)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- C++ Features --------------------------===//
// Act on C++ namespaces
Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
SourceLocation NamespaceLoc,
SourceLocation IdentLoc, IdentifierInfo *Ident,
SourceLocation LBrace,
const ParsedAttributesView &AttrList,
UsingDirectiveDecl *&UsingDecl);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
NamespaceDecl *lookupStdExperimentalNamespace();
CXXRecordDecl *getStdBadAlloc() const;
EnumDecl *getStdAlignValT() const;
private:
// A cache representing if we've fully checked the various comparison category
// types stored in ASTContext. The bit-index corresponds to the integer value
// of a ComparisonCategoryType enumerator.
llvm::SmallBitVector FullyCheckedComparisonCategories;
ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
CXXScopeSpec &SS,
ParsedType TemplateTypeTy,
IdentifierInfo *MemberOrBase);
public:
enum class ComparisonCategoryUsage {
/// The '<=>' operator was used in an expression and a builtin operator
/// was selected.
OperatorInExpression,
/// A defaulted 'operator<=>' needed the comparison category. This
/// typically only applies to 'std::strong_ordering', due to the implicit
/// fallback return value.
DefaultedOperator,
};
/// Lookup the specified comparison category types in the standard
/// library, an check the VarDecls possibly returned by the operator<=>
/// builtins for that type.
///
/// \return The type of the comparison category type corresponding to the
/// specified Kind, or a null type if an error occurs
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
SourceLocation Loc,
ComparisonCategoryUsage Usage);
/// Tests whether Ty is an instance of std::initializer_list and, if
/// it is and Element is not NULL, assigns the element type to Element.
bool isStdInitializerList(QualType Ty, QualType *Element);
/// Looks for the std::initializer_list template and instantiates it
/// with Element, or emits an error if it's not found.
///
/// \returns The instantiated template, or null on error.
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
/// Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const FunctionDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
SourceLocation NamespcLoc, CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
const ParsedAttributesView &AttrList);
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
Decl *ActOnNamespaceAliasDef(Scope *CurScope,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident);
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
NamedDecl *Target,
UsingShadowDecl *PrevDecl);
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Previous);
bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
bool HasTypename,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc);
NamedDecl *BuildUsingDeclaration(
Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList, bool IsInstantiation);
NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
ArrayRef<NamedDecl *> Expansions);
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
/// Given a derived-class using shadow declaration for a constructor and the
/// correspnding base class constructor, find or create the implicit
/// synthesized derived class constructor to use for this initialization.
CXXConstructorDecl *
findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
ConstructorUsingShadowDecl *DerivedShadow);
Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
SourceLocation UsingLoc,
SourceLocation TypenameLoc, CXXScopeSpec &SS,
UnqualifiedId &Name, SourceLocation EllipsisLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc, UnqualifiedId &Name,
const ParsedAttributesView &AttrList,
TypeResult Type, Decl *DeclFromDeclSpec);
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
/// including handling of its default argument expressions.
///
/// \param ConstructKind - a CXXConstructExpr::ConstructionKind
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
/// Build a CXXConstructExpr whose constructor has already been resolved if
/// it denotes an inherited constructor.
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
// FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
// the constructor can be elidable?
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
NamedDecl *FoundDecl,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs, bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization, bool RequiresZeroInit,
unsigned ConstructKind, SourceRange ParenRange);
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
/// Instantiate or parse a C++ default argument expression as necessary.
/// Return true on error.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
ParmVarDecl *Param);
/// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
/// the default expr if needed.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD,
ParmVarDecl *Param);
/// FinalizeVarWithDestructor - Prepare for calling destructor on the
/// constructed variable.
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
/// Helper class that collects exception specifications for
/// implicitly-declared special member functions.
class ImplicitExceptionSpecification {
// Pointer to allow copying
Sema *Self;
// We order exception specifications thus:
// noexcept is the most restrictive, but is only used in C++11.
// throw() comes next.
// Then a throw(collected exceptions)
// Finally no specification, which is expressed as noexcept(false).
// throw(...) is used instead if any called function uses it.
ExceptionSpecificationType ComputedEST;
llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
SmallVector<QualType, 4> Exceptions;
void ClearExceptions() {
ExceptionsSeen.clear();
Exceptions.clear();
}
public:
explicit ImplicitExceptionSpecification(Sema &Self)
: Self(&Self), ComputedEST(EST_BasicNoexcept) {
if (!Self.getLangOpts().CPlusPlus11)
ComputedEST = EST_DynamicNone;
}
/// Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E) { CalledStmt(E); }
/// Integrate an invoked statement into the collected data.
void CalledStmt(Stmt *S);
/// Overwrite an EPI's exception specification with this
/// computed exception specification.
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
FunctionProtoType::ExceptionSpecInfo ESI;
ESI.Type = getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = Exceptions;
} else if (ESI.Type == EST_None) {
/// C++11 [except.spec]p14:
/// The exception-specification is noexcept(false) if the set of
/// potential exceptions of the special member function contains "any"
ESI.Type = EST_NoexceptFalse;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// default constructor of a class will have, and whether the parameter
/// will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(SourceLocation Loc,
CXXConstructorDecl *CD);
/// Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
/// Check the given noexcept-specifier, convert its expression, and compute
/// the appropriate ExceptionSpecificationType.
ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr,
ExceptionSpecificationType &EST);
/// Check the given exception-specification and update the
/// exception specification information with the results.
void checkExceptionSpecification(bool IsTopLevel,
ExceptionSpecificationType EST,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr,
SmallVectorImpl<QualType> &Exceptions,
FunctionProtoType::ExceptionSpecInfo &ESI);
/// Determine if we're in a case where we need to (incorrectly) eagerly
/// parse an exception specification to work around a libstdc++ bug.
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
/// Add an exception-specification to the given member function
/// (or member function template). The exception-specification was parsed
/// after the method itself was declared.
void actOnDelayedExceptionSpecification(Decl *Method,
ExceptionSpecificationType EST,
SourceRange SpecificationRange,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr);
class InheritedConstructorInfo;
/// Determine if a special member function should have a deleted
/// definition when it is defaulted.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
InheritedConstructorInfo *ICI = nullptr,
bool Diagnose = false);
/// Produce notes explaining why a defaulted function was defined as deleted.
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
/// Declare the implicit default constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// default constructor will be added.
///
/// \returns The implicitly-declared default constructor.
CXXConstructorDecl *DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl);
/// DefineImplicitDefaultConstructor - Checks for feasibility of
/// defining this constructor as the default constructor.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit destructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// destructor will be added.
///
/// \returns The implicitly-declared destructor.
CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitDestructor - Checks for feasibility of
/// defining this destructor as the default destructor.
void DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor);
/// Build an exception spec for destructors that don't have one.
///
/// C++11 says that user-defined destructors with no exception spec get one
/// that looks as if the destructor was implicitly declared.
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
/// Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy constructor will be added.
///
/// \returns The implicitly-declared copy constructor.
CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitCopyConstructor - Checks for feasibility of
/// defining this constructor as the copy constructor.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit move constructor for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move constructor will be added.
///
/// \returns The implicitly-declared move constructor, or NULL if it wasn't
/// declared.
CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitMoveConstructor - Checks for feasibility of
/// defining this constructor as the move constructor.
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// Declare the implicit copy assignment operator for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy assignment operator will be added.
///
/// \returns The implicitly-declared copy assignment operator.
CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Declare the implicit move assignment operator for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move assignment operator will be added.
///
/// \returns The implicitly-declared move assignment operator, or NULL if it
/// wasn't declared.
CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
/// Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// Check a completed declaration of an implicit special member.
void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
/// Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// Check whether 'this' shows up in the type of a static member
/// function after the (naturally empty) cv-qualifier-seq would be.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
/// Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// Check whether 'this' shows up in the attributes of the given
/// static member function.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
/// MaybeBindToTemporary - If the passed in expression has a record type with
/// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
/// it simply returns the passed in expression.
ExprResult MaybeBindToTemporary(Expr *E);
bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr*> &ConvertedArgs,
bool AllowExplicit = false,
bool IsListInitialization = false);
ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
SourceLocation NameLoc,
IdentifierInfo &Name);
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
ParsedType getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
ParsedType ObjectType);
// Checks that reinterpret casts don't have undefined behavior.
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference, SourceRange Range);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
SourceLocation LAngleBracketLoc,
Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc,
Expr *E,
SourceLocation RParenLoc);
ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
TypeSourceInfo *Ty,
Expr *E,
SourceRange AngleBrackets,
SourceRange Parens);
ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
ExprResult Operand,
SourceLocation RParenLoc);
ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
Expr *Operand, SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXTypeid - Parse typeid( something ).
ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
/// Handle a C++1z fold-expression: ( expr op ... op expr ).
ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc,
Optional<unsigned> NumExpansions);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// Build a CXXThisExpr and mark it referenced in the current context.
Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
void MarkThisReferenced(CXXThisExpr *This);
/// Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// When non-NULL, the C++ 'this' expression is allowed despite the
/// current context not being a non-static member function. In such cases,
/// this provides the type used for 'this'.
QualType CXXThisTypeOverride;
/// RAII object used to temporarily allow the C++ 'this' expression
/// to be used, with the given qualifiers on the current class type.
class CXXThisScopeRAII {
Sema &S;
QualType OldCXXThisTypeOverride;
bool Enabled;
public:
/// Introduce a new scope where 'this' may be allowed (when enabled),
/// using the given declaration (which is either a class template or a
/// class) along with the given qualifiers.
/// along with the qualifiers placed on '*this'.
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// Make sure the value of 'this' is actually available in the current
/// context, if it is a potentially evaluated context.
///
/// \param Loc The location at which the capture of 'this' occurs.
///
/// \param Explicit Whether 'this' is explicitly captured in a lambda
/// capture list.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// 'this' that may or may not be used in certain specializations of
/// a nested generic lambda (depending on whether the name resolves to
/// a non-static member function or a static function).
/// \return returns 'true' if failed, 'false' if success.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
bool BuildAndDiagnose = true,
const unsigned *const FunctionScopeIndexToStopAt = nullptr,
bool ByCopy = false);
/// Determine whether the given type is the type of *this that is used
/// outside of the body of a member function for a type that is currently
/// being defined.
bool isThisOutsideMemberFunctionBody(QualType BaseType);
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
ExprResult
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
SourceLocation AtLoc, SourceLocation RParen);
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
//// ActOnCXXThrow - Parse throw expressions.
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
bool IsThrownVarInScope);
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
SourceLocation LParenOrBraceLoc,
MultiExprArg Exprs,
SourceLocation RParenOrBraceLoc,
bool ListInitialization);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc,
bool ListInitialization);
/// ActOnCXXNew - Parsed a C++ 'new' expression.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D,
Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
TypeSourceInfo *AllocTypeInfo,
Optional<Expr *> ArraySize,
SourceRange DirectInitRange,
Expr *Initializer);
/// Determine whether \p FD is an aligned allocation or deallocation
/// function that is unavailable.
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
/// Produce diagnostics if \p FD is an aligned allocation or deallocation
/// function that is unavailable.
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
SourceLocation Loc);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
/// The scope in which to find allocation functions.
enum AllocationFunctionScope {
/// Only look for allocation functions in the global scope.
AFS_Global,
/// Only look for allocation functions in the scope of the
/// allocated class.
AFS_Class,
/// Look for allocation functions in both the global scope
/// and in the scope of the allocated class.
AFS_Both
};
/// Finds the overloads of operator new and delete that are appropriate
/// for the allocation.
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
AllocationFunctionScope NewScope,
AllocationFunctionScope DeleteScope,
QualType AllocType, bool IsArray,
bool &PassAlignment, MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete,
bool Diagnose = true);
void DeclareGlobalNewDelete();
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
ArrayRef<QualType> Params);
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name, FunctionDecl* &Operator,
bool Diagnose = true);
FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
bool CanProvideSize,
bool Overaligned,
DeclarationName Name);
FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
CXXRecordDecl *RD);
/// ActOnCXXDelete - Parsed a C++ 'delete' expression
ExprResult ActOnCXXDelete(SourceLocation StartLoc,
bool UseGlobal, bool ArrayForm,
Expr *Operand);
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
bool IsDelete, bool CallCanBeVirtual,
bool WarnOnNonAbstractTypes,
SourceLocation DtorLoc);
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
Expr *Operand, SourceLocation RParen);
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
SourceLocation RParen);
/// Parsed one of the type trait support pseudo-functions.
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<ParsedType> Args,
SourceLocation RParenLoc);
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc);
/// ActOnArrayTypeTrait - Parsed one of the binary type trait support
/// pseudo-functions.
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
ParsedType LhsTy,
Expr *DimExpr,
SourceLocation RParen);
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
TypeSourceInfo *TSInfo,
Expr *DimExpr,
SourceLocation RParen);
/// ActOnExpressionTrait - Parsed one of the unary type trait support
/// pseudo-functions.
ExprResult ActOnExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult BuildExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult ActOnStartCXXMemberReference(Scope *S,
Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
ParsedType &ObjectType,
bool &MayBePseudoDestructor);
ExprResult BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeType,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
SourceLocation TildeLoc,
const DeclSpec& DS);
/// MaybeCreateExprWithCleanups - If the current full-expression
/// requires any cleanups, surround it with a ExprWithCleanups node.
/// Otherwise, just returns the passed-in expression.
Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
MaterializeTemporaryExpr *
CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
bool BoundToLvalueReference);
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
return ActOnFinishFullExpr(
Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue, bool IsConstexpr = false);
StmtResult ActOnFinishFullStmt(Stmt *Stmt);
// Marks SS invalid if it represents an incomplete type.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
DeclContext *computeDeclContext(QualType T);
DeclContext *computeDeclContext(const CXXScopeSpec &SS,
bool EnteringContext = false);
bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
/// The parser has parsed a global nested-name-specifier '::'.
///
/// \param CCLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
/// The parser has parsed a '__super' nested-name-specifier.
///
/// \param SuperLoc The location of the '__super' keyword.
///
/// \param ColonColonLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
SourceLocation ColonColonLoc, CXXScopeSpec &SS);
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
bool *CanCorrect = nullptr);
NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
/// Keeps information about an identifier in a nested-name-spec.
///
struct NestedNameSpecInfo {
/// The type of the object, if we're parsing nested-name-specifier in
/// a member access expression.
ParsedType ObjectType;
/// The identifier preceding the '::'.
IdentifierInfo *Identifier;
/// The location of the identifier.
SourceLocation IdentifierLoc;
/// The location of the '::'.
SourceLocation CCLoc;
/// Creates info object for the most typical case.
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
: ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
CCLoc(ColonColonLoc) {
}
NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
SourceLocation ColonColonLoc, QualType ObjectType)
: ObjectType(ParsedType::make(ObjectType)), Identifier(II),
IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
}
};
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo);
bool BuildCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
NamedDecl *ScopeLookupResult,
bool ErrorRecoveryLookup,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
/// The parser has parsed a nested-name-specifier 'identifier::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param IdInfo Parser information about an identifier in the
/// nested-name-spec.
///
/// \param EnteringContext Whether we're entering the context nominated by
/// this nested-name-specifier.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param ErrorRecoveryLookup If true, then this method is called to improve
/// error recovery. In this case do not emit error message.
///
/// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
/// are allowed. The bool value pointed by this parameter is set to 'true'
/// if the identifier is treated as if it was followed by ':', not '::'.
///
/// \param OnlyNamespace If true, only considers namespaces in lookup.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
NestedNameSpecInfo &IdInfo,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr,
bool OnlyNamespace = false);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
NestedNameSpecInfo &IdInfo,
bool EnteringContext);
/// The parser has parsed a nested-name-specifier
/// 'template[opt] template-name < template-args >::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param TemplateKWLoc the location of the 'template' keyword, if any.
/// \param TemplateName the template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
/// \param CCLoc The location of the '::'.
///
/// \param EnteringContext Whether we're entering the context of the
/// nested-name-specifier.
///
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
SourceLocation CCLoc,
bool EnteringContext);
/// Given a C++ nested-name-specifier, produce an annotation value
/// that the parser can use later to reconstruct the given
/// nested-name-specifier.
///
/// \param SS A nested-name-specifier.
///
/// \returns A pointer containing all of the information in the
/// nested-name-specifier \p SS.
void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
/// Given an annotation pointer for a nested-name-specifier, restore
/// the nested-name-specifier structure.
///
/// \param Annotation The annotation pointer, produced by
/// \c SaveNestedNameSpecifierAnnotation().
///
/// \param AnnotationRange The source range corresponding to the annotation.
///
/// \param SS The nested-name-specifier that will be updated with the contents
/// of the annotation pointer.
void RestoreNestedNameSpecifierAnnotation(void *Annotation,
SourceRange AnnotationRange,
CXXScopeSpec &SS);
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
/// After this method is called, according to [C++ 3.4.3p3], names should be
/// looked up in the declarator-id's scope, until the declarator is parsed and
/// ActOnCXXExitDeclaratorScope is called.
/// The 'SS' should be a non-empty valid CXXScopeSpec.
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
/// Used to indicate that names should revert to being looked up in the
/// defining scope.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
/// initializer for the declaration 'Dcl'.
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
/// static data member of class X, names should be looked up in the scope of
/// class X.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
/// initializer for the declaration 'Dcl'.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
/// Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// Start the definition of a lambda expression.
CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodType,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params,
ConstexprSpecKind ConstexprKind);
/// Number lambda for linkage purposes if necessary.
void handleLambdaNumbering(
CXXRecordDecl *Class, CXXMethodDecl *Method,
Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None);
/// Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable);
/// Perform initialization analysis of the init-capture and perform
/// any implicit conversions such as an lvalue-to-rvalue conversion if
/// not being used to initialize a reference.
ParsedType actOnLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
return ParsedType::make(buildLambdaInitCaptureInitialization(
Loc, ByRef, EllipsisLoc, None, Id,
InitKind != LambdaCaptureInitKind::CopyInit, Init));
}
QualType buildLambdaInitCaptureInitialization(
SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
Expr *&Init);
/// Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture.
///
/// CodeGen handles emission of lambda captures, ignoring these dummy
/// variables appropriately.
VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType,
SourceLocation EllipsisLoc,
IdentifierInfo *Id,
unsigned InitStyle, Expr *Init);
/// Add an init-capture to a lambda scope.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief This is called after parsing the explicit template parameter list
/// on a lambda (if it exists) in C++2a.
void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> TParams,
SourceLocation RAngleLoc);
/// Introduce the lambda parameters into scope.
void addLambdaParameters(
ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
CXXMethodDecl *CallOperator, Scope *CurScope);
/// Deduce a block or lambda's return type based on the return
/// statements present in the body.
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
/// ActOnStartOfLambdaDefinition - This is called just before we start
/// parsing the body of a lambda; it analyzes the explicit captures and
/// arguments, and sets up various data-structures for the body of the
/// lambda.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo, Scope *CurScope);
/// ActOnLambdaError - If there is an error parsing a lambda, this callback
/// is invoked to pop the information about the lambda.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation = false);
/// ActOnLambdaExpr - This is called when the body of a lambda expression
/// was successfully completed.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope);
/// Does copying/destroying the captured variable have side effects?
bool CaptureHasSideEffects(const sema::Capture &From);
/// Diagnose if an explicit lambda capture is unused. Returns true if a
/// diagnostic is emitted.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
const sema::Capture &From);
/// Build a FieldDecl suitable to hold the given capture.
FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
/// Initialize the given capture with a suitable expression.
ExprResult BuildCaptureInit(const sema::Capture &Capture,
SourceLocation ImplicitCaptureLoc,
bool IsOpenMPMapping = false);
/// Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// Get the return type to use for a lambda's conversion function(s) to
/// function pointer type, given the type of the call operator.
QualType
getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType);
/// Define the "body" of the conversion from a lambda object to a
/// function pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLoc, CXXConversionDecl *Conv);
/// Define the "body" of the conversion from a lambda object to a
/// block pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
CXXConversionDecl *Conv);
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src);
/// Check whether the given expression is a valid constraint expression.
/// A diagnostic is emitted if it is not, and false is returned.
bool CheckConstraintExpression(Expr *CE);
/// \brief Check whether the given list of constraint expressions are
/// satisfied (as if in a 'conjunction') given template arguments.
/// \param ConstraintExprs a list of constraint expressions, treated as if
/// they were 'AND'ed together.
/// \param TemplateArgs the list of template arguments to substitute into the
/// constraint expression.
/// \param TemplateIDRange The source range of the template id that
/// caused the constraints check.
/// \param Satisfaction if true is returned, will contain details of the
/// satisfaction, with enough information to diagnose an unsatisfied
/// expression.
/// \returns true if an error occurred and satisfaction could not be checked,
/// false otherwise.
bool CheckConstraintSatisfaction(TemplateDecl *Template,
ArrayRef<const Expr *> ConstraintExprs,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange,
ConstraintSatisfaction &Satisfaction);
bool CheckConstraintSatisfaction(ClassTemplatePartialSpecializationDecl *TD,
ArrayRef<const Expr *> ConstraintExprs,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange,
ConstraintSatisfaction &Satisfaction);
bool CheckConstraintSatisfaction(VarTemplatePartialSpecializationDecl *TD,
ArrayRef<const Expr *> ConstraintExprs,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange,
ConstraintSatisfaction &Satisfaction);
/// \brief Check whether the given non-dependent constraint expression is
/// satisfied. Returns false and updates Satisfaction with the satisfaction
/// verdict if successful, emits a diagnostic and returns true if an error
/// occured and satisfaction could not be determined.
///
/// \returns true if an error occurred, false otherwise.
bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
ConstraintSatisfaction &Satisfaction);
/// Check that the associated constraints of a template declaration match the
/// associated constraints of an older declaration of which it is a
/// redeclaration.
bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old,
TemplateParameterList *New);
/// \brief Ensure that the given template arguments satisfy the constraints
/// associated with the given template, emitting a diagnostic if they do not.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateArgs The converted, canonicalized template arguments.
///
/// \param TemplateIDRange The source range of the template id that
/// caused the constraints check.
///
/// \returns true if the constrains are not satisfied or could not be checked
/// for satisfaction, false if the constraints are satisfied.
bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange TemplateIDRange);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied.
void
DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied.
void
DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction& Satisfaction);
/// \brief Emit diagnostics explaining why a constraint expression was deemed
/// unsatisfied because it was ill-formed.
void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation,
StringRef Diagnostic);
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
ArrayRef<Expr *> Strings);
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *"
/// or "id" if NSNumber is unavailable.
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
bool Value);
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
/// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
/// '@' prefixed parenthesized expression. The type of the expression will
/// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
/// of ValueType, which is allowed to be a built-in numeric type, "char *",
/// "const char *" or C structure with attribute 'objc_boxable'.
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod);
ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
MutableArrayRef<ObjCDictionaryElement> Elements);
ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc);
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
CXXConversionDecl *Method,
bool HadMultipleCandidates);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc);
/// ParseObjCSelectorExpression - Build selector expression for \@selector
ExprResult ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors);
/// ParseObjCProtocolExpression - Build protocol expression for \@protocol
ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc);
//===--------------------------------------------------------------------===//
// C++ Declarations
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Classes
//
CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS = nullptr);
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
SourceLocation ColonLoc,
const ParsedAttributesView &Attrs);
NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BitfieldWidth, const VirtSpecifiers &VS,
InClassInitStyle InitStyle);
void ActOnStartCXXInClassMemberInitializer();
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
SourceLocation EqualLoc,
Expr *Init);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc);
MemInitResult BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc);
MemInitResult BuildMemberInitializer(ValueDecl *Member,
Expr *Init,
SourceLocation IdLoc);
MemInitResult BuildBaseInitializer(QualType BaseType,
TypeSourceInfo *BaseTInfo,
Expr *Init,
CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc);
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Expr *Init,
CXXRecordDecl *ClassDecl);
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer);
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers = None);
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
/// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
/// mark all the non-trivial destructors of its members and bases as
/// referenced.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
CXXRecordDecl *Record);
/// The list of classes whose vtables have been used within
/// this translation unit, and the source locations at which the
/// first use occurred.
typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
/// The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// The set of classes whose vtables have been used within
/// this translation unit, and a bit that will be true if the vtable is
/// required to be emitted (otherwise, it should be emitted only if needed
/// by code generation).
llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
/// Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// Mark the exception specifications of all virtual member functions
/// in the given class as needed.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD);
/// MarkVirtualMembersReferenced - Will mark all members of the given
/// CXXRecordDecl referenced.
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
bool ConstexprOnly = false);
/// Define all of the vtables that have been used in this
/// translation unit and reference any virtual members used by those
/// vtables.
///
/// \returns true if any work was done, false otherwise.
bool DefineUsedVTables();
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
void ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors);
/// Check class-level dllimport/dllexport attribute. The caller must
/// ensure that referenceDLLExportedClassMethods is called some point later
/// when all outer classes of Class are complete.
void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
void referenceDLLExportedClassMethods();
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
/// Add gsl::Pointer attribute to std::container::iterator
/// \param ND The declaration that introduces the name
/// std::container::iterator. \param UnderlyingRecord The record named by ND.
void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
/// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
/// Add [[gsl::Pointer]] attributes for std:: types.
void inferGslPointerAttribute(TypedefNameDecl *TD);
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
/// Check that the C++ class annoated with "trivial_abi" satisfies all the
/// conditions that are needed for the attribute to have an effect.
void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
Decl *TagDecl, SourceLocation LBrac,
SourceLocation RBrac,
const ParsedAttributesView &AttrList);
void ActOnFinishCXXMemberDecls();
void ActOnFinishCXXNonNestedClass();
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnFinishDelayedMemberInitializers(Decl *Record);
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
CachedTokens &Toks);
void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
bool IsInsideALocalClassWithinATemplateFunction();
Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc);
Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessageExpr,
SourceLocation RParenLoc,
bool Failed);
FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo);
Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TemplateParams);
NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams);
QualType CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
void CheckConstructor(CXXConstructorDecl *Constructor);
QualType CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
bool CheckDestructor(CXXDestructorDecl *Destructor);
void CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC);
Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
StorageClass &SC);
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
CXXSpecialMember CSM);
void CheckDelayedMemberExceptionSpecs();
bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
DefaultedComparisonKind DCK);
void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
FunctionDecl *Spaceship);
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
DefaultedComparisonKind DCK);
//===--------------------------------------------------------------------===//
// C++ Derived Classes
//
/// ActOnBaseSpecifier - Parsed a base specifier
CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc);
BaseResult ActOnBaseSpecifier(Decl *classdecl,
SourceRange SpecifierRange,
ParsedAttributes &Attrs,
bool Virtual, AccessSpecifier Access,
ParsedType basetype,
SourceLocation BaseLoc,
SourceLocation EllipsisLoc);
bool AttachBaseSpecifiers(CXXRecordDecl *Class,
MutableArrayRef<CXXBaseSpecifier *> Bases);
void ActOnBaseSpecifiers(Decl *ClassDecl,
MutableArrayRef<CXXBaseSpecifier *> Bases);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
CXXBasePaths &Paths);
// FIXME: I don't like this name.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath = nullptr,
bool IgnoreAccess = false);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbigiousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath,
bool IgnoreAccess = false);
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionReturnType - Checks whether the return types are
/// covariant, according to C++ [class.virtual]p5.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionExceptionSpec - Checks whether the exception
/// spec is a subset of base spec.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
/// CheckOverrideControl - Check C++11 override control semantics.
void CheckOverrideControl(NamedDecl *D);
/// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
/// not used in the declaration of an overriding method.
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
/// CheckForFunctionMarkedFinal - Checks whether a virtual member function
/// overrides a virtual member function marked 'final', according to
/// C++11 [class.virtual]p4.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
//===--------------------------------------------------------------------===//
// C++ Access Control
//
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent,
AR_delayed
};
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS);
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
SourceRange PlacementRange,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
bool Diagnose = true);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
bool IsCopyBindingRefToTemp = false);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
DeclAccessPair FoundDecl,
const InitializedEntity &Entity,
const PartialDiagnostic &PDiag);
AccessResult CheckDestructorAccess(SourceLocation Loc,
CXXDestructorDecl *Dtor,
const PartialDiagnostic &PDiag,
QualType objectType = QualType());
AccessResult CheckFriendAccess(NamedDecl *D);
AccessResult CheckMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *NamingClass,
DeclAccessPair Found);
AccessResult
CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *DecomposedClass,
DeclAccessPair Field);
AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
Expr *ObjectExpr,
Expr *ArgExpr,
DeclAccessPair FoundDecl);
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
DeclAccessPair FoundDecl);
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
QualType Base, QualType Derived,
const CXXBasePath &Path,
unsigned DiagID,
bool ForceCheck = false,
bool ForceUnprivileged = false);
void CheckLookupAccess(const LookupResult &R);
bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
QualType BaseType);
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
DeclAccessPair Found, QualType ObjectType,
SourceLocation Loc,
const PartialDiagnostic &Diag);
bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
DeclAccessPair Found,
QualType ObjectType) {
return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
SourceLocation(), PDiag());
}
void HandleDependentAccessCheck(const DependentDiagnostic &DD,
const MultiLevelTemplateArgumentList &TemplateArgs);
void PerformDependentDiagnostics(const DeclContext *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
/// When true, access checking violations are treated as SFINAE
/// failures rather than hard errors.
bool AccessCheckingSFINAE;
enum AbstractDiagSelID {
AbstractNone = -1,
AbstractReturnType,
AbstractParamType,
AbstractVariableType,
AbstractFieldType,
AbstractIvarType,
AbstractSynthesizedIvarType,
AbstractArrayType
};
bool isAbstractType(SourceLocation Loc, QualType T);
bool RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
template <typename... Ts>
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireNonAbstractType(Loc, T, Diagnoser);
}
void DiagnoseAbstractType(const CXXRecordDecl *RD);
//===--------------------------------------------------------------------===//
// C++ Overloaded Operators [C++ 13.5]
//
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
//===--------------------------------------------------------------------===//
// C++ Templates [C++ 14]
//
void FilterAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
bool hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true,
bool AllowDependent = true,
bool AllowNonTemplateFunctions = false);
/// Try to interpret the lookup result D as a template-name.
///
/// \param D A declaration found by name lookup.
/// \param AllowFunctionTemplates Whether function templates should be
/// considered valid results.
/// \param AllowDependent Whether unresolved using declarations (that might
/// name templates) should be considered valid results.
NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
bool AllowFunctionTemplates = true,
bool AllowDependent = true);
enum class AssumedTemplateKind {
/// This is not assumed to be a template name.
None,
/// This is assumed to be a template name because lookup found nothing.
FoundNothing,
/// This is assumed to be a template name because lookup found one or more
/// functions (but no function templates).
FoundFunctions,
};
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
QualType ObjectType, bool EnteringContext,
bool &MemberOfUnknownSpecialization,
SourceLocation TemplateKWLoc = SourceLocation(),
AssumedTemplateKind *ATK = nullptr);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
const UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization);
/// Try to resolve an undeclared template name as a type template.
///
/// Sets II to the identifier corresponding to the template name, and updates
/// Name to a corresponding (typo-corrected) type template name and TNK to
/// the corresponding kind, if possible.
void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
TemplateNameKind &TNK,
SourceLocation NameLoc,
IdentifierInfo *&II);
bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
SourceLocation NameLoc,
bool Diagnose = true);
/// Determine whether a particular identifier might be the name in a C++1z
/// deduction-guide declaration.
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
SourceLocation NameLoc,
ParsedTemplateTy *Template = nullptr);
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
SourceLocation IILoc,
Scope *S,
const CXXScopeSpec *SS,
TemplateTy &SuggestedTemplate,
TemplateNameKind &SuggestedKind);
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
NamedDecl *Instantiation,
bool InstantiatedFromMember,
const NamedDecl *Pattern,
const NamedDecl *PatternDef,
TemplateSpecializationKind TSK,
bool Complain = true);
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
SourceLocation EllipsisLoc,
SourceLocation KeyLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth, unsigned Position,
SourceLocation EqualLoc,
ParsedType DefaultArg);
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
SourceLocation Loc);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
SourceLocation TmpLoc,
TemplateParameterList *Params,
SourceLocation EllipsisLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
ParsedTemplateArgument DefaultArg);
TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,
SourceLocation ExportLoc,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ArrayRef<NamedDecl *> Params,
SourceLocation RAngleLoc,
Expr *RequiresClause);
/// The context in which we are checking a template parameter list.
enum TemplateParamListContext {
TPC_ClassTemplate,
TPC_VarTemplate,
TPC_FunctionTemplate,
TPC_ClassTemplateMember,
TPC_FriendClassTemplate,
TPC_FriendFunctionTemplate,
TPC_FriendFunctionTemplateDefinition,
TPC_TypeAliasTemplate
};
bool CheckTemplateParameterList(TemplateParameterList *NewParams,
TemplateParameterList *OldParams,
TemplateParamListContext TPC,
SkipBodyInfo *SkipBody = nullptr);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsMemberSpecialization, bool &Invalid);
DeclResult CheckClassTemplate(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
AccessSpecifier AS, SourceLocation ModulePrivateLoc,
SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
TemplateParameterList **OuterTemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
QualType NTTPType,
SourceLocation Loc);
void translateTemplateArguments(const ASTTemplateArgsPtr &In,
TemplateArgumentListInfo &Out);
ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false, bool IsClassName = false);
/// Parsed an elaborated-type-specifier that refers to a template-id,
/// such as \c class T::template apply<U>.
TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
TypeSpecifierType TagSpec,
SourceLocation TagLoc,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateD,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgsIn,
SourceLocation RAngleLoc);
DeclResult ActOnVarTemplateSpecialization(
Scope *S, Declarator &D, TypeSourceInfo *DI,
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult
CheckConceptTemplateId(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
SourceLocation ConceptNameLoc, NamedDecl *FoundDecl,
ConceptDecl *NamedConcept,
const TemplateArgumentListInfo *TemplateArgs);
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
bool RequiresADL,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
TemplateNameKind ActOnDependentTemplateName(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
TemplateTy &Template, bool AllowInjectedClassName = false);
DeclResult ActOnClassTemplateSpecialization(
Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
const ParsedAttributesView &Attr,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody = nullptr);
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
TemplateDecl *PrimaryTemplate,
unsigned NumExplicitArgs,
ArrayRef<TemplateArgument> Args);
void CheckTemplatePartialSpecialization(
ClassTemplatePartialSpecializationDecl *Partial);
void CheckTemplatePartialSpecialization(
VarTemplatePartialSpecializationDecl *Partial);
Decl *ActOnTemplateDeclarator(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
TemplateSpecializationKind NewTSK,
NamedDecl *PrevDecl,
TemplateSpecializationKind PrevTSK,
SourceLocation PrevPtOfInstantiation,
bool &SuppressNew);
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
const TemplateArgumentListInfo &ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckFunctionTemplateSpecialization(
FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
LookupResult &Previous, bool QualifiedFriend = false);
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
DeclResult ActOnExplicitInstantiation(
Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
TemplateTy Template, SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec, SourceLocation KWLoc,
CXXScopeSpec &SS, IdentifierInfo *Name,
SourceLocation NameLoc,
const ParsedAttributesView &Attr);
DeclResult ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
Declarator &D);
TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
Decl *Param,
SmallVectorImpl<TemplateArgument>
&Converted,
bool &HasDefaultArg);
/// Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// The template argument was deduced from an array bound
/// via template argument deduction.
CTAK_DeducedFromArrayBound
};
bool CheckTemplateArgument(NamedDecl *Param,
TemplateArgumentLoc &Arg,
NamedDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
unsigned ArgumentPackIndex,
SmallVectorImpl<TemplateArgument> &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
/// Check that the given template arguments can be be provided to
/// the given template, converting the arguments along the way.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateLoc The location of the template name in the source.
///
/// \param TemplateArgs The list of template arguments. If the template is
/// a template template parameter, this function may extend the set of
/// template arguments to also include substituted, defaulted template
/// arguments.
///
/// \param PartialTemplateArgs True if the list of template arguments is
/// intentionally partial, e.g., because we're checking just the initial
/// set of template arguments.
///
/// \param Converted Will receive the converted, canonicalized template
/// arguments.
///
/// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
/// contain the converted forms of the template arguments as written.
/// Otherwise, \p TemplateArgs will not be modified.
///
/// \param ConstraintsNotSatisfied If provided, and an error occured, will
/// receive true if the cause for the error is the associated constraints of
/// the template not being satisfied by the template arguments.
///
/// \returns true if an error occurred, false otherwise.
bool CheckTemplateArgumentList(TemplateDecl *Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs,
bool PartialTemplateArgs,
SmallVectorImpl<TemplateArgument> &Converted,
bool UpdateArgsWithConversions = true,
bool *ConstraintsNotSatisfied = nullptr);
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
TemplateArgumentLoc &Arg,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
TypeSourceInfo *Arg);
ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
bool CheckTemplateTemplateArgument(TemplateParameterList *Params,
TemplateArgumentLoc &Arg);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// We are matching the template parameter lists of two templates
/// that might be redeclarations.
///
/// \code
/// template<typename T> struct X;
/// template<typename T> struct X;
/// \endcode
TPL_TemplateMatch,
/// We are matching the template parameter lists of two template
/// template parameters as part of matching the template parameter lists
/// of two templates that might be redeclarations.
///
/// \code
/// template<template<int I> class TT> struct X;
/// template<template<int Value> class Other> struct X;
/// \endcode
TPL_TemplateTemplateParmMatch,
/// We are matching the template parameter lists of a template
/// template argument against the template parameter lists of a template
/// template parameter.
///
/// \code
/// template<template<int Value> class Metafun> struct X;
/// template<int Value> struct integer_c;
/// X<integer_c> xic;
/// \endcode
TPL_TemplateTemplateArgumentMatch
};
bool TemplateParameterListsAreEqual(TemplateParameterList *New,
TemplateParameterList *Old,
bool Complain,
TemplateParameterListEqualKind Kind,
SourceLocation TemplateArgLoc
= SourceLocation());
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
/// Called when the parser has parsed a C++ typename
/// specifier, e.g., "typename T::type".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param II the identifier we're retrieving (e.g., 'type' in the example).
/// \param IdLoc the location of the identifier.
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS, const IdentifierInfo &II,
SourceLocation IdLoc);
/// Called when the parser has parsed a C++ typename
/// specifier that ends in a template-id, e.g.,
/// "typename MetaFun::template apply<T1, T2>".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param TemplateLoc the location of the 'template' keyword, if any.
/// \param TemplateName The template name.
/// \param TemplateII The identifier used to name the template.
/// \param TemplateIILoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
IdentifierInfo *TemplateII,
SourceLocation TemplateIILoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc);
TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
SourceLocation Loc,
DeclarationName Name);
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
ExprResult RebuildExprInCurrentInstantiation(Expr *E);
bool RebuildTemplateParamsInCurrentInstantiation(
TemplateParameterList *Params);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgumentList &Args);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgument *Args,
unsigned NumArgs);
// Concepts
Decl *ActOnConceptDefinition(
Scope *S, MultiTemplateParamsArg TemplateParameterLists,
IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
//===--------------------------------------------------------------------===//
// C++ Variadic Templates (C++0x [temp.variadic])
//===--------------------------------------------------------------------===//
/// Determine whether an unexpanded parameter pack might be permitted in this
/// location. Useful for error recovery.
bool isUnexpandedParameterPackPermitted();
/// The context in which an unexpanded parameter pack is
/// being diagnosed.
///
/// Note that the values of this enumeration line up with the first
/// argument to the \c err_unexpanded_parameter_pack diagnostic.
enum UnexpandedParameterPackContext {
/// An arbitrary expression.
UPPC_Expression = 0,
/// The base type of a class type.
UPPC_BaseType,
/// The type of an arbitrary declaration.
UPPC_DeclarationType,
/// The type of a data member.
UPPC_DataMemberType,
/// The size of a bit-field.
UPPC_BitFieldWidth,
/// The expression in a static assertion.
UPPC_StaticAssertExpression,
/// The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// The enumerator value.
UPPC_EnumeratorValue,
/// A using declaration.
UPPC_UsingDeclaration,
/// A friend declaration.
UPPC_FriendDeclaration,
/// A declaration qualifier.
UPPC_DeclarationQualifier,
/// An initializer.
UPPC_Initializer,
/// A default argument.
UPPC_DefaultArgument,
/// The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// The type of an exception.
UPPC_ExceptionType,
/// Partial specialization.
UPPC_PartialSpecialization,
/// Microsoft __if_exists.
UPPC_IfExists,
/// Microsoft __if_not_exists.
UPPC_IfNotExists,
/// Lambda expression.
UPPC_Lambda,
/// Block expression,
UPPC_Block
};
/// Diagnose unexpanded parameter packs.
///
/// \param Loc The location at which we should emit the diagnostic.
///
/// \param UPPC The context in which we are diagnosing unexpanded
/// parameter packs.
///
/// \param Unexpanded the set of unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
UnexpandedParameterPackContext UPPC,
ArrayRef<UnexpandedParameterPack> Unexpanded);
/// If the given type contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The source location where a diagnostc should be emitted.
///
/// \param T The type that is being checked for unexpanded parameter
/// packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
UnexpandedParameterPackContext UPPC);
/// If the given expression contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param E The expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
/// If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
/// \param SS The nested-name-specifier that is being checked for
/// unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
UnexpandedParameterPackContext UPPC);
/// If the given name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param NameInfo The name (with source location information) that
/// is being checked for unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
UnexpandedParameterPackContext UPPC);
/// If the given template name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The location of the template name.
///
/// \param Template The template name that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
TemplateName Template,
UnexpandedParameterPackContext UPPC);
/// If the given template argument contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param Arg The template argument that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
UnexpandedParameterPackContext UPPC);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgument Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param T The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(QualType T,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param TL The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TypeLoc TL,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// nested-name-specifier.
///
/// \param NNS The nested-name-specifier that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Collect the set of unexpanded parameter packs within the given
/// name.
///
/// \param NameInfo The name that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// Invoked when parsing a template argument followed by an
/// ellipsis, which creates a pack expansion.
///
/// \param Arg The template argument preceding the ellipsis, which
/// may already be invalid.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
SourceLocation EllipsisLoc);
/// Invoked when parsing a type followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Type The type preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
/// Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly
/// transforming the pattern.
///
/// \param EllipsisLoc The location of the ellipsis that identifies the
/// pack expansion.
///
/// \param PatternRange The source range that covers the entire pattern of
/// the pack expansion.
///
/// \param Unexpanded The set of unexpanded parameter packs within the
/// pattern.
///
/// \param ShouldExpand Will be set to \c true if the transformer should
/// expand the corresponding pack expansions into separate arguments. When
/// set, \c NumExpansions must also be set.
///
/// \param RetainExpansion Whether the caller should add an unexpanded
/// pack expansion after all of the expanded arguments. This is used
/// when extending explicitly-specified template argument packs per
/// C++0x [temp.arg.explicit]p9.
///
/// \param NumExpansions The number of separate arguments that will be in
/// the expanded form of the corresponding pack expansion. This is both an
/// input and an output parameter, which can be set by the caller if the
/// number of expansions is known a priori (e.g., due to a prior substitution)
/// and will be set by the callee when the number of expansions is known.
/// The callee must set this value when \c ShouldExpand is \c true; it may
/// set this value in other cases.
///
/// \returns true if an error occurred (e.g., because the parameter packs
/// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool &ShouldExpand,
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// Determine the number of arguments in the given pack expansion
/// type.
///
/// This routine assumes that the number of arguments in the expansion is
/// consistent across all of the unexpanded parameter packs in its pattern.
///
/// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Determine whether the given declarator contains any unexpanded
/// parameter packs.
///
/// This routine is used by the parser to disambiguate function declarators
/// with an ellipsis prior to the ')', e.g.,
///
/// \code
/// void f(T...);
/// \endcode
///
/// To determine whether we have an (unnamed) function parameter pack or
/// a variadic function.
///
/// \returns true if the declarator contains any unexpanded parameter packs,
/// false otherwise.
bool containsUnexpandedParameterPacks(Declarator &D);
/// Returns the pattern of the pack expansion for a template argument.
///
/// \param OrigLoc The template argument to expand.
///
/// \param Ellipsis Will be set to the location of the ellipsis.
///
/// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc,
SourceLocation &Ellipsis,
Optional<unsigned> &NumExpansions) const;
/// Given a template argument that contains an unexpanded parameter pack, but
/// which has already been substituted, attempt to determine the number of
/// elements that will be produced once this argument is fully-expanded.
///
/// This is intended for use when transforming 'sizeof...(Arg)' in order to
/// avoid actually expanding the pack where possible.
Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
//===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct])
//===--------------------------------------------------------------------===//
/// Adjust the type \p ArgFunctionType to match the calling convention,
/// noreturn, and optionally the exception specification of \p FunctionType.
/// Deduction often wants to ignore these properties when matching function
/// types.
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
bool AdjustExceptionSpec = false);
/// Describes the result of template argument deduction.
///
/// The TemplateDeductionResult enumeration describes the result of
/// template argument deduction, as returned from
/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
/// structure provides additional information about the results of
/// template argument deduction, e.g., the deduced template argument
/// list (if successful) or the specific template parameters or
/// deduced arguments that were involved in the failure.
enum TemplateDeductionResult {
/// Template argument deduction was successful.
TDK_Success = 0,
/// The declaration was invalid; do nothing.
TDK_Invalid,
/// Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// Template argument deduction did not deduce a value for every
/// expansion of an expanded template parameter pack.
TDK_IncompletePack,
/// Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// Template argument deduction failed due to inconsistent
/// cv-qualifiers on a template parameter type that would
/// otherwise be deduced, e.g., we tried to deduce T in "const T"
/// but were given a non-const "X".
TDK_Underqualified,
/// Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// After substituting deduced template arguments, a dependent
/// parameter type did not match the corresponding argument.
TDK_DeducedMismatch,
/// After substituting deduced template arguments, an element of
/// a dependent parameter type did not match the corresponding element
/// of the corresponding argument (when deducing from an initializer list).
TDK_DeducedMismatchNested,
/// A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// Checking non-dependent argument conversions failed.
TDK_NonDependentConversionFailure,
/// The deduced arguments did not satisfy the constraints associated
/// with the template.
TDK_ConstraintsNotSatisfied,
/// Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure,
/// CUDA Target attributes do not match.
TDK_CUDATargetMismatch
};
TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult SubstituteExplicitTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo &ExplicitTemplateArgs,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
sema::TemplateDeductionInfo &Info);
/// brief A function argument from which we performed template argument
// deduction for a call.
struct OriginalCallArg {
OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
unsigned ArgIdx, QualType OriginalArgType)
: OriginalParamType(OriginalParamType),
DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
OriginalArgType(OriginalArgType) {}
QualType OriginalParamType;
bool DecomposedParam;
unsigned ArgIdx;
QualType OriginalArgType;
};
TemplateDeductionResult FinishTemplateArgumentDeduction(
FunctionTemplateDecl *FunctionTemplate,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
bool PartialOverloading = false,
llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
TemplateDeductionResult DeduceTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
bool PartialOverloading,
llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ArgFunctionType,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
QualType ToType,
CXXConversionDecl *&Specialization,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool IsAddressOfFunction = false);
/// Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// Completely replace the \c auto in \p TypeWithAuto by
/// \p Replacement. This does not retain any \c auto type sugar.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
/// Result type of DeduceAutoType.
enum DeduceAutoResult {
DAR_Succeeded,
DAR_Failed,
DAR_FailedAlreadyDiagnosed
};
DeduceAutoResult
DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None);
DeduceAutoResult
DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
Optional<unsigned> DependentDeductionDepth = None);
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
bool Diagnose = true);
/// Declare implicit deduction guides for a class template if we've
/// not already done so.
void DeclareImplicitDeductionGuides(TemplateDecl *Template,
SourceLocation Loc);
QualType DeduceTemplateSpecializationFromInitializer(
TypeSourceInfo *TInfo, const InitializedEntity &Entity,
const InitializationKind &Kind, MultiExprArg Init);
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
QualType Type, TypeSourceInfo *TSI,
SourceRange Range, bool DirectInit,
Expr *Init);
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
SourceLocation ReturnLoc,
Expr *&RetExpr, AutoType *AT);
FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
FunctionTemplateDecl *FT2,
SourceLocation Loc,
TemplatePartialOrderingContext TPOC,
unsigned NumCallArguments1,
unsigned NumCallArguments2);
UnresolvedSetIterator
getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
TemplateSpecCandidateSet &FailedCandidates,
SourceLocation Loc,
const PartialDiagnostic &NoneDiag,
const PartialDiagnostic &AmbigDiag,
const PartialDiagnostic &CandidateDiag,
bool Complain = true, QualType TargetType = QualType());
ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(
ClassTemplatePartialSpecializationDecl *PS1,
ClassTemplatePartialSpecializationDecl *PS2,
SourceLocation Loc);
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
VarTemplatePartialSpecializationDecl *PS1,
VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
sema::TemplateDeductionInfo &Info);
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc);
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
bool OnlyDeduced,
unsigned Depth,
llvm::SmallBitVector &Used);
void MarkDeducedTemplateParameters(
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced) {
return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
}
static void MarkDeducedTemplateParameters(ASTContext &Ctx,
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced);
//===--------------------------------------------------------------------===//
// C++ Template Instantiation
//
MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl *D,
const TemplateArgumentList *Innermost = nullptr,
bool RelativeToPrimary = false,
const FunctionDecl *Pattern = nullptr);
/// A context in which code is being synthesized (where a source location
/// alone is not sufficient to identify the context). This covers template
/// instantiation and various forms of implicitly-generated functions.
struct CodeSynthesisContext {
/// The kind of template instantiation we are performing
enum SynthesisKind {
/// We are instantiating a template declaration. The entity is
/// the declaration we're instantiating (e.g., a CXXRecordDecl).
TemplateInstantiation,
/// We are instantiating a default argument for a template
/// parameter. The Entity is the template parameter whose argument is
/// being instantiated, the Template is the template, and the
/// TemplateArgs/NumTemplateArguments provide the template arguments as
/// specified.
DefaultTemplateArgumentInstantiation,
/// We are instantiating a default argument for a function.
/// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
/// provides the template arguments as specified.
DefaultFunctionArgumentInstantiation,
/// We are substituting explicit template arguments provided for
/// a function template. The entity is a FunctionTemplateDecl.
ExplicitTemplateArgumentSubstitution,
/// We are substituting template argument determined as part of
/// template argument deduction for either a class template
/// partial specialization or a function template. The
/// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
/// a TemplateDecl.
DeducedTemplateArgumentSubstitution,
/// We are substituting prior template arguments into a new
/// template parameter. The template parameter itself is either a
/// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
PriorTemplateArgumentSubstitution,
/// We are checking the validity of a default template argument that
/// has been used when naming a template-id.
DefaultTemplateArgumentChecking,
/// We are computing the exception specification for a defaulted special
/// member function.
ExceptionSpecEvaluation,
/// We are instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation,
/// We are declaring an implicit special member function.
DeclaringSpecialMember,
/// We are declaring an implicit 'operator==' for a defaulted
/// 'operator<=>'.
DeclaringImplicitEqualityComparison,
/// We are defining a synthesized function (such as a defaulted special
/// member).
DefiningSynthesizedFunction,
// We are checking the constraints associated with a constrained entity or
// the constraint expression of a concept. This includes the checks that
// atomic constraints have the type 'bool' and that they can be constant
// evaluated.
ConstraintsCheck,
// We are substituting template arguments into a constraint expression.
ConstraintSubstitution,
/// We are rewriting a comparison operator in terms of an operator<=>.
RewritingOperatorAsSpaceship,
/// Added for Template instantiation observation.
/// Memoization means we are _not_ instantiating a template because
/// it is already instantiated (but we entered a context where we
/// would have had to if it was not already instantiated).
Memoization
} Kind;
/// Was the enclosing context a non-instantiation SFINAE context?
bool SavedInNonInstantiationSFINAEContext;
/// The point of instantiation or synthesis within the source code.
SourceLocation PointOfInstantiation;
/// The entity that is being synthesized.
Decl *Entity;
/// The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
// FIXME: Wrap this union around more members, or perhaps store the
// kind-specific members in the RAII object owning the context.
union {
/// The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
/// The special member being declared or defined.
CXXSpecialMember SpecialMember;
};
ArrayRef<TemplateArgument> template_arguments() const {
assert(Kind != DeclaringSpecialMember);
return {TemplateArgs, NumTemplateArgs};
}
/// The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
CodeSynthesisContext()
: Kind(TemplateInstantiation),
SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
DeductionInfo(nullptr) {}
/// Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
};
/// List of active code synthesis contexts.
///
/// This vector is treated as a stack. As synthesis of one entity requires
/// synthesis of another, additional contexts are pushed onto the stack.
SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
/// Specializations whose definitions are currently being instantiated.
llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
/// Non-dependent types used in templates that have already been instantiated
/// by some template instantiation.
llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
/// Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
/// Cache of additional modules that should be used for name lookup
/// within the current template instantiation. Computed lazily; use
/// getLookupModules() to get a complete set.
llvm::DenseSet<Module*> LookupModulesCache;
/// Get the set of additional modules that should be checked during
/// name lookup. A module and its imports become visible when instanting a
/// template defined within it.
llvm::DenseSet<Module*> &getLookupModules();
/// Map from the most recent declaration of a namespace to the most
/// recent visible declaration of that namespace.
llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
/// Whether we are in a SFINAE context that is not associated with
/// template instantiation.
///
/// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
/// of a template instantiation or template argument deduction.
bool InNonInstantiationSFINAEContext;
/// The number of \p CodeSynthesisContexts that are not template
/// instantiations and, therefore, should not be counted as part of the
/// instantiation depth.
///
/// When the instantiation depth reaches the user-configurable limit
/// \p LangOptions::InstantiationDepth we will abort instantiation.
// FIXME: Should we have a similar limit for other forms of synthesis?
unsigned NonInstantiationEntries;
/// The depth of the context stack at the point when the most recent
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant context stacks
/// when there are multiple errors or warnings in the same instantiation.
// FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
unsigned LastEmittedCodeSynthesisContextDepth = 0;
/// The template instantiation callbacks to trace or track
/// instantiations (objects can be chained).
///
/// This callbacks is used to print, trace or track template
/// instantiations as they are being constructed.
std::vector<std::unique_ptr<TemplateInstantiationCallback>>
TemplateInstCallbacks;
/// The current index into pack expansion arguments that will be
/// used for substitution of parameter packs.
///
/// The pack expansion index will be -1 to indicate that parameter packs
/// should be instantiated as themselves. Otherwise, the index specifies
/// which argument within the parameter pack will be used for substitution.
int ArgumentPackSubstitutionIndex;
/// RAII object used to change the argument pack substitution index
/// within a \c Sema object.
///
/// See \c ArgumentPackSubstitutionIndex for more information.
class ArgumentPackSubstitutionIndexRAII {
Sema &Self;
int OldSubstitutionIndex;
public:
ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
: Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
}
~ArgumentPackSubstitutionIndexRAII() {
Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
}
};
friend class ArgumentPackSubstitutionRAII;
/// For each declaration that involved template argument deduction, the
/// set of diagnostics that were suppressed during that template argument
/// deduction.
///
/// FIXME: Serialize this structure to the AST file.
typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
SuppressedDiagnosticsMap;
SuppressedDiagnosticsMap SuppressedDiagnostics;
/// A stack object to be created when performing template
/// instantiation.
///
/// Construction of an object of type \c InstantiatingTemplate
/// pushes the current instantiation onto the stack of active
/// instantiations. If the size of this stack exceeds the maximum
/// number of recursive template instantiations, construction
/// produces an error and evaluates true.
///
/// Destruction of this object will pop the named instantiation off
/// the stack.
struct InstantiatingTemplate {
/// Note that we are instantiating a class template,
/// function template, variable template, alias template,
/// or a member thereof.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Decl *Entity,
SourceRange InstantiationRange = SourceRange());
struct ExceptionSpecification {};
/// Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateParameter Param, TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting either explicitly-specified or
/// deduced template arguments during function template argument deduction.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionTemplateDecl *FunctionTemplate,
ArrayRef<TemplateArgument> TemplateArgs,
CodeSynthesisContext::SynthesisKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template declaration.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a class template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ClassTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating as part of template
/// argument deduction for a variable template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
VarTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// Note that we are instantiating a default argument for a function
/// parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParmVarDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// Note that we are substituting prior template arguments into a
/// non-type parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
NonTypeTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are substituting prior template arguments into a
/// template template parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
TemplateTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// Note that we are checking the default template argument
/// against the template parameter for a given template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
NamedDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
struct ConstraintsCheck {};
/// \brief Note that we are checking the constraints associated with some
/// constrained entity (a concept declaration or a template with associated
/// constraints).
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ConstraintsCheck, NamedDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
struct ConstraintSubstitution {};
/// \brief Note that we are checking a constraint expression associated
/// with a template declaration or as part of the satisfaction check of a
/// concept.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ConstraintSubstitution, NamedDecl *Template,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange);
/// Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
/// Determine whether we are already instantiating this
/// specialization in some surrounding active instantiation.
bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
private:
Sema &SemaRef;
bool Invalid;
bool AlreadyInstantiating;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
Decl *Entity, NamedDecl *Template = nullptr,
ArrayRef<TemplateArgument> TemplateArgs = None,
sema::TemplateDeductionInfo *DeductionInfo = nullptr);
InstantiatingTemplate(const InstantiatingTemplate&) = delete;
InstantiatingTemplate&
operator=(const InstantiatingTemplate&) = delete;
};
void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
void popCodeSynthesisContext();
/// Determine whether we are currently performing template instantiation.
bool inTemplateInstantiation() const {
return CodeSynthesisContexts.size() > NonInstantiationEntries;
}
void PrintContextStack() {
if (!CodeSynthesisContexts.empty() &&
CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
PrintInstantiationStack();
LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
}
if (PragmaAttributeCurrentTargetDecl)
PrintPragmaAttributeInstantiationPoint();
}
void PrintInstantiationStack();
void PrintPragmaAttributeInstantiationPoint();
/// Determines whether we are currently in a context where
/// template argument substitution failures are not considered
/// errors.
///
/// \returns An empty \c Optional if we're not in a SFINAE context.
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5.
bool isUnevaluatedContext() const {
assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context");
return ExprEvalContexts.back().isUnevaluated();
}
/// RAII class used to determine whether SFINAE has
/// trapped any errors that occur during template argument
/// deduction.
class SFINAETrap {
Sema &SemaRef;
unsigned PrevSFINAEErrors;
bool PrevInNonInstantiationSFINAEContext;
bool PrevAccessCheckingSFINAE;
bool PrevLastDiagnosticIgnored;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
PrevLastDiagnosticIgnored(
SemaRef.getDiagnostics().isLastDiagnosticIgnored())
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
SemaRef.getDiagnostics().setLastDiagnosticIgnored(
PrevLastDiagnosticIgnored);
}
/// Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// RAII class used to indicate that we are performing provisional
/// semantic analysis to determine the validity of a construct, so
/// typo-correction and diagnostics in the immediate context (not within
/// implicitly-instantiated templates) should be suppressed.
class TentativeAnalysisScope {
Sema &SemaRef;
// FIXME: Using a SFINAETrap for this is a hack.
SFINAETrap Trap;
bool PrevDisableTypoCorrection;
public:
explicit TentativeAnalysisScope(Sema &SemaRef)
: SemaRef(SemaRef), Trap(SemaRef, true),
PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
SemaRef.DisableTypoCorrection = true;
}
~TentativeAnalysisScope() {
SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
}
};
/// The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// A cache containing identifiers for which typo correction failed and
/// their locations, so that repeated attempts to correct an identifier in a
/// given location are ignored if typo correction already failed for it.
IdentifierSourceLocations TypoCorrectionFailures;
/// Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// An entity for which implicit template instantiation is required.
///
/// The source location associated with the declaration is the first place in
/// the source code where the declaration was "used". It is not necessarily
/// the point of instantiation (which will be either before or after the
/// namespace-scope declaration that triggered this implicit instantiation),
/// However, it is the location that diagnostics should generally refer to,
/// because users will need to know what code triggered the instantiation.
typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
/// The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
/// Queue of implicit template instantiations that cannot be performed
/// eagerly.
SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
class GlobalEagerInstantiationScope {
public:
GlobalEagerInstantiationScope(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
void perform() {
if (Enabled) {
S.DefineUsedVTables();
S.PerformPendingInstantiations();
}
}
~GlobalEagerInstantiationScope() {
if (!Enabled) return;
// Restore the set of pending vtables.
assert(S.VTableUses.empty() &&
"VTableUses should be empty before it is discarded.");
S.VTableUses.swap(SavedVTableUses);
// Restore the set of pending implicit instantiations.
assert(S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded.");
S.PendingInstantiations.swap(SavedPendingInstantiations);
}
private:
Sema &S;
SmallVector<VTableUse, 16> SavedVTableUses;
std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
bool Enabled;
};
/// The queue of implicit template instantiations that are required
/// and must be performed within the current local scope.
///
/// This queue is only used for member functions of local classes in
/// templates, which must be instantiated in the same scope as their
/// enclosing function, so that they can reference function-local
/// types, static variables, enumerators, etc.
std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
class LocalEagerInstantiationScope {
public:
LocalEagerInstantiationScope(Sema &S) : S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
~LocalEagerInstantiationScope() {
assert(S.PendingLocalImplicitInstantiations.empty() &&
"there shouldn't be any pending local implicit instantiations");
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
private:
Sema &S;
std::deque<PendingImplicitInstantiation>
SavedPendingLocalImplicitInstantiations;
};
/// A helper class for building up ExtParameterInfos.
class ExtParameterInfoBuilder {
SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
bool HasInteresting = false;
public:
/// Set the ExtParameterInfo for the parameter at the given index,
///
void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
assert(Infos.size() <= index);
Infos.resize(index);
Infos.push_back(info);
if (!HasInteresting)
HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
}
/// Return a pointer (suitable for setting in an ExtProtoInfo) to the
/// ExtParameterInfo array we've built up.
const FunctionProtoType::ExtParameterInfo *
getPointerOrNull(unsigned numParams) {
if (!HasInteresting) return nullptr;
Infos.resize(numParams);
return Infos.data();
}
};
void PerformPendingInstantiations(bool LocalOnly = false);
TypeSourceInfo *SubstType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity,
bool AllowDeducedTST = false);
QualType SubstType(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstType(TypeLoc TL,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc,
DeclarationName Entity,
CXXRecordDecl *ThisContext,
Qualifiers ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
const MultiLevelTemplateArgumentList &Args);
bool SubstExceptionSpec(SourceLocation Loc,
FunctionProtoType::ExceptionSpecInfo &ESI,
SmallVectorImpl<QualType> &ExceptionStorage,
const MultiLevelTemplateArgumentList &Args);
ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment,
Optional<unsigned> NumExpansions,
bool ExpectParameterPack);
bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<QualType> &ParamTypes,
SmallVectorImpl<ParmVarDecl *> *OutParams,
ExtParameterInfoBuilder &ParamInfos);
ExprResult SubstExpr(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Substitute the given template arguments into a list of
/// expressions, expanding pack expansions if required.
///
/// \param Exprs The list of expressions to substitute into.
///
/// \param IsCall Whether this is some form of call, in which case
/// default arguments will be dropped.
///
/// \param TemplateArgs The set of template arguments to substitute.
///
/// \param Outputs Will receive all of the substituted arguments.
///
/// \returns true if an error occurred, false otherwise.
bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<Expr *> &Outputs);
StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateParameterList *
SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
Decl *SubstDecl(Decl *D, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// Substitute the name and return type of a defaulted 'operator<=>' to form
/// an implicit 'operator=='.
FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
FunctionDecl *Spaceship);
ExprResult SubstInitializer(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool CXXDirectInit);
bool
SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
InstantiateClass(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK,
bool Complain = true);
bool InstantiateEnum(SourceLocation PointOfInstantiation,
EnumDecl *Instantiation, EnumDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
bool InstantiateInClassInitializer(
SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
struct LateInstantiatedAttribute {
const Attr *TmplAttr;
LocalInstantiationScope *Scope;
Decl *NewDecl;
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
Decl *D)
: TmplAttr(A), Scope(S), NewDecl(D)
{ }
};
typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
void
InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
bool usesPartialOrExplicitSpecialization(
SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
bool
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK,
bool Complain = true);
void InstantiateClassMembers(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
void InstantiateClassTemplateSpecializationMembers(
SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK);
NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
SourceLocation Loc,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
TemplateArgumentListInfo &Result,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
FunctionDecl *Function);
FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
const TemplateArgumentList *Args,
SourceLocation Loc);
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
FunctionDecl *Function,
bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
SourceLocation PointOfInstantiation, void *InsertPos,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
const MultiLevelTemplateArgumentList &TemplateArgs);
void
BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs,
LateInstantiatedAttrVec *LateAttrs,
DeclContext *Owner,
LocalInstantiationScope *StartingScope,
bool InstantiatingVarTemplate = false,
VarTemplateSpecializationDecl *PrevVTSD = nullptr);
VarDecl *getVarTemplateSpecialization(
VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs,
const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc);
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
VarDecl *Var, bool Recursive = false,
bool DefinitionRequired = false,
bool AtEndOfTU = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool FindingInstantiatedContext = false);
DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
const MultiLevelTemplateArgumentList &TemplateArgs);
// Objective-C declarations.
enum ObjCContainerKind {
OCK_None = -1,
OCK_Interface = 0,
OCK_Protocol,
OCK_Category,
OCK_ClassExtension,
OCK_Implementation,
OCK_CategoryImplementation
};
ObjCContainerKind getObjCContainerKind() const;
DeclResult actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType typeBound);
ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParams,
SourceLocation rAngleLoc);
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
Decl *ActOnStartClassInterface(
Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName, SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
void ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange);
void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
SmallVectorImpl<SourceLocation> &ProtocolLocs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc);
Decl *ActOnCompatibilityAlias(
SourceLocation AtCompatibilityAliasLoc,
IdentifierInfo *AliasName, SourceLocation AliasLocation,
IdentifierInfo *ClassName, SourceLocation ClassLocation);
bool CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &PLoc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList);
Decl *ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryInterface(
SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc,
const ParsedAttributesView &AttrList);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc,
const ParsedAttributesView &AttrList);
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
ArrayRef<Decl *> Decls);
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts);
DeclGroupPtrTy
ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
ArrayRef<IdentifierLocPair> IdentList,
const ParsedAttributesView &attrList);
void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
ArrayRef<IdentifierLocPair> ProtocolId,
SmallVectorImpl<Decl *> &Protocols);
void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
SourceLocation ProtocolLoc,
IdentifierInfo *TypeArgId,
SourceLocation TypeArgLoc,
bool SelectProtocolFirst = false);
/// Given a list of identifiers (and their locations), resolve the
/// names to either Objective-C protocol qualifiers or type
/// arguments, as appropriate.
void actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols);
/// Build a an Objective-C protocol-qualified 'id' type where no
/// base type was specified.
TypeResult actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc,
ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs,
SourceLocation rAngleLoc);
/// Build a specialized and/or protocol-qualified Objective-C type.
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S,
SourceLocation Loc,
ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc);
/// Build an Objective-C type parameter type.
QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Build an Objective-C object pointer type.
QualType BuildObjCObjectType(QualType BaseType,
SourceLocation Loc,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Ensure attributes are consistent with type.
/// \param [in, out] Attributes The attributes to check; they will
/// be modified to be consistent with \p PropertyTy.
void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
SourceLocation Loc,
unsigned &Attributes,
bool propertyInPrimaryClass);
/// Process the specified property declaration and create decls for the
/// setters and getters as needed.
/// \param property The property declaration being processed
void ProcessPropertyDecl(ObjCPropertyDecl *property);
void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
ObjCPropertyDecl *SuperProperty,
const IdentifierInfo *Name,
bool OverridingProtocolProperty);
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID);
Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
ArrayRef<Decl *> allMethods = None,
ArrayRef<DeclGroupPtrTy> allTUVars = None);
Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD, ObjCDeclSpec &ODS,
Selector GetterSel, Selector SetterSel,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
Decl *ActOnPropertyImplDecl(Scope *S,
SourceLocation AtLoc,
SourceLocation PropertyLoc,
bool ImplKind,
IdentifierInfo *PropertyId,
IdentifierInfo *PropertyIvar,
SourceLocation PropertyIvarLoc,
ObjCPropertyQueryKind QueryKind);
enum ObjCSpecialMethodKind {
OSMK_None,
OSMK_Alloc,
OSMK_New,
OSMK_Copy,
OSMK_RetainingInit,
OSMK_NonRetainingInit
};
struct ObjCArgInfo {
IdentifierInfo *Name;
SourceLocation NameLoc;
// The Type is null if no type was specified, and the DeclSpec is invalid
// in this case.
ParsedType Type;
ObjCDeclSpec DeclSpec;
/// ArgAttrs - Attribute list for this argument.
ParsedAttributesView ArgAttrs;
};
Decl *ActOnMethodDeclaration(
Scope *S,
SourceLocation BeginLoc, // location of the + or -.
SourceLocation EndLoc, // location of the ; or {.
tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
// optional arguments. The number of types/arguments is obtained
// from the Sel.getNumArgs().
ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
unsigned CNumArgs, // c-style args
const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
bool isVariadic, bool MethodDefinition);
ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool IsInstance);
ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
bool IsInstance);
bool CheckARCMethodDecl(ObjCMethodDecl *method);
bool inferObjCARCLifetime(ValueDecl *decl);
void deduceOpenCLAddressSpace(ValueDecl *decl);
ExprResult
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr,
SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super);
ExprResult
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc);
ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
/// Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// The message is sent to 'super'.
ObjCSuperMessage,
/// The message is an instance message.
ObjCInstanceMessage,
/// The message is a class message, and the identifier is a type
/// name.
ObjCClassMessage
};
ObjCMessageKind getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType);
ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr);
ExprResult ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr);
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind);
bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs, bool Diagnose = true);
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr, bool Diagnose = true);
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr,
bool Diagnose = true);
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
/// Check whether the given new method is a valid override of the
/// given overridden method, and set any properties that should be inherited.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden);
/// Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
/// Check whether the declared result type of the given Objective-C
/// method declaration is compatible with the method's class.
ResultTypeCompatibilityKind
checkRelatedResultTypeCompatibility(const ObjCMethodDecl *Method,
const ObjCInterfaceDecl *CurrentClass);
void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
ObjCMethodDecl *overridden);
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC);
enum PragmaOptionsAlignKind {
POAK_Native, // #pragma options align=native
POAK_Natural, // #pragma options align=natural
POAK_Packed, // #pragma options align=packed
POAK_Power, // #pragma options align=power
POAK_Mac68k, // #pragma options align=mac68k
POAK_Reset // #pragma options align=reset
};
/// ActOnPragmaClangSection - Called on well formed \#pragma clang section
void ActOnPragmaClangSection(SourceLocation PragmaLoc,
PragmaClangSectionAction Action,
PragmaClangSectionKind SecKind, StringRef SecName);
/// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc);
/// ActOnPragmaPack - Called on well formed \#pragma pack(...).
void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
StringRef SlotLabel, Expr *Alignment);
enum class PragmaPackDiagnoseKind {
NonDefaultStateAtInclude,
ChangedStateAtExit
};
void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind,
SourceLocation IncludeLoc);
void DiagnoseUnterminatedPragmaPack();
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
/// ActOnPragmaMSComment - Called on well formed
/// \#pragma comment(kind, "arg").
void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
StringRef Arg);
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
SourceLocation PragmaLoc,
MSVtorDispMode Value);
enum PragmaSectionKind {
PSK_DataSeg,
PSK_BSSSeg,
PSK_ConstSeg,
PSK_CodeSeg,
};
bool UnifySection(StringRef SectionName,
int SectionFlags,
DeclaratorDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
/// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm::StringRef PragmaName);
/// Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// Called on #pragma clang __debug dump II
void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
StringRef Value);
/// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
void ActOnPragmaUnused(const Token &Identifier,
Scope *curScope,
SourceLocation PragmaLoc);
/// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
void ActOnPragmaVisibility(const IdentifierInfo* VisType,
SourceLocation PragmaLoc);
NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
SourceLocation Loc);
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
/// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
void ActOnPragmaWeakID(IdentifierInfo* WeakName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc);
/// ActOnPragmaRedefineExtname - Called on well formed
/// \#pragma redefine_extname oldname newname.
void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaFPContract - Called on well formed
/// \#pragma {STDC,OPENCL} FP_CONTRACT and
/// \#pragma clang fp contract
void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC);
/// ActOnPragmaFenvAccess - Called on well formed
/// \#pragma STDC FENV_ACCESS
void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC);
/// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
/// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
void AddAlignmentAttributesForRecord(RecordDecl *RD);
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
/// FreePackedContext - Deallocate and null out PackContext.
void FreePackedContext();
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc);
/// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
/// add an appropriate visibility attribute.
void AddPushedVisibilityAttribute(Decl *RD);
/// PopPragmaVisibility - Pop the top element of the visibility stack; used
/// for '\#pragma GCC visibility' and visibility attributes on namespaces.
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
/// FreeVisContext - Deallocate and null out VisContext.
void FreeVisContext();
/// AddCFAuditedAttribute - Check whether we're currently within
/// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
/// the appropriate attribute.
void AddCFAuditedAttribute(Decl *D);
void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
SourceLocation PragmaLoc,
attr::ParsedSubjectMatchRuleSet Rules);
void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Called on well-formed '\#pragma clang attribute pop'.
void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
const IdentifierInfo *Namespace);
/// Adds the attributes that have been specified using the
/// '\#pragma clang attribute push' directives to the given declaration.
void AddPragmaAttributes(Scope *S, Decl *D);
void DiagnoseUnterminatedPragmaAttribute();
/// Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// Get the location for the currently active "\#pragma clang optimize
/// off". If this location is invalid, then the state of the pragma is "on".
SourceLocation getOptimizeOffPragmaLocation() const {
return OptimizeOffPragmaLocation;
}
/// Only called on function definitions; if there is a pragma in scope
/// with the effect of a range-based optnone, consider marking the function
/// with attribute optnone.
void AddRangeBasedOptnone(FunctionDecl *FD);
/// Adds the 'optnone' attribute to the function declaration if there
/// are no conflicts; Loc represents the location causing the 'optnone'
/// attribute to be added (usually because of a pragma).
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
bool IsPackExpansion);
void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
Expr *OE);
/// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
/// declaration.
void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *ParamExpr);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *MaxThreads, Expr *MinBlocks);
/// AddModeAttr - Adds a mode attribute to a particular declaration.
void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
bool InInstantiation = false);
void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
ParameterABI ABI);
enum class RetainOwnershipKind {NS, CF, OS};
void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
RetainOwnershipKind K, bool IsTemplateInstantiation);
/// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
/// attribute to a particular declaration.
void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *Min, Expr *Max);
/// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
/// particular declaration.
void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
Expr *Min, Expr *Max);
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
//===--------------------------------------------------------------------===//
// C++ Coroutines TS
//
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
StringRef Keyword);
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
UnresolvedLookupExpr* Lookup);
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
bool IsImplicit = false);
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
bool buildCoroutineParameterMoves(SourceLocation Loc);
VarDecl *buildCoroutinePromise(SourceLocation Loc);
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
SourceLocation FuncLoc);
//===--------------------------------------------------------------------===//
// OpenCL extensions.
//
private:
std::string CurrOpenCLExtension;
/// Extensions required by an OpenCL type.
llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap;
/// Extensions required by an OpenCL declaration.
llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap;
public:
llvm::StringRef getCurrentOpenCLExtension() const {
return CurrOpenCLExtension;
}
/// Check if a function declaration \p FD associates with any
/// extensions present in OpenCLDeclExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD);
/// Check if a function type \p FT associates with any
/// extensions present in OpenCLTypeExtMap and if so return the
/// extension(s) name(s).
std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT);
/// Find an extension in an appropriate extension map and return its name
template<typename T, typename MapT>
std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map);
void setCurrentOpenCLExtension(llvm::StringRef Ext) {
CurrOpenCLExtension = Ext;
}
/// Set OpenCL extensions for a type which can only be used when these
/// OpenCL extensions are enabled. If \p Exts is empty, do nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts);
/// Set OpenCL extensions for a declaration which can only be
/// used when these OpenCL extensions are enabled. If \p Exts is empty, do
/// nothing.
/// \param Exts A space separated list of OpenCL extensions.
void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts);
/// Set current OpenCL extensions for a type which can only be used
/// when these OpenCL extensions are enabled. If current OpenCL extension is
/// empty, do nothing.
void setCurrentOpenCLExtensionForType(QualType T);
/// Set current OpenCL extensions for a declaration which
/// can only be used when these OpenCL extensions are enabled. If current
/// OpenCL extension is empty, do nothing.
void setCurrentOpenCLExtensionForDecl(Decl *FD);
bool isOpenCLDisabledDecl(Decl *FD);
/// Check if type \p T corresponding to declaration specifier \p DS
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T);
/// Check if declaration \p D used by expression \p E
/// is disabled due to required OpenCL extensions being disabled. If so,
/// emit diagnostics.
/// \return true if type is disabled.
bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E);
//===--------------------------------------------------------------------===//
// OpenMP directives and clauses.
//
private:
void *VarDataSharingAttributesStack;
/// Number of nested '#pragma omp declare target' directives.
unsigned DeclareTargetNestingLevel = 0;
/// Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult
VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
bool StrictlyPositive = true);
/// Returns OpenMP nesting level for current directive.
unsigned getOpenMPNestingLevel() const;
/// Adjusts the function scopes index for the target-based regions.
void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
unsigned Level) const;
/// Returns the number of scopes associated with the construct on the given
/// OpenMP level.
int getNumberOfConstructScopes(unsigned Level) const;
/// Push new OpenMP function region for non-capturing function.
void pushOpenMPFunctionRegion();
/// Pop OpenMP function region for non-capturing function.
void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
/// Check whether we're allowed to call Callee from the current function.
void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
bool CheckForDelayedContext = true);
/// Check whether we're allowed to call Callee from the current function.
void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
bool CheckCaller = true);
/// Check if the expression is allowed to be used in expressions for the
/// OpenMP devices.
void checkOpenMPDeviceExpr(const Expr *E);
/// Finishes analysis of the deferred functions calls that may be declared as
/// host/nohost during device/host compilation.
void finalizeOpenMPDelayedAnalysis();
/// Checks if a type or a declaration is disabled due to the owning extension
/// being disabled, and emits diagnostic messages if it is disabled.
/// \param D type or declaration to be checked.
/// \param DiagLoc source location for the diagnostic message.
/// \param DiagInfo information to be emitted for the diagnostic message.
/// \param SrcRange source range of the declaration.
/// \param Map maps type or declaration to the extensions.
/// \param Selector selects diagnostic message: 0 for type and 1 for
/// declaration.
/// \return true if the type or declaration is disabled.
template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo,
MapT &Map, unsigned Selector = 0,
SourceRange SrcRange = SourceRange());
/// Marks all the functions that might be required for the currently active
/// OpenMP context.
void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
FunctionDecl *Func,
bool MightBeOdrUse);
public:
/// Struct to store the context selectors info for declare variant directive.
using OMPCtxStringType = SmallString<8>;
using OMPCtxSelectorData =
OpenMPCtxSelectorData<SmallVector<OMPCtxStringType, 4>, ExprResult>;
/// Checks if the variant/multiversion functions are compatible.
bool areMultiversionVariantFunctionsCompatible(
const FunctionDecl *OldFD, const FunctionDecl *NewFD,
const PartialDiagnostic &NoProtoDiagID,
const PartialDiagnosticAt &NoteCausedDiagIDAt,
const PartialDiagnosticAt &NoSupportDiagIDAt,
const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
bool ConstexprSupported, bool CLinkageMayDiffer);
/// Function tries to capture lambda's captured variables in the OpenMP region
/// before the original lambda is captured.
void tryCaptureOpenMPLambdas(ValueDecl *V);
/// Return true if the provided declaration \a VD should be captured by
/// reference.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
/// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
unsigned OpenMPCaptureLevel) const;
/// Check if the specified variable is used in one of the private
/// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
/// constructs.
VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
unsigned StopAt = 0);
ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
ExprObjectKind OK, SourceLocation Loc);
/// If the current region is a loop-based region, mark the start of the loop
/// construct.
void startOpenMPLoop();
/// If the current region is a range loop-based region, mark the start of the
/// loop construct.
void startOpenMPCXXRangeFor();
/// Check if the specified variable is used in 'private' clause.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const;
/// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
/// for \p FD based on DSA for the provided corresponding captured declaration
/// \p D.
void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
/// Check if the specified variable is captured by 'target' directive.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const;
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// End analysis of clauses.
void EndOpenMPClause();
/// Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// Check if the current region is an OpenMP loop region and if it is,
/// mark loop control variable, used in \p Init for loop initialization, as
/// private by default.
/// \param Init First part of the for loop.
void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
// OpenMP directives and clauses.
/// Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
OpenMPDirectiveKind Kind);
/// Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// Called on well-formed '#pragma omp allocate'.
DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
ArrayRef<Expr *> VarList,
ArrayRef<OMPClause *> Clauses,
DeclContext *Owner = nullptr);
/// Called on well-formed '#pragma omp requires'.
DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
ArrayRef<OMPClause *> ClauseList);
/// Check restrictions on Requires directive
OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
ArrayRef<OMPClause *> Clauses);
/// Check if the specified type is allowed to be used in 'omp declare
/// reduction' construct.
QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name,
ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
/// Initialize declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
/// Initialize declare reduction construct initializer.
/// \return omp_priv variable.
VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
/// Finish current declare reduction construct initializer.
void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
VarDecl *OmpPrivParm);
/// Called at the end of '#pragma omp declare reduction'.
DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
/// Check variable declaration in 'omp declare mapper' construct.
TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
/// Check if the specified type is allowed to be used in 'omp declare
/// mapper' construct.
QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
TypeResult ParsedType);
/// Called on start of '#pragma omp declare mapper'.
OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart(
Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
Decl *PrevDeclInScope = nullptr);
/// Build the mapper variable of '#pragma omp declare mapper'.
void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
Scope *S, QualType MapperType,
SourceLocation StartLoc,
DeclarationName VN);
/// Called at the end of '#pragma omp declare mapper'.
DeclGroupPtrTy
ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
ArrayRef<OMPClause *> ClauseList);
/// Called on the start of target region i.e. '#pragma omp declare target'.
bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc);
/// Called at the end of target region i.e. '#pragme omp end declare target'.
void ActOnFinishOpenMPDeclareTargetDirective();
/// Searches for the provided declaration name for OpenMP declare target
/// directive.
NamedDecl *
lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id,
NamedDeclSetType &SameDirectiveDecls);
/// Called on correct id-expression from the '#pragma omp declare target'.
void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
OMPDeclareTargetDeclAttr::MapTypeTy MT,
OMPDeclareTargetDeclAttr::DevTypeTy DT);
/// Check declaration inside target region.
void
checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
SourceLocation IdLoc = SourceLocation());
/// Return true inside OpenMP declare target region.
bool isInOpenMPDeclareTargetContext() const {
return DeclareTargetNestingLevel > 0;
}
/// Return true inside OpenMP target region.
bool isInOpenMPTargetExecutionDirective() const;
/// Return the number of captured regions created for an OpenMP directive.
static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
/// Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// End of OpenMP region.
///
/// \param S Statement associated with the current OpenMP region.
/// \param Clauses List of clauses for the current OpenMP region.
///
/// \returns Statement for finished OpenMP region.
StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
StmtResult ActOnOpenMPExecutableDirective(
OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
using VarsWithInheritedDSAType =
llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
/// Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp for simd' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp critical' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp parallel sections' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target data' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target enter data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target exit data' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp target parallel' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// Called on well-formed '\#pragma omp taskloop' after parsing of the
/// associated statement.
StmtResult
ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp master taskloop' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master taskloop' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp parallel master taskloop simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute' after parsing
/// of the associated statement.
StmtResult
ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target update'.
StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc,
Stmt *AStmt);
/// Called on well-formed '\#pragma omp distribute parallel for' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target simd' after parsing of
/// the associated statement.
StmtResult
ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
SourceLocation StartLoc, SourceLocation EndLoc,
VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute' after parsing of
/// the associated statement.
StmtResult ActOnOpenMPTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for simd'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed '\#pragma omp target teams distribute' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for'
/// after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute parallel for
/// simd' after parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Called on well-formed '\#pragma omp target teams distribute simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
/// Checks correctness of linear modifiers.
bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
SourceLocation LinLoc);
/// Checks that the specified declaration matches requirements for the linear
/// decls.
bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
OpenMPLinearClauseKind LinKind, QualType Type);
/// Called on well-formed '\#pragma omp declare simd' after parsing of
/// the associated method/function.
DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
/// Checks '\#pragma omp declare variant' variant function and original
/// functions after parsing of the associated method/function.
/// \param DG Function declaration to which declare variant directive is
/// applied to.
/// \param VariantRef Expression that references the variant function, which
/// must be used instead of the original one, specified in \p DG.
/// \returns None, if the function/variant function are not compatible with
/// the pragma, pair of original function/variant ref expression otherwise.
Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(
DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR);
/// Called on well-formed '\#pragma omp declare variant' after parsing of
/// the associated method/function.
/// \param FD Function declaration to which declare variant directive is
/// applied to.
/// \param VariantRef Expression that references the variant function, which
/// must be used instead of the original one, specified in \p DG.
/// \param Data Set of context-specific data for the specified context
/// selector.
void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef,
SourceRange SR,
ArrayRef<OMPCtxSelectorData> Data);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'allocator' clause.
OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation NameModifierLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simdlen' clause.
OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'ordered' clause.
OMPClause *
ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
SourceLocation LParenLoc = SourceLocation(),
Expr *NumForLoops = nullptr);
/// Called on well-formed 'grainsize' clause.
OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'num_tasks' clause.
OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'hint' clause.
OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
SourceLocation ArgumentLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'proc_bind' clause.
OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprWithArgClause(
OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
SourceLocation StartLoc, SourceLocation LParenLoc,
ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
SourceLocation EndLoc);
/// Called on well-formed 'schedule' clause.
OMPClause *ActOnOpenMPScheduleClause(
OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'threads' clause.
OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'simd' clause.
OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'nogroup' clause.
OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'unified_address' clause.
OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reverse_offload' clause.
OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dynamic_allocators' clause.
OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// Called on well-formed 'atomic_default_mem_order' clause.
OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
CXXScopeSpec &ReductionOrMapperIdScopeSpec,
DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
OpenMPLinearClauseKind LinKind,
ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
bool IsMapTypeImplicit, SourceLocation DepLinMapLoc);
/// Called on well-formed 'allocate' clause.
OMPClause *
ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation ColonLoc,
SourceLocation LParenLoc, SourceLocation EndLoc);
/// Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'firstprivate' clause.
OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'lastprivate' clause.
OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'reduction' clause.
OMPClause *ActOnOpenMPReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'task_reduction' clause.
OMPClause *ActOnOpenMPTaskReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'in_reduction' clause.
OMPClause *ActOnOpenMPInReductionClause(
ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId,
ArrayRef<Expr *> UnresolvedReductions = llvm::None);
/// Called on well-formed 'linear' clause.
OMPClause *
ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
SourceLocation StartLoc, SourceLocation LParenLoc,
OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
SourceLocation ColonLoc, SourceLocation EndLoc);
/// Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'device' clause.
OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'map' clause.
OMPClause *
ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
ArrayRef<SourceLocation> MapTypeModifiersLoc,
CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
SourceLocation MapLoc, SourceLocation ColonLoc,
ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'num_teams' clause.
OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'thread_limit' clause.
OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'priority' clause.
OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// Called on well-formed 'dist_schedule' clause.
OMPClause *ActOnOpenMPDistScheduleClause(
OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
SourceLocation CommaLoc, SourceLocation EndLoc);
/// Called on well-formed 'defaultmap' clause.
OMPClause *ActOnOpenMPDefaultmapClause(
OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
SourceLocation KindLoc, SourceLocation EndLoc);
/// Called on well-formed 'to' clause.
OMPClause *
ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId,
const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'from' clause.
OMPClause *ActOnOpenMPFromClause(
ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec,
DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs,
ArrayRef<Expr *> UnresolvedMappers = llvm::None);
/// Called on well-formed 'use_device_ptr' clause.
OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'is_device_ptr' clause.
OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
const OMPVarListLocTy &Locs);
/// Called on well-formed 'nontemporal' clause.
OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// The kind of conversion being performed.
enum CheckedConversionKind {
/// An implicit conversion.
CCK_ImplicitConversion,
/// A C-style cast.
CCK_CStyleCast,
/// A functional-style cast.
CCK_FunctionalCast,
/// A cast other than a C-style cast.
CCK_OtherCast,
/// A conversion for an operand of a builtin overloaded operator.
CCK_ForBuiltinOverloadedOp
};
static bool isCast(CheckedConversionKind CCK) {
return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
CCK == CCK_OtherCast;
}
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
/// cast. If there is already an implicit cast, merge into the existing one.
/// If isLvalue, the result of the cast is an lvalue.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
ExprValueKind VK = VK_RValue,
const CXXCastPath *BasePath = nullptr,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
/// IgnoredValueConversions - Given that an expression's result is
/// syntactically ignored, perform any conversions that are
/// required.
ExprResult IgnoredValueConversions(Expr *E);
// UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
// DefaultFunctionArrayLvalueConversion - converts functions and
// arrays to their respective pointers and performs the
// lvalue-to-rvalue conversion.
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
bool Diagnose = true);
// DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
// the operand. This is DefaultFunctionArrayLvalueConversion,
// except that it assumes the operand isn't of function or array
// type.
ExprResult DefaultLvalueConversion(Expr *E);
// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
// do not have a prototype. Integer promotions are performed on each
// argument, and arguments that have type float are promoted to double.
ExprResult DefaultArgumentPromotion(Expr *E);
/// If \p E is a prvalue denoting an unmaterialized temporary, materialize
/// it as an xvalue. In C++98, the result will still be a prvalue, because
/// we don't have xvalues there.
ExprResult TemporaryMaterializationConversion(Expr *E);
// Used for emitting the right warning by DefaultVariadicArgumentPromotion
enum VariadicCallType {
VariadicFunction,
VariadicBlock,
VariadicMethod,
VariadicConstructor,
VariadicDoesNotApply
};
VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
const FunctionProtoType *Proto,
Expr *Fn);
// Used for determining in which context a type is allowed to be passed to a
// vararg function.
enum VarArgKind {
VAK_Valid,
VAK_ValidInCXX11,
VAK_Undefined,
VAK_MSVCUndefined,
VAK_Invalid
};
// Determines which VarArgKind fits an expression.
VarArgKind isValidVarArgType(const QualType &Ty);
/// Check to see if the given expression is a valid argument to a variadic
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType = VariadicDoesNotApply,
bool AllowExplicit = false,
bool IsListInitialization = false);
// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
// will create a runtime trap if the resulting type is not a POD type.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl);
/// Context in which we're performing a usual arithmetic conversion.
enum ArithConvKind {
/// An arithmetic operation.
ACK_Arithmetic,
/// A bitwise operation.
ACK_BitwiseOp,
/// A comparison.
ACK_Comparison,
/// A conditional (?:) operator.
ACK_Conditional,
/// A compound assignment expression.
ACK_CompAssign,
};
// UsualArithmeticConversions - performs the UsualUnaryConversions on it's
// operands and then handles various conversions that are common to binary
// operators (C99 6.3.1.8). If both operands aren't arithmetic, this
// routine returns the first non-arithmetic type found. The client is
// responsible for emitting appropriate error diagnostics.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, ArithConvKind ACK);
/// AssignConvertType - All of the 'assignment' semantic checks return this
/// enum to indicate whether the assignment was allowed. These checks are
/// done for simple assignments, as well as initialization, return from
/// function, argument passing, etc. The query is phrased in terms of a
/// source and destination type.
enum AssignConvertType {
/// Compatible - the types are compatible according to the standard.
Compatible,
/// PointerToInt - The assignment converts a pointer to an int, which we
/// accept as an extension.
PointerToInt,
/// IntToPointer - The assignment converts an int to a pointer, which we
/// accept as an extension.
IntToPointer,
/// FunctionVoidPointer - The assignment is between a function pointer and
/// void*, which the standard doesn't allow, but we accept as an extension.
FunctionVoidPointer,
/// IncompatiblePointer - The assignment is between two pointers types that
/// are not compatible, but we accept them as an extension.
IncompatiblePointer,
/// IncompatiblePointerSign - The assignment is between two pointers types
/// which point to integers which have a different sign, but are otherwise
/// identical. This is a subset of the above, but broken out because it's by
/// far the most common case of incompatible pointers.
IncompatiblePointerSign,
/// CompatiblePointerDiscardsQualifiers - The assignment discards
/// c/v/r qualifiers, which we accept as an extension.
CompatiblePointerDiscardsQualifiers,
/// IncompatiblePointerDiscardsQualifiers - The assignment
/// discards qualifiers that we don't permit to be discarded,
/// like address spaces.
IncompatiblePointerDiscardsQualifiers,
/// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
/// changes address spaces in nested pointer types which is not allowed.
/// For instance, converting __private int ** to __generic int ** is
/// illegal even though __private could be converted to __generic.
IncompatibleNestedPointerAddressSpaceMismatch,
/// IncompatibleNestedPointerQualifiers - The assignment is between two
/// nested pointer types, and the qualifiers other than the first two
/// levels differ e.g. char ** -> const char **, but we accept them as an
/// extension.
IncompatibleNestedPointerQualifiers,
/// IncompatibleVectors - The assignment is between two vector types that
/// have the same size, which we accept as an extension.
IncompatibleVectors,
/// IntToBlockPointer - The assignment converts an int to a block
/// pointer. We disallow this.
IntToBlockPointer,
/// IncompatibleBlockPointer - The assignment is between two block
/// pointers types that are not compatible.
IncompatibleBlockPointer,
/// IncompatibleObjCQualifiedId - The assignment is between a qualified
/// id type and something else (that is incompatible with it). For example,
/// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
IncompatibleObjCQualifiedId,
/// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
/// object with __weak qualifier.
IncompatibleObjCWeakRef,
/// Incompatible - We reject this conversion outright, it is invalid to
/// represent it in the AST.
Incompatible
};
/// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
/// assignment conversion type specified by ConvTy. This returns true if the
/// conversion was invalid or false if the conversion was accepted.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained = nullptr);
/// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
/// enum. If AllowMask is true, then we also allow the complement of a valid
/// value, to be used as a mask.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
bool AllowMask) const;
/// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
/// integer not in the range of enum values.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
Expr *SrcExpr);
/// CheckAssignmentConstraints - Perform type checking for assignment,
/// argument passing, variable initialization, and function return values.
/// C99 6.5.16.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType,
QualType RHSType);
/// Check assignment constraints and optionally prepare for a conversion of
/// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
/// is true.
AssignConvertType CheckAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
CastKind &Kind,
bool ConvertRHS = true);
/// Check assignment constraints for an assignment of RHS to LHSType.
///
/// \param LHSType The destination type for the assignment.
/// \param RHS The source expression for the assignment.
/// \param Diagnose If \c true, diagnostics may be produced when checking
/// for assignability. If a diagnostic is produced, \p RHS will be
/// set to ExprError(). Note that this function may still return
/// without producing a diagnostic, even for an invalid assignment.
/// \param DiagnoseCFAudited If \c true, the target is a function parameter
/// in an audited Core Foundation API and does not need to be checked
/// for ARC retain issues.
/// \param ConvertRHS If \c true, \p RHS will be updated to model the
/// conversions necessary to perform the assignment. If \c false,
/// \p Diagnose must also be \c false.
AssignConvertType CheckSingleAssignmentConstraints(
QualType LHSType, ExprResult &RHS, bool Diagnose = true,
bool DiagnoseCFAudited = false, bool ConvertRHS = true);
// If the lhs type is a transparent union, check whether we
// can initialize the transparent union with the given expression.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS);
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit,
ImplicitConversionSequence& ICS);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action,
CheckedConversionKind CCK);
ExprResult PerformQualificationConversion(
Expr *E, QualType Ty, ExprValueKind VK = VK_RValue,
CheckedConversionKind CCK = CCK_ImplicitConversion);
/// the following "Check" methods will return a valid/converted QualType
/// or a null QualType (indicating an error diagnostic was issued).
/// type checking binary operators (subroutines of CreateBuiltinBinOp).
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType CheckPointerToMemberOperands( // C++ 5.5
ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
SourceLocation OpLoc, bool isIndirect);
QualType CheckMultiplyDivideOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
bool IsDivide);
QualType CheckRemainderOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckAdditionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
QualType CheckSubtractionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
QualType* CompLHSTy = nullptr);
QualType CheckShiftOperands( // C99 6.5.7
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc, bool IsCompAssign = false);
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
BinaryOperatorKind Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opcode, Expr *Op);
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opcode,
Expr *LHS, Expr *RHS);
ExprResult checkPseudoObjectRValue(Expr *E);
Expr *recreateSyntacticForm(PseudoObjectExpr *E);
QualType CheckConditionalOperands( // C99 6.5.15
ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
QualType CXXCheckConditionalOperands( // C++ 5.16
ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
bool ConvertArgs = true);
QualType FindCompositePointerType(SourceLocation Loc,
ExprResult &E1, ExprResult &E2,
bool ConvertArgs = true) {
Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
QualType Composite =
FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
E1 = E1Tmp;
E2 = E2Tmp;
return Composite;
}
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc);
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign,
bool AllowBothBool, bool AllowBoolConversion);
QualType GetSignedVectorType(QualType V);
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc,
BinaryOperatorKind Opc);
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc);
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
bool isLaxVectorConversion(QualType srcType, QualType destType);
/// type checking declaration initializers (C99 6.7.8)
bool CheckForConstantInitializer(Expr *e, QualType t);
// type checking C++ declaration initializers (C++ [dcl.init]).
/// ReferenceCompareResult - Expresses the result of comparing two
/// types (cv1 T1 and cv2 T2) to determine their compatibility for the
/// purposes of initialization by reference (C++ [dcl.init.ref]p4).
enum ReferenceCompareResult {
/// Ref_Incompatible - The two types are incompatible, so direct
/// reference binding is not possible.
Ref_Incompatible = 0,
/// Ref_Related - The two types are reference-related, which means
/// that their unqualified forms (T1 and T2) are either the same
/// or T1 is a base class of T2.
Ref_Related,
/// Ref_Compatible - The two types are reference-compatible.
Ref_Compatible
};
// Fake up a scoped enumeration that still contextually converts to bool.
struct ReferenceConversionsScope {
/// The conversions that would be performed on an lvalue of type T2 when
/// binding a reference of type T1 to it, as determined when evaluating
/// whether T1 is reference-compatible with T2.
enum ReferenceConversions {
Qualification = 0x1,
Function = 0x2,
DerivedToBase = 0x4,
ObjC = 0x8,
ObjCLifetime = 0x10,
LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)
};
};
using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
ReferenceCompareResult
CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
ReferenceConversions *Conv = nullptr);
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path);
/// Force an expression with unknown-type to an expression of the
/// given type.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
/// Type-check an expression that's being passed to an
/// __unknown_anytype parameter.
ExprResult checkUnknownAnyArg(SourceLocation callLoc,
Expr *result, QualType ¶mType);
// CheckVectorCast - check type constraints for vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size.
// returns true if the cast is invalid
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind);
/// Prepare `SplattedExpr` for a vector splat operation, adding
/// implicit casts if necessary.
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
// CheckExtVectorCast - check type constraints for extended vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size,
// or vectors and the element type of that vector.
// returns the cast expr
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
CastKind &Kind);
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
/// Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds for ARC and Weak.
ARCConversionResult CheckObjCConversion(SourceRange castRange,
QualType castType, Expr *&op,
CheckedConversionKind CCK,
bool Diagnose = true,
bool DiagnoseCFAudited = false,
BinaryOperatorKind Opc = BO_PtrMemD
);
Expr *stripARCUnbridgedCast(Expr *e);
void diagnoseARCUnbridgedCast(Expr *e);
bool CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType ExprType);
/// checkRetainCycles - Check whether an Objective-C message send
/// might create an obvious retain cycle.
void checkRetainCycles(ObjCMessageExpr *msg);
void checkRetainCycles(Expr *receiver, Expr *argument);
void checkRetainCycles(VarDecl *Var, Expr *Init);
/// checkUnsafeAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained type.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
/// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained expression.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
/// CheckMessageArgumentTypes - Check types in an Obj-C message send.
/// \param Method - May be null.
/// \param [out] ReturnType - The return type of the send.
/// \return true iff there were any incompatible types.
bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
MultiExprArg Args, Selector Sel,
ArrayRef<SourceLocation> SelectorLocs,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage, SourceLocation lbrac,
SourceLocation rbrac, SourceRange RecRange,
QualType &ReturnType, ExprValueKind &VK);
/// Determine the result of a message send expression based on
/// the type of the receiver, the method expected to receive the message,
/// and the form of the message send.
QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage);
/// If the given expression involves a message send to a method
/// with a related result type, emit a note describing what happened.
void EmitRelatedResultTypeNote(const Expr *E);
/// Given that we had incompatible pointer types in a return
/// statement, check whether we're in a method with a related result
/// type, and if so, emit a note describing what happened.
void EmitRelatedResultTypeNoteForReturn(QualType destType);
class ConditionResult {
Decl *ConditionVar;
FullExprArg Condition;
bool Invalid;
bool HasKnownValue;
bool KnownValue;
friend class Sema;
ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
bool IsConstexpr)
: ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
HasKnownValue(IsConstexpr && Condition.get() &&
!Condition.get()->isValueDependent()),
KnownValue(HasKnownValue &&
!!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
explicit ConditionResult(bool Invalid)
: ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
HasKnownValue(false), KnownValue(false) {}
public:
ConditionResult() : ConditionResult(false) {}
bool isInvalid() const { return Invalid; }
std::pair<VarDecl *, Expr *> get() const {
return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
Condition.get());
}
llvm::Optional<bool> getKnownValue() const {
if (!HasKnownValue)
return None;
return KnownValue;
}
};
static ConditionResult ConditionError() { return ConditionResult(true); }
enum class ConditionKind {
Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
Switch ///< An integral condition for a 'switch' statement.
};
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr, ConditionKind CK);
ConditionResult ActOnConditionVariable(Decl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
ExprResult CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
ConditionKind CK);
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
/// CheckBooleanCondition - Diagnose problems involving the use of
/// the given expression as a boolean condition (e.g. in an if
/// statement). Also performs the standard function and array
/// decays, possibly changing the input variable.
///
/// \param Loc - A location associated with the condition, e.g. the
/// 'if' keyword.
/// \return true iff there were any errors
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
bool IsConstexpr = false);
/// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
/// found in an explicit(bool) specifier.
ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
/// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
/// Returns true if the explicit specifier is now resolved.
bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
/// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
/// the specified width and sign. If an overflow occurs, detect it and emit
/// the specified diagnostic.
void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
unsigned NewWidth, bool NewSign,
SourceLocation Loc, unsigned DiagID);
/// Checks that the Objective-C declaration is declared in the global scope.
/// Emits an error and marks the declaration as invalid if it's not declared
/// in the global scope.
bool CheckObjCDeclScope(Decl *D);
/// Abstract base class used for diagnosing integer constant
/// expression violations.
class VerifyICEDiagnoser {
public:
bool Suppress;
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
virtual ~VerifyICEDiagnoser() { }
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
/// and reports the appropriate diagnostics. Returns false on success.
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result = nullptr);
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
/// Returns false on success.
/// Can optionally return whether the bit-field is of width 0
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
QualType FieldTy, bool IsMsStruct,
Expr *BitWidth, bool *ZeroWidth = nullptr);
private:
unsigned ForceCUDAHostDeviceDepth = 0;
public:
/// Increments our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. So long as this count is greater
/// than zero, all functions encountered will be __host__ __device__.
void PushForceCUDAHostDevice();
/// Decrements our count of the number of times we've seen a pragma forcing
/// functions to be __host__ __device__. Returns false if the count is 0
/// before incrementing, so you can emit an error.
bool PopForceCUDAHostDevice();
/// Diagnostics that are emitted only if we discover that the given function
/// must be codegen'ed. Because handling these correctly adds overhead to
/// compilation, this is currently only enabled for CUDA compilations.
llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
std::vector<PartialDiagnosticAt>>
DeviceDeferredDiags;
/// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
/// key in a hashtable, both the FD and location are hashed.
struct FunctionDeclAndLoc {
CanonicalDeclPtr<FunctionDecl> FD;
SourceLocation Loc;
};
/// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
/// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
/// same deferred diag twice.
llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
/// An inverse call graph, mapping known-emitted functions to one of their
/// known-emitted callers (plus the location of the call).
///
/// Functions that we can tell a priori must be emitted aren't added to this
/// map.
llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
/* Caller = */ FunctionDeclAndLoc>
DeviceKnownEmittedFns;
/// A partial call graph maintained during CUDA/OpenMP device code compilation
/// to support deferred diagnostics.
///
/// Functions are only added here if, at the time they're considered, they are
/// not known-emitted. As soon as we discover that a function is
/// known-emitted, we remove it and everything it transitively calls from this
/// set and add those functions to DeviceKnownEmittedFns.
llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>,
/* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>,
SourceLocation>>
DeviceCallGraph;
/// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be
/// deferred.
///
/// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
/// which are not allowed to appear inside __device__ functions and are
/// allowed to appear in __host__ __device__ functions only if the host+device
/// function is never codegen'ed.
///
/// To handle this, we use the notion of "deferred diagnostics", where we
/// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
///
/// This class lets you emit either a regular diagnostic, a deferred
/// diagnostic, or no diagnostic at all, according to an argument you pass to
/// its constructor, thus simplifying the process of creating these "maybe
/// deferred" diagnostics.
class DeviceDiagBuilder {
public:
enum Kind {
/// Emit no diagnostics.
K_Nop,
/// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
K_Immediate,
/// Emit the diagnostic immediately, and, if it's a warning or error, also
/// emit a call stack showing how this function can be reached by an a
/// priori known-emitted function.
K_ImmediateWithCallStack,
/// Create a deferred diagnostic, which is emitted only if the function
/// it's attached to is codegen'ed. Also emit a call stack as with
/// K_ImmediateWithCallStack.
K_Deferred
};
DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
FunctionDecl *Fn, Sema &S);
DeviceDiagBuilder(DeviceDiagBuilder &&D);
DeviceDiagBuilder(const DeviceDiagBuilder &) = default;
~DeviceDiagBuilder();
/// Convertible to bool: True if we immediately emitted an error, false if
/// we didn't emit an error or we created a deferred error.
///
/// Example usage:
///
/// if (DeviceDiagBuilder(...) << foo << bar)
/// return ExprError();
///
/// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
/// want to use these instead of creating a DeviceDiagBuilder yourself.
operator bool() const { return ImmediateDiag.hasValue(); }
template <typename T>
friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag,
const T &Value) {
if (Diag.ImmediateDiag.hasValue())
*Diag.ImmediateDiag << Value;
else if (Diag.PartialDiagId.hasValue())
Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
<< Value;
return Diag;
}
private:
Sema &S;
SourceLocation Loc;
unsigned DiagID;
FunctionDecl *Fn;
bool ShowCallStack;
// Invariant: At most one of these Optionals has a value.
// FIXME: Switch these to a Variant once that exists.
llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag;
llvm::Optional<unsigned> PartialDiagId;
};
/// Indicate that this function (and thus everything it transtively calls)
/// will be codegen'ed, and emit any deferred diagnostics on this function and
/// its (transitive) callees.
void markKnownEmitted(
Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee,
SourceLocation OrigLoc,
const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as device code".
///
/// - If CurContext is a __host__ function, does not emit any diagnostics.
/// - If CurContext is a __device__ or __global__ function, emits the
/// diagnostics immediately.
/// - If CurContext is a __host__ __device__ function and we are compiling for
/// the device, creates a diagnostic which is emitted if and when we realize
/// that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in CUDA device code.
/// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current context
/// is "used as host code".
///
/// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current
/// context is "used as device code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the device, emits the diagnostics immediately.
/// - If CurContext is a non-`declare target` function and we are compiling
/// for the device, creates a diagnostic which is emitted if and when we
/// realize that the function will be codegen'ed.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID);
/// Creates a DeviceDiagBuilder that emits the diagnostic if the current
/// context is "used as host code".
///
/// - If CurContext is a `declare target` function or it is known that the
/// function is emitted for the host, emits the diagnostics immediately.
/// - If CurContext is a non-host function, just ignore it.
///
/// Example usage:
///
/// // Variable-length arrays are not allowed in NVPTX device code.
/// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
/// return ExprError();
/// // Otherwise, continue parsing as normal.
DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID);
DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID);
enum CUDAFunctionTarget {
CFT_Device,
CFT_Global,
CFT_Host,
CFT_HostDevice,
CFT_InvalidTarget
};
/// Determines whether the given function is a CUDA device/host/kernel/etc.
/// function.
///
/// Use this rather than examining the function's attributes yourself -- you
/// will get it wrong. Returns CFT_Host if D is null.
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
bool IgnoreImplicitHDAttr = false);
CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
/// Gets the CUDA target for the current context.
CUDAFunctionTarget CurrentCUDATarget() {
return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
}
// CUDA function call preference. Must be ordered numerically from
// worst to best.
enum CUDAFunctionPreference {
CFP_Never, // Invalid caller/callee combination.
CFP_WrongSide, // Calls from host-device to host or device
// function that do not match current compilation
// mode.
CFP_HostDevice, // Any calls to host/device functions.
CFP_SameSide, // Calls from host-device to host or device
// function matching current compilation mode.
CFP_Native, // host-to-host or device-to-device calls.
};
/// Identifies relative preference of a given Caller/Callee
/// combination, based on their host/device attributes.
/// \param Caller function which needs address of \p Callee.
/// nullptr in case of global context.
/// \param Callee target function
///
/// \returns preference value for particular Caller/Callee combination.
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
const FunctionDecl *Callee);
/// Determines whether Caller may invoke Callee, based on their CUDA
/// host/device attributes. Returns false if the call is not allowed.
///
/// Note: Will return true for CFP_WrongSide calls. These may appear in
/// semantically correct CUDA programs, but only if they're never codegen'ed.
bool IsAllowedCUDACall(const FunctionDecl *Caller,
const FunctionDecl *Callee) {
return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
}
/// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
/// depending on FD and the current compilation settings.
void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
const LookupResult &Previous);
public:
/// Check whether we're allowed to call Callee from the current context.
///
/// - If the call is never allowed in a semantically-correct program
/// (CFP_Never), emits an error and returns false.
///
/// - If the call is allowed in semantically-correct programs, but only if
/// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
/// be emitted if and when the caller is codegen'ed, and returns true.
///
/// Will only create deferred diagnostics for a given SourceLocation once,
/// so you can safely call this multiple times without generating duplicate
/// deferred errors.
///
/// - Otherwise, returns true without emitting any diagnostics.
bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
/// Set __device__ or __host__ __device__ attributes on the given lambda
/// operator() method.
///
/// CUDA lambdas declared inside __device__ or __global__ functions inherit
/// the __device__ attribute. Similarly, lambdas inside __host__ __device__
/// functions become __host__ __device__ themselves.
void CUDASetLambdaAttrs(CXXMethodDecl *Method);
/// Finds a function in \p Matches with highest calling priority
/// from \p Caller context and erases all functions with lower
/// calling priority.
void EraseUnwantedCUDAMatches(
const FunctionDecl *Caller,
SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
/// Given a implicit special member, infer its CUDA target from the
/// calls it needs to make to underlying base/field special members.
/// \param ClassDecl the class for which the member is being created.
/// \param CSM the kind of special member.
/// \param MemberDecl the special member itself.
/// \param ConstRHS true if this is a copy operation with a const object on
/// its RHS.
/// \param Diagnose true if this call should emit diagnostics.
/// \return true if there was an error inferring.
/// The result of this call is implicit CUDA target attribute(s) attached to
/// the member declaration.
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose);
/// \return true if \p CD can be considered empty according to CUDA
/// (E.2.3.1 in CUDA 7.5 Programming guide).
bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
// \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
// case of error emits appropriate diagnostic and invalidates \p Var.
//
// \details CUDA allows only empty constructors as initializers for global
// variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
// __shared__ variables whether they are local or not (they all are implicitly
// static in CUDA). One exception is that CUDA allows constant initializers
// for __constant__ and __device__ variables.
void checkAllowedCUDAInitializer(VarDecl *VD);
/// Check whether NewFD is a valid overload for CUDA. Emits
/// diagnostics and invalidates NewFD if not.
void checkCUDATargetOverload(FunctionDecl *NewFD,
const LookupResult &Previous);
/// Copies target attributes from the template TD to the function FD.
void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
/// Returns the name of the launch configuration function. This is the name
/// of the function that will be called to configure kernel call, with the
/// parameters specified via <<<>>>.
std::string getCudaConfigureFuncName() const;
/// \name Code completion
//@{
/// Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// Code completion occurs within a class, struct, or union.
PCC_Class,
/// Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// Code completion occurs following one or more template
/// headers.
PCC_Template,
/// Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// Code completion occurs within an expression.
PCC_Expression,
/// Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// Code completion occurs within the body of a function on a
/// recovery path, where we do not have a specific handle on our position
/// in the grammar.
PCC_RecoveryInFunction,
/// Code completion occurs where only a type is permitted.
PCC_Type,
/// Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// Code completion occurs within a sequence of declaration
/// specifiers within a function, method, or block.
PCC_LocalDeclarationSpecifiers
};
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
void CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext);
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers);
struct CodeCompleteExpressionData;
void CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data);
void CodeCompleteExpression(Scope *S, QualType PreferredType,
bool IsParenthesized = false);
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
SourceLocation OpLoc, bool IsArrow,
bool IsBaseExprStatement,
QualType PreferredType);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
QualType PreferredType);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
const VirtSpecifiers *VS = nullptr);
void CodeCompleteBracketDeclarator(Scope *S);
void CodeCompleteCase(Scope *S);
/// Reports signatures for a call to CodeCompleteConsumer and returns the
/// preferred type for the current argument. Returned type can be null.
QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type,
SourceLocation Loc,
ArrayRef<Expr *> Args,
SourceLocation OpenParLoc);
QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl,
CXXScopeSpec SS,
ParsedType TemplateTypeTy,
ArrayRef<Expr *> ArgExprs,
IdentifierInfo *II,
SourceLocation OpenParLoc);
void CodeCompleteInitializer(Scope *S, Decl *D);
void CodeCompleteAfterIf(Scope *S);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
bool IsUsingDeclaration, QualType BaseType,
QualType PreferredType);
void CodeCompleteUsing(Scope *S);
void CodeCompleteUsingDirective(Scope *S);
void CodeCompleteNamespaceDecl(Scope *S);
void CodeCompleteNamespaceAliasDecl(Scope *S);
void CodeCompleteOperatorName(Scope *S);
void CodeCompleteConstructorInitializer(
Decl *Constructor,
ArrayRef<CXXCtorInitializer *> Initializers);
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand);
void CodeCompleteObjCAtDirective(Scope *S);
void CodeCompleteObjCAtVisibility(Scope *S);
void CodeCompleteObjCAtStatement(Scope *S);
void CodeCompleteObjCAtExpression(Scope *S);
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
void CodeCompleteObjCPropertyGetter(Scope *S);
void CodeCompleteObjCPropertySetter(Scope *S);
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter);
void CodeCompleteObjCMessageReceiver(Scope *S);
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression);
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
bool IsSuper = false);
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super = nullptr);
void CodeCompleteObjCForCollection(Scope *S,
DeclGroupPtrTy IterationVar);
void CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCProtocolReferences(
ArrayRef<IdentifierLocPair> Protocols);
void CodeCompleteObjCProtocolDecl(Scope *S);
void CodeCompleteObjCInterfaceDecl(Scope *S);
void CodeCompleteObjCSuperclass(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationDecl(Scope *S);
void CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod,
bool AtParameterName,
ParsedType ReturnType,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
SourceLocation ClassNameLoc,
bool IsBaseExprStatement);
void CodeCompletePreprocessorDirective(bool InConditional);
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
void CodeCompletePreprocessorMacroName(bool IsDefinition);
void CodeCompletePreprocessorExpression();
void CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument);
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
void CodeCompleteNaturalLanguage();
void CodeCompleteAvailabilityPlatformName();
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results);
//@}
//===--------------------------------------------------------------------===//
// Extra semantic analysis beyond the C type system
public:
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const;
private:
void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE=nullptr,
bool AllowOnePastEnd=true, bool IndexNegated=false);
void CheckArrayAccess(const Expr *E);
// Used to grab the relevant information from a FormatAttr and a
// FunctionDeclaration.
struct FormatStringInfo {
unsigned FormatIdx;
unsigned FirstDataArg;
bool HasVAListArg;
};
static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI);
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef<const Expr *> Args);
bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
void CheckConstructorCall(FunctionDecl *FDecl,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc);
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
const Expr *ThisArg, ArrayRef<const Expr *> Args,
bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
ExprResult CheckOSLogFormatStringArg(Expr *Arg);
ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID, CallExpr *TheCall);
void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
bool SemaBuiltinVSX(CallExpr *TheCall);
bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
public:
// Used by C++ template instantiation.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
bool SemaBuiltinAssume(CallExpr *TheCall);
bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
bool SemaBuiltinSetjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op);
ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
bool IsDelete);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
int High, bool RangeIsError = true);
bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
unsigned Multiple);
bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
public:
enum FormatStringType {
FST_Scanf,
FST_Printf,
FST_NSString,
FST_Strftime,
FST_Strfmon,
FST_Kprintf,
FST_FreeBSDKPrintf,
FST_OSTrace,
FST_OSLog,
FST_Unknown
};
static FormatStringType GetFormatStringType(const FormatAttr *Format);
bool FormatStringHasSArg(const StringLiteral *FExpr);
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
private:
bool CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs);
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange range,
llvm::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl);
void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);
void CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
const AttrVec *Attrs = nullptr,
const FunctionDecl *FD = nullptr);
public:
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS);
private:
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(Expr *E);
/// Perform semantic checks on a completed expression. This will either
/// be a full-expression or a default argument expression.
void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
bool IsConstexpr = false);
void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
Expr *Init);
/// Check if there is a field shadowing.
void CheckShadowInheritedFields(const SourceLocation &Loc,
DeclarationName FieldName,
const CXXRecordDecl *RD,
bool DeclIsField = true);
/// Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// Check whether receiver is mutable ObjC container which
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
public:
/// Register a magic integral constant to be used as a type tag.
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible, bool MustBeNull);
struct TypeTagData {
TypeTagData() {}
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
Type(Type), LayoutCompatible(LayoutCompatible),
MustBeNull(MustBeNull)
{}
QualType Type;
/// If true, \c Type should be compared with other expression's types for
/// layout-compatibility.
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
/// A pair of ArgumentKind identifier and magic value. This uniquely
/// identifies the magic value.
typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
private:
/// A map from magic value to type information.
std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// Peform checks on a call of a function with argument_with_type_tag
/// or pointer_with_type_tag attributes.
void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const ArrayRef<const Expr *> ExprArgs,
SourceLocation CallSiteLoc);
/// Check if we are taking the address of a packed field
/// as this may be a problem if the pointer value is dereferenced.
void CheckAddressOfPackedMember(Expr *rhs);
/// The parser's current scope.
///
/// The parser maintains this state here.
Scope *CurScope;
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
/// The handler for the FileChanged preprocessor events.
///
/// Used for diagnostics that implement custom semantic analysis for #include
/// directives, like -Wpragma-pack.
sema::SemaPPCallbacks *SemaPPCallbackHandler;
protected:
friend class Parser;
friend class InitializationSequence;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTWriter;
public:
/// Retrieve the keyword associated
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
bool isCFError(RecordDecl *D);
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
/// and the parser are in precisely the same context, which is not the case
/// when, e.g., we are performing any kind of template instantiation.
/// Therefore, the only safe places to use this scope are in the parser
/// itself and in routines directly invoked from the parser and *never* from
/// template substitution or instantiation.
Scope *getCurScope() const { return CurScope; }
void incrementMSManglingNumber() const {
return CurScope->incrementMSManglingNumber();
}
IdentifierInfo *getSuperIdentifier() const;
IdentifierInfo *getFloat128Identifier() const;
Decl *getObjCDeclContext() const;
DeclContext *getCurLexicalContext() const {
return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
}
const DeclContext *getCurObjCLexicalContext() const {
const DeclContext *DC = getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// To be used for checking whether the arguments being passed to
/// function exceeds the number of parameters expected for it.
static bool TooManyArguments(size_t NumParams, size_t NumArgs,
bool PartialOverloading = false) {
// We check whether we're just after a comma in code-completion.
if (NumArgs > 0 && PartialOverloading)
return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
return NumArgs > NumParams;
}
// Emitting members of dllexported classes is delayed until the class
// (including field initializers) is fully parsed.
SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
private:
int ParsingClassDepth = 0;
class SavePendingParsedClassStateRAII {
public:
SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
~SavePendingParsedClassStateRAII() {
assert(S.DelayedOverridingExceptionSpecChecks.empty() &&
"there shouldn't be any pending delayed exception spec checks");
assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&
"there shouldn't be any pending delayed exception spec checks");
swapSavedState();
}
private:
Sema &S;
decltype(DelayedOverridingExceptionSpecChecks)
SavedOverridingExceptionSpecChecks;
decltype(DelayedEquivalentExceptionSpecChecks)
SavedEquivalentExceptionSpecChecks;
void swapSavedState() {
SavedOverridingExceptionSpecChecks.swap(
S.DelayedOverridingExceptionSpecChecks);
SavedEquivalentExceptionSpecChecks.swap(
S.DelayedEquivalentExceptionSpecChecks);
}
};
/// Helper class that collects misaligned member designations and
/// their location info for delayed diagnostics.
struct MisalignedMember {
Expr *E;
RecordDecl *RD;
ValueDecl *MD;
CharUnits Alignment;
MisalignedMember() : E(), RD(), MD(), Alignment() {}
MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment)
: E(E), RD(RD), MD(MD), Alignment(Alignment) {}
explicit MisalignedMember(Expr *E)
: MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
bool operator==(const MisalignedMember &m) { return this->E == m.E; }
};
/// Small set of gathered accesses to potentially misaligned members
/// due to the packed attribute.
SmallVector<MisalignedMember, 4> MisalignedMembers;
/// Adds an expression to the set of gathered misaligned members.
void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
CharUnits Alignment);
public:
/// Diagnoses the current set of gathered accesses. This typically
/// happens at full expression level. The set is cleared after emitting the
/// diagnostics.
void DiagnoseMisalignedMembers();
/// This function checks if the expression is in the sef of potentially
/// misaligned members and it is converted to some pointer type T with lower
/// or equal alignment requirements. If so it removes it. This is used when
/// we do not want to diagnose such misaligned access (e.g. in conversions to
/// void*).
void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
/// This function calls Action when it determines that E designates a
/// misaligned member due to the packed attribute. This is used to emit
/// local diagnostics like in reference binding.
void RefersToMemberWithReducedAlignment(
Expr *E,
llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
Action);
/// Describes the reason a calling convention specification was ignored, used
/// for diagnostics.
enum class CallingConventionIgnoredReason {
ForThisTarget = 0,
VariadicFunction,
ConstructorDestructor,
BuiltinFunction
};
};
/// RAII object that enters a new expression evaluation context.
class EnterExpressionEvaluationContext {
Sema &Actions;
bool Entered = true;
public:
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other,
bool ShouldEnter = true)
: Actions(Actions), Entered(ShouldEnter) {
if (Entered)
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
ExprContext);
}
EnterExpressionEvaluationContext(
Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
Sema::ExpressionEvaluationContextRecord::EK_Other)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(
NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
}
enum InitListTag { InitList };
EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
bool ShouldEnter = true)
: Actions(Actions), Entered(false) {
// In C++11 onwards, narrowing checks are performed on the contents of
// braced-init-lists, even when they occur within unevaluated operands.
// Therefore we still need to instantiate constexpr functions used in such
// a context.
if (ShouldEnter && Actions.isUnevaluatedContext() &&
Actions.getLangOpts().CPlusPlus11) {
Actions.PushExpressionEvaluationContext(
Sema::ExpressionEvaluationContext::UnevaluatedList);
Entered = true;
}
}
~EnterExpressionEvaluationContext() {
if (Entered)
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// The template function declaration to be late parsed.
Decl *D;
};
} // end namespace clang
namespace llvm {
// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
// SourceLocation.
template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
static FunctionDeclAndLoc getEmptyKey() {
return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
}
static FunctionDeclAndLoc getTombstoneKey() {
return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
}
static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
FDL.Loc.getRawEncoding());
}
static bool isEqual(const FunctionDeclAndLoc &LHS,
const FunctionDeclAndLoc &RHS) {
return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
}
};
} // namespace llvm
#endif
|
core_dtsqrt.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_ztsqrt.c, normal z -> d, Fri Sep 28 17:38:24 2018
*
**/
#include <plasma_core_blas.h>
#include "plasma_types.h"
#include "plasma_internal.h"
#include "core_lapack.h"
#include <omp.h>
// This will be swapped during the automatic code generation.
#undef REAL
#define REAL
/***************************************************************************//**
*
* @ingroup core_tsqrt
*
* Computes a QR factorization of a rectangular matrix
* formed by coupling an n-by-n upper triangular tile A1
* on top of an m-by-n tile A2:
*
* | A1 | = Q * R
* | A2 |
*
*******************************************************************************
*
* @param[in] m
* The number of columns of the tile A2. m >= 0.
*
* @param[in] n
* The number of rows of the tile A1.
* The number of columns of the tiles A1 and A2. n >= 0.
*
* @param[in] ib
* The inner-blocking size. ib >= 0.
*
* @param[in,out] A1
* On entry, the n-by-n tile A1.
* On exit, the elements on and above the diagonal of the array
* contain the n-by-n upper trapezoidal tile R;
* the elements below the diagonal are not referenced.
*
* @param[in] lda1
* The leading dimension of the array A1. LDA1 >= max(1,N).
*
* @param[in,out] A2
* On entry, the m-by-n tile A2.
* On exit, all the elements with the array tau, represent
* the orthogonal tile Q as a product of elementary reflectors
* (see Further Details).
*
* @param[in] lda2
* The leading dimension of the tile A2. lda2 >= max(1,m).
*
* @param[out] T
* The ib-by-n triangular factor T of the block reflector.
* T is upper triangular by block (economic storage);
* The rest of the array is not referenced.
*
* @param[in] ldt
* The leading dimension of the array T. ldt >= ib.
*
* @param tau
* Auxiliary workspace array of length n.
*
* @param work
* Auxiliary workspace array of length ib*n.
*
*******************************************************************************
*
* @retval PlasmaSuccess successful exit
* @retval < 0 if -i, the i-th argument had an illegal value
*
******************************************************************************/
__attribute__((weak))
int plasma_core_dtsqrt(int m, int n, int ib,
double *A1, int lda1,
double *A2, int lda2,
double *T, int ldt,
double *tau,
double *work)
{
// Check input arguments.
if (m < 0) {
plasma_coreblas_error("illegal value of m");
return -1;
}
if (n < 0) {
plasma_coreblas_error("illegal value of n");
return -2;
}
if (ib < 0) {
plasma_coreblas_error("illegal value of ib");
return -3;
}
if (A1 == NULL) {
plasma_coreblas_error("NULL A1");
return -4;
}
if (lda1 < imax(1, m) && m > 0) {
plasma_coreblas_error("illegal value of lda1");
return -5;
}
if (A2 == NULL) {
plasma_coreblas_error("NULL A2");
return -6;
}
if (lda2 < imax(1, m) && m > 0) {
plasma_coreblas_error("illegal value of lda2");
return -7;
}
if (T == NULL) {
plasma_coreblas_error("NULL T");
return -8;
}
if (ldt < imax(1, ib) && ib > 0) {
plasma_coreblas_error("illegal value of ldt");
return -9;
}
if (tau == NULL) {
plasma_coreblas_error("NULL tau");
return -10;
}
if (work == NULL) {
plasma_coreblas_error("NULL work");
return -11;
}
// quick return
if (m == 0 || n == 0 || ib == 0)
return PlasmaSuccess;
static double zone = 1.0;
static double zzero = 0.0;
for (int ii = 0; ii < n; ii += ib) {
int sb = imin(n-ii, ib);
for (int i = 0; i < sb; i++) {
// Generate elementary reflector H( II*IB+I ) to annihilate
// A( II*IB+I:M, II*IB+I ).
LAPACKE_dlarfg_work(m+1, &A1[lda1*(ii+i)+ii+i], &A2[lda2*(ii+i)], 1,
&tau[ii+i]);
if (ii+i+1 < n) {
// Apply H( II*IB+I ) to A( II*IB+I:M, II*IB+I+1:II*IB+IB )
// from the left.
double alpha = -(tau[ii+i]);
cblas_dcopy(sb-i-1, &A1[lda1*(ii+i+1)+(ii+i)], lda1, work, 1);
#ifdef COMPLEX
LAPACKE_dlacgv_work(sb-i-1, work, 1);
#endif
cblas_dgemv(CblasColMajor, (CBLAS_TRANSPOSE)PlasmaTrans,
m, sb-i-1,
(zone), &A2[lda2*(ii+i+1)], lda2,
&A2[lda2*(ii+i)], 1,
(zone), work, 1);
#ifdef COMPLEX
LAPACKE_dlacgv_work(sb-i-1, work, 1);
#endif
cblas_daxpy(sb-i-1, (alpha), work, 1,
&A1[lda1*(ii+i+1)+ii+i], lda1);
#ifdef COMPLEX
LAPACKE_dlacgv_work(sb-i-1, work, 1);
#endif
cblas_dger(CblasColMajor,
m, sb-i-1,
(alpha), &A2[lda2*(ii+i)], 1,
work, 1,
&A2[lda2*(ii+i+1)], lda2);
}
// Calculate T.
double alpha = -tau[ii+i];
cblas_dgemv(CblasColMajor, (CBLAS_TRANSPOSE)PlasmaTrans,
m, i,
(alpha), &A2[lda2*ii], lda2,
&A2[lda2*(ii+i)], 1,
(zzero), &T[ldt*(ii+i)], 1);
cblas_dtrmv(CblasColMajor, (CBLAS_UPLO)PlasmaUpper,
(CBLAS_TRANSPOSE)PlasmaNoTrans,
(CBLAS_DIAG)PlasmaNonUnit,
i,
&T[ldt*ii], ldt,
&T[ldt*(ii+i)], 1);
T[ldt*(ii+i)+i] = tau[ii+i];
}
if (n > ii+sb) {
plasma_core_dtsmqr(PlasmaLeft, PlasmaTrans,
sb, n-(ii+sb), m, n-(ii+sb), ib, ib,
&A1[lda1*(ii+sb)+ii], lda1,
&A2[lda2*(ii+sb)], lda2,
&A2[lda2*ii], lda2,
&T[ldt*ii], ldt,
work, sb);
}
}
return PlasmaSuccess;
}
/******************************************************************************/
void plasma_core_omp_dtsqrt(int m, int n, int ib,
double *A1, int lda1,
double *A2, int lda2,
double *T, int ldt,
plasma_workspace_t work,
plasma_sequence_t *sequence, plasma_request_t *request)
{
#pragma omp task depend(inout:A1[0:lda1*n]) \
depend(inout:A2[0:lda2*n]) \
depend(out:T[0:ib*n])
{
if (sequence->status == PlasmaSuccess) {
// Prepare workspaces.
int tid = omp_get_thread_num();
double *tau = ((double*)work.spaces[tid]);
// Call the kernel.
int info = plasma_core_dtsqrt(m, n, ib,
A1, lda1,
A2, lda2,
T, ldt,
tau,
tau+n);
if (info != PlasmaSuccess) {
plasma_error("core_dtsqrt() failed");
plasma_request_fail(sequence, request, PlasmaErrorInternal);
}
}
}
}
|
GB_binop__bshift_uint64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__bshift_uint64)
// A.*B function (eWiseMult): GB (_AemultB_08__bshift_uint64)
// A.*B function (eWiseMult): GB (_AemultB_02__bshift_uint64)
// A.*B function (eWiseMult): GB (_AemultB_04__bshift_uint64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_uint64)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__bshift_uint64)
// C+=b function (dense accum): GB (_Cdense_accumb__bshift_uint64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_uint64)
// C=scalar+B GB (_bind1st__bshift_uint64)
// C=scalar+B' GB (_bind1st_tran__bshift_uint64)
// C=A+scalar GB (_bind2nd__bshift_uint64)
// C=A'+scalar GB (_bind2nd_tran__bshift_uint64)
// C type: uint64_t
// A type: uint64_t
// B,b type: int8_t
// BinaryOp: cij = GB_bitshift_uint64 (aij, bij)
#define GB_ATYPE \
uint64_t
#define GB_BTYPE \
int8_t
#define GB_CTYPE \
uint64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
0
// 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 \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint64_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int8_t bij = GBX (Bx, pB, B_iso)
// 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,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_bitshift_uint64 (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_BSHIFT || GxB_NO_UINT64 || GxB_NO_BSHIFT_UINT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__bshift_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__bshift_uint64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bshift_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 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
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *restrict Cx = (uint64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bshift_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__bshift_uint64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bshift_uint64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__bshift_uint64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bshift_uint64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bshift_uint64)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t x = (*((uint64_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] = GB_bitshift_uint64 (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bshift_uint64)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint64_t *Cx = (uint64_t *) Cx_output ;
uint64_t *Ax = (uint64_t *) Ax_input ;
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 ;
uint64_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_bitshift_uint64 (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] = GB_bitshift_uint64 (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__bshift_uint64)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint64_t x = (*((const uint64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_bitshift_uint64 (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__bshift_uint64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
DRB108-atomic-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.
*/
#include <stdio.h>
/*
* Test if atomic can be recognized properly. No data races.
* */
int main (void)
{
int a=0;
#pragma omp parallel for reduction(+:a)
for (int i = 0; i < 100; i++)
{
a += 1;
}
printf ("a=%d\n",a);
return 0;
}
|
threading.h | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for
* license information.
*/
#ifndef LIGHTGBM_UTILS_THREADING_H_
#define LIGHTGBM_UTILS_THREADING_H_
#include <LightGBM/meta.h>
#include <LightGBM/utils/common.h>
#include <LightGBM/utils/openmp_wrapper.h>
#include <algorithm>
#include <functional>
#include <vector>
namespace LightGBM {
class Threading {
public:
template <typename INDEX_T>
static inline void BlockInfo(INDEX_T cnt, INDEX_T min_cnt_per_block,
int* out_nblock, INDEX_T* block_size) {
int num_threads = OMP_NUM_THREADS();
BlockInfo<INDEX_T>(num_threads, cnt, min_cnt_per_block, out_nblock,
block_size);
}
template <typename INDEX_T>
static inline void BlockInfo(int num_threads, INDEX_T cnt,
INDEX_T min_cnt_per_block, int* out_nblock,
INDEX_T* block_size) {
*out_nblock = std::min<int>(
num_threads,
static_cast<int>((cnt + min_cnt_per_block - 1) / min_cnt_per_block));
if (*out_nblock > 1) {
*block_size = SIZE_ALIGNED((cnt + (*out_nblock) - 1) / (*out_nblock));
} else {
*block_size = cnt;
}
}
template <typename INDEX_T>
static inline void BlockInfoForceSize(int num_threads, INDEX_T cnt,
INDEX_T min_cnt_per_block,
int* out_nblock, INDEX_T* block_size) {
*out_nblock = std::min<int>(
num_threads,
static_cast<int>((cnt + min_cnt_per_block - 1) / min_cnt_per_block));
if (*out_nblock > 1) {
*block_size = (cnt + (*out_nblock) - 1) / (*out_nblock);
// force the block size to the times of min_cnt_per_block
*block_size = (*block_size + min_cnt_per_block - 1) / min_cnt_per_block *
min_cnt_per_block;
} else {
*block_size = cnt;
}
}
template <typename INDEX_T>
static inline void BlockInfoForceSize(INDEX_T cnt, INDEX_T min_cnt_per_block,
int* out_nblock, INDEX_T* block_size) {
int num_threads = OMP_NUM_THREADS();
BlockInfoForceSize<INDEX_T>(num_threads, cnt, min_cnt_per_block, out_nblock,
block_size);
}
template <typename INDEX_T>
static inline int For(
INDEX_T start, INDEX_T end, INDEX_T min_block_size,
const std::function<void(int, INDEX_T, INDEX_T)>& inner_fun) {
int n_block = 1;
INDEX_T num_inner = end - start;
BlockInfo<INDEX_T>(num_inner, min_block_size, &n_block, &num_inner);
OMP_INIT_EX();
#pragma omp parallel for schedule(static, 1)
for (int i = 0; i < n_block; ++i) {
OMP_LOOP_EX_BEGIN();
INDEX_T inner_start = start + num_inner * i;
INDEX_T inner_end = std::min(end, inner_start + num_inner);
if (inner_start < inner_end) {
inner_fun(i, inner_start, inner_end);
}
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
return n_block;
}
};
template <typename INDEX_T, bool TWO_BUFFER>
class ParallelPartitionRunner {
public:
ParallelPartitionRunner(INDEX_T num_data, INDEX_T min_block_size)
: min_block_size_(min_block_size) {
num_threads_ = OMP_NUM_THREADS();
left_.resize(num_data);
if (TWO_BUFFER) {
right_.resize(num_data);
}
offsets_.resize(num_threads_);
left_cnts_.resize(num_threads_);
right_cnts_.resize(num_threads_);
left_write_pos_.resize(num_threads_);
right_write_pos_.resize(num_threads_);
}
~ParallelPartitionRunner() {}
void ReSize(INDEX_T num_data) {
left_.resize(num_data);
if (TWO_BUFFER) {
right_.resize(num_data);
}
}
template<bool FORCE_SIZE>
INDEX_T Run(
INDEX_T cnt,
const std::function<INDEX_T(int, INDEX_T, INDEX_T, INDEX_T*, INDEX_T*)>& func,
INDEX_T* out) {
int nblock = 1;
INDEX_T inner_size = cnt;
if (FORCE_SIZE) {
Threading::BlockInfoForceSize<INDEX_T>(num_threads_, cnt, min_block_size_,
&nblock, &inner_size);
} else {
Threading::BlockInfo<INDEX_T>(num_threads_, cnt, min_block_size_, &nblock,
&inner_size);
}
OMP_INIT_EX();
#pragma omp parallel for schedule(static, 1) num_threads(num_threads_)
for (int i = 0; i < nblock; ++i) {
OMP_LOOP_EX_BEGIN();
INDEX_T cur_start = i * inner_size;
INDEX_T cur_cnt = std::min(inner_size, cnt - cur_start);
offsets_[i] = cur_start;
if (cur_cnt <= 0) {
left_cnts_[i] = 0;
right_cnts_[i] = 0;
continue;
}
auto left_ptr = left_.data() + cur_start;
INDEX_T* right_ptr = nullptr;
if (TWO_BUFFER) {
right_ptr = right_.data() + cur_start;
}
// split data inner, reduce the times of function called
INDEX_T cur_left_count =
func(i, cur_start, cur_cnt, left_ptr, right_ptr);
if (!TWO_BUFFER) {
// reverse for one buffer
std::reverse(left_ptr + cur_left_count, left_ptr + cur_cnt);
}
left_cnts_[i] = cur_left_count;
right_cnts_[i] = cur_cnt - cur_left_count;
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
left_write_pos_[0] = 0;
right_write_pos_[0] = 0;
for (int i = 1; i < nblock; ++i) {
left_write_pos_[i] = left_write_pos_[i - 1] + left_cnts_[i - 1];
right_write_pos_[i] = right_write_pos_[i - 1] + right_cnts_[i - 1];
}
data_size_t left_cnt = left_write_pos_[nblock - 1] + left_cnts_[nblock - 1];
auto right_start = out + left_cnt;
#pragma omp parallel for schedule(static, 1) num_threads(num_threads_)
for (int i = 0; i < nblock; ++i) {
std::copy_n(left_.data() + offsets_[i], left_cnts_[i],
out + left_write_pos_[i]);
if (TWO_BUFFER) {
std::copy_n(right_.data() + offsets_[i], right_cnts_[i],
right_start + right_write_pos_[i]);
} else {
std::copy_n(left_.data() + offsets_[i] + left_cnts_[i], right_cnts_[i],
right_start + right_write_pos_[i]);
}
}
return left_cnt;
}
private:
int num_threads_;
INDEX_T min_block_size_;
std::vector<INDEX_T> left_;
std::vector<INDEX_T> right_;
std::vector<INDEX_T> offsets_;
std::vector<INDEX_T> left_cnts_;
std::vector<INDEX_T> right_cnts_;
std::vector<INDEX_T> left_write_pos_;
std::vector<INDEX_T> right_write_pos_;
};
} // namespace LightGBM
#endif // LightGBM_UTILS_THREADING_H_
|
convolutiondepthwise_5x5_pack4.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void convdw5x5s1_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
#if __aarch64__
const int w = bottom_blob.w;
#endif
const int outw = top_blob.w;
const int outh = top_blob.h;
const int group = bottom_blob.c;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int g = 0; g < group; g++)
{
Mat out = top_blob.channel(g);
float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + g * 4) : vdupq_n_f32(0.f);
const float* k0 = kernel.row(g);
float* outptr0 = out.row(0);
const Mat img0 = bottom_blob.channel(g);
const float* r0 = img0.row(0);
const float* r1 = img0.row(1);
const float* r2 = img0.row(2);
const float* r3 = img0.row(3);
const float* r4 = img0.row(4);
int i = 0;
#if __aarch64__
float* outptr1 = out.row(1);
const float* r5 = img0.row(5);
for (; i + 1 < outh; i += 2)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
float32x4_t _sum00 = _bias0;
float32x4_t _sum01 = _bias0;
float32x4_t _sum02 = _bias0;
float32x4_t _sum03 = _bias0;
float32x4_t _sum10 = _bias0;
float32x4_t _sum11 = _bias0;
float32x4_t _sum12 = _bias0;
float32x4_t _sum13 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _r05 = vld1q_f32(r0 + 20);
float32x4_t _r06 = vld1q_f32(r0 + 24);
float32x4_t _r07 = vld1q_f32(r0 + 28);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum00 = vmlaq_f32(_sum00, _k00, _r00);
_sum00 = vmlaq_f32(_sum00, _k01, _r01);
_sum00 = vmlaq_f32(_sum00, _k02, _r02);
_sum00 = vmlaq_f32(_sum00, _k03, _r03);
_sum00 = vmlaq_f32(_sum00, _k04, _r04);
_sum01 = vmlaq_f32(_sum01, _k00, _r01);
_sum01 = vmlaq_f32(_sum01, _k01, _r02);
_sum01 = vmlaq_f32(_sum01, _k02, _r03);
_sum01 = vmlaq_f32(_sum01, _k03, _r04);
_sum01 = vmlaq_f32(_sum01, _k04, _r05);
_sum02 = vmlaq_f32(_sum02, _k00, _r02);
_sum02 = vmlaq_f32(_sum02, _k01, _r03);
_sum02 = vmlaq_f32(_sum02, _k02, _r04);
_sum02 = vmlaq_f32(_sum02, _k03, _r05);
_sum02 = vmlaq_f32(_sum02, _k04, _r06);
_sum03 = vmlaq_f32(_sum03, _k00, _r03);
_sum03 = vmlaq_f32(_sum03, _k01, _r04);
_sum03 = vmlaq_f32(_sum03, _k02, _r05);
_sum03 = vmlaq_f32(_sum03, _k03, _r06);
_sum03 = vmlaq_f32(_sum03, _k04, _r07);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _r15 = vld1q_f32(r1 + 20);
float32x4_t _r16 = vld1q_f32(r1 + 24);
float32x4_t _r17 = vld1q_f32(r1 + 28);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum10 = vmlaq_f32(_sum10, _k00, _r10);
_sum10 = vmlaq_f32(_sum10, _k01, _r11);
_sum10 = vmlaq_f32(_sum10, _k02, _r12);
_sum10 = vmlaq_f32(_sum10, _k03, _r13);
_sum10 = vmlaq_f32(_sum10, _k04, _r14);
_sum11 = vmlaq_f32(_sum11, _k00, _r11);
_sum11 = vmlaq_f32(_sum11, _k01, _r12);
_sum11 = vmlaq_f32(_sum11, _k02, _r13);
_sum11 = vmlaq_f32(_sum11, _k03, _r14);
_sum11 = vmlaq_f32(_sum11, _k04, _r15);
_sum12 = vmlaq_f32(_sum12, _k00, _r12);
_sum12 = vmlaq_f32(_sum12, _k01, _r13);
_sum12 = vmlaq_f32(_sum12, _k02, _r14);
_sum12 = vmlaq_f32(_sum12, _k03, _r15);
_sum12 = vmlaq_f32(_sum12, _k04, _r16);
_sum13 = vmlaq_f32(_sum13, _k00, _r13);
_sum13 = vmlaq_f32(_sum13, _k01, _r14);
_sum13 = vmlaq_f32(_sum13, _k02, _r15);
_sum13 = vmlaq_f32(_sum13, _k03, _r16);
_sum13 = vmlaq_f32(_sum13, _k04, _r17);
_sum00 = vmlaq_f32(_sum00, _k10, _r10);
_sum00 = vmlaq_f32(_sum00, _k11, _r11);
_sum00 = vmlaq_f32(_sum00, _k12, _r12);
_sum00 = vmlaq_f32(_sum00, _k13, _r13);
_sum00 = vmlaq_f32(_sum00, _k14, _r14);
_sum01 = vmlaq_f32(_sum01, _k10, _r11);
_sum01 = vmlaq_f32(_sum01, _k11, _r12);
_sum01 = vmlaq_f32(_sum01, _k12, _r13);
_sum01 = vmlaq_f32(_sum01, _k13, _r14);
_sum01 = vmlaq_f32(_sum01, _k14, _r15);
_sum02 = vmlaq_f32(_sum02, _k10, _r12);
_sum02 = vmlaq_f32(_sum02, _k11, _r13);
_sum02 = vmlaq_f32(_sum02, _k12, _r14);
_sum02 = vmlaq_f32(_sum02, _k13, _r15);
_sum02 = vmlaq_f32(_sum02, _k14, _r16);
_sum03 = vmlaq_f32(_sum03, _k10, _r13);
_sum03 = vmlaq_f32(_sum03, _k11, _r14);
_sum03 = vmlaq_f32(_sum03, _k12, _r15);
_sum03 = vmlaq_f32(_sum03, _k13, _r16);
_sum03 = vmlaq_f32(_sum03, _k14, _r17);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _r25 = vld1q_f32(r2 + 20);
float32x4_t _r26 = vld1q_f32(r2 + 24);
float32x4_t _r27 = vld1q_f32(r2 + 28);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum10 = vmlaq_f32(_sum10, _k10, _r20);
_sum10 = vmlaq_f32(_sum10, _k11, _r21);
_sum10 = vmlaq_f32(_sum10, _k12, _r22);
_sum10 = vmlaq_f32(_sum10, _k13, _r23);
_sum10 = vmlaq_f32(_sum10, _k14, _r24);
_sum11 = vmlaq_f32(_sum11, _k10, _r21);
_sum11 = vmlaq_f32(_sum11, _k11, _r22);
_sum11 = vmlaq_f32(_sum11, _k12, _r23);
_sum11 = vmlaq_f32(_sum11, _k13, _r24);
_sum11 = vmlaq_f32(_sum11, _k14, _r25);
_sum12 = vmlaq_f32(_sum12, _k10, _r22);
_sum12 = vmlaq_f32(_sum12, _k11, _r23);
_sum12 = vmlaq_f32(_sum12, _k12, _r24);
_sum12 = vmlaq_f32(_sum12, _k13, _r25);
_sum12 = vmlaq_f32(_sum12, _k14, _r26);
_sum13 = vmlaq_f32(_sum13, _k10, _r23);
_sum13 = vmlaq_f32(_sum13, _k11, _r24);
_sum13 = vmlaq_f32(_sum13, _k12, _r25);
_sum13 = vmlaq_f32(_sum13, _k13, _r26);
_sum13 = vmlaq_f32(_sum13, _k14, _r27);
_sum00 = vmlaq_f32(_sum00, _k20, _r20);
_sum00 = vmlaq_f32(_sum00, _k21, _r21);
_sum00 = vmlaq_f32(_sum00, _k22, _r22);
_sum00 = vmlaq_f32(_sum00, _k23, _r23);
_sum00 = vmlaq_f32(_sum00, _k24, _r24);
_sum01 = vmlaq_f32(_sum01, _k20, _r21);
_sum01 = vmlaq_f32(_sum01, _k21, _r22);
_sum01 = vmlaq_f32(_sum01, _k22, _r23);
_sum01 = vmlaq_f32(_sum01, _k23, _r24);
_sum01 = vmlaq_f32(_sum01, _k24, _r25);
_sum02 = vmlaq_f32(_sum02, _k20, _r22);
_sum02 = vmlaq_f32(_sum02, _k21, _r23);
_sum02 = vmlaq_f32(_sum02, _k22, _r24);
_sum02 = vmlaq_f32(_sum02, _k23, _r25);
_sum02 = vmlaq_f32(_sum02, _k24, _r26);
_sum03 = vmlaq_f32(_sum03, _k20, _r23);
_sum03 = vmlaq_f32(_sum03, _k21, _r24);
_sum03 = vmlaq_f32(_sum03, _k22, _r25);
_sum03 = vmlaq_f32(_sum03, _k23, _r26);
_sum03 = vmlaq_f32(_sum03, _k24, _r27);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _r35 = vld1q_f32(r3 + 20);
float32x4_t _r36 = vld1q_f32(r3 + 24);
float32x4_t _r37 = vld1q_f32(r3 + 28);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum10 = vmlaq_f32(_sum10, _k20, _r30);
_sum10 = vmlaq_f32(_sum10, _k21, _r31);
_sum10 = vmlaq_f32(_sum10, _k22, _r32);
_sum10 = vmlaq_f32(_sum10, _k23, _r33);
_sum10 = vmlaq_f32(_sum10, _k24, _r34);
_sum11 = vmlaq_f32(_sum11, _k20, _r31);
_sum11 = vmlaq_f32(_sum11, _k21, _r32);
_sum11 = vmlaq_f32(_sum11, _k22, _r33);
_sum11 = vmlaq_f32(_sum11, _k23, _r34);
_sum11 = vmlaq_f32(_sum11, _k24, _r35);
_sum12 = vmlaq_f32(_sum12, _k20, _r32);
_sum12 = vmlaq_f32(_sum12, _k21, _r33);
_sum12 = vmlaq_f32(_sum12, _k22, _r34);
_sum12 = vmlaq_f32(_sum12, _k23, _r35);
_sum12 = vmlaq_f32(_sum12, _k24, _r36);
_sum13 = vmlaq_f32(_sum13, _k20, _r33);
_sum13 = vmlaq_f32(_sum13, _k21, _r34);
_sum13 = vmlaq_f32(_sum13, _k22, _r35);
_sum13 = vmlaq_f32(_sum13, _k23, _r36);
_sum13 = vmlaq_f32(_sum13, _k24, _r37);
_sum00 = vmlaq_f32(_sum00, _k30, _r30);
_sum00 = vmlaq_f32(_sum00, _k31, _r31);
_sum00 = vmlaq_f32(_sum00, _k32, _r32);
_sum00 = vmlaq_f32(_sum00, _k33, _r33);
_sum00 = vmlaq_f32(_sum00, _k34, _r34);
_sum01 = vmlaq_f32(_sum01, _k30, _r31);
_sum01 = vmlaq_f32(_sum01, _k31, _r32);
_sum01 = vmlaq_f32(_sum01, _k32, _r33);
_sum01 = vmlaq_f32(_sum01, _k33, _r34);
_sum01 = vmlaq_f32(_sum01, _k34, _r35);
_sum02 = vmlaq_f32(_sum02, _k30, _r32);
_sum02 = vmlaq_f32(_sum02, _k31, _r33);
_sum02 = vmlaq_f32(_sum02, _k32, _r34);
_sum02 = vmlaq_f32(_sum02, _k33, _r35);
_sum02 = vmlaq_f32(_sum02, _k34, _r36);
_sum03 = vmlaq_f32(_sum03, _k30, _r33);
_sum03 = vmlaq_f32(_sum03, _k31, _r34);
_sum03 = vmlaq_f32(_sum03, _k32, _r35);
_sum03 = vmlaq_f32(_sum03, _k33, _r36);
_sum03 = vmlaq_f32(_sum03, _k34, _r37);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _r45 = vld1q_f32(r4 + 20);
float32x4_t _r46 = vld1q_f32(r4 + 24);
float32x4_t _r47 = vld1q_f32(r4 + 28);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum10 = vmlaq_f32(_sum10, _k30, _r40);
_sum10 = vmlaq_f32(_sum10, _k31, _r41);
_sum10 = vmlaq_f32(_sum10, _k32, _r42);
_sum10 = vmlaq_f32(_sum10, _k33, _r43);
_sum10 = vmlaq_f32(_sum10, _k34, _r44);
_sum11 = vmlaq_f32(_sum11, _k30, _r41);
_sum11 = vmlaq_f32(_sum11, _k31, _r42);
_sum11 = vmlaq_f32(_sum11, _k32, _r43);
_sum11 = vmlaq_f32(_sum11, _k33, _r44);
_sum11 = vmlaq_f32(_sum11, _k34, _r45);
_sum12 = vmlaq_f32(_sum12, _k30, _r42);
_sum12 = vmlaq_f32(_sum12, _k31, _r43);
_sum12 = vmlaq_f32(_sum12, _k32, _r44);
_sum12 = vmlaq_f32(_sum12, _k33, _r45);
_sum12 = vmlaq_f32(_sum12, _k34, _r46);
_sum13 = vmlaq_f32(_sum13, _k30, _r43);
_sum13 = vmlaq_f32(_sum13, _k31, _r44);
_sum13 = vmlaq_f32(_sum13, _k32, _r45);
_sum13 = vmlaq_f32(_sum13, _k33, _r46);
_sum13 = vmlaq_f32(_sum13, _k34, _r47);
_sum00 = vmlaq_f32(_sum00, _k40, _r40);
_sum00 = vmlaq_f32(_sum00, _k41, _r41);
_sum00 = vmlaq_f32(_sum00, _k42, _r42);
_sum00 = vmlaq_f32(_sum00, _k43, _r43);
_sum00 = vmlaq_f32(_sum00, _k44, _r44);
_sum01 = vmlaq_f32(_sum01, _k40, _r41);
_sum01 = vmlaq_f32(_sum01, _k41, _r42);
_sum01 = vmlaq_f32(_sum01, _k42, _r43);
_sum01 = vmlaq_f32(_sum01, _k43, _r44);
_sum01 = vmlaq_f32(_sum01, _k44, _r45);
_sum02 = vmlaq_f32(_sum02, _k40, _r42);
_sum02 = vmlaq_f32(_sum02, _k41, _r43);
_sum02 = vmlaq_f32(_sum02, _k42, _r44);
_sum02 = vmlaq_f32(_sum02, _k43, _r45);
_sum02 = vmlaq_f32(_sum02, _k44, _r46);
_sum03 = vmlaq_f32(_sum03, _k40, _r43);
_sum03 = vmlaq_f32(_sum03, _k41, _r44);
_sum03 = vmlaq_f32(_sum03, _k42, _r45);
_sum03 = vmlaq_f32(_sum03, _k43, _r46);
_sum03 = vmlaq_f32(_sum03, _k44, _r47);
float32x4_t _r50 = vld1q_f32(r5);
float32x4_t _r51 = vld1q_f32(r5 + 4);
float32x4_t _r52 = vld1q_f32(r5 + 8);
float32x4_t _r53 = vld1q_f32(r5 + 12);
float32x4_t _r54 = vld1q_f32(r5 + 16);
float32x4_t _r55 = vld1q_f32(r5 + 20);
float32x4_t _r56 = vld1q_f32(r5 + 24);
float32x4_t _r57 = vld1q_f32(r5 + 28);
_sum10 = vmlaq_f32(_sum10, _k40, _r50);
_sum10 = vmlaq_f32(_sum10, _k41, _r51);
_sum10 = vmlaq_f32(_sum10, _k42, _r52);
_sum10 = vmlaq_f32(_sum10, _k43, _r53);
_sum10 = vmlaq_f32(_sum10, _k44, _r54);
_sum11 = vmlaq_f32(_sum11, _k40, _r51);
_sum11 = vmlaq_f32(_sum11, _k41, _r52);
_sum11 = vmlaq_f32(_sum11, _k42, _r53);
_sum11 = vmlaq_f32(_sum11, _k43, _r54);
_sum11 = vmlaq_f32(_sum11, _k44, _r55);
_sum12 = vmlaq_f32(_sum12, _k40, _r52);
_sum12 = vmlaq_f32(_sum12, _k41, _r53);
_sum12 = vmlaq_f32(_sum12, _k42, _r54);
_sum12 = vmlaq_f32(_sum12, _k43, _r55);
_sum12 = vmlaq_f32(_sum12, _k44, _r56);
_sum13 = vmlaq_f32(_sum13, _k40, _r53);
_sum13 = vmlaq_f32(_sum13, _k41, _r54);
_sum13 = vmlaq_f32(_sum13, _k42, _r55);
_sum13 = vmlaq_f32(_sum13, _k43, _r56);
_sum13 = vmlaq_f32(_sum13, _k44, _r57);
vst1q_f32(outptr0, _sum00);
vst1q_f32(outptr0 + 4, _sum01);
vst1q_f32(outptr0 + 8, _sum02);
vst1q_f32(outptr0 + 12, _sum03);
vst1q_f32(outptr1, _sum10);
vst1q_f32(outptr1 + 4, _sum11);
vst1q_f32(outptr1 + 8, _sum12);
vst1q_f32(outptr1 + 12, _sum13);
r0 += 16;
r1 += 16;
r2 += 16;
r3 += 16;
r4 += 16;
r5 += 16;
outptr0 += 16;
outptr1 += 16;
}
for (; j + 1 < outw; j += 2)
{
float32x4_t _sum00 = _bias0;
float32x4_t _sum01 = _bias0;
float32x4_t _sum10 = _bias0;
float32x4_t _sum11 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _r05 = vld1q_f32(r0 + 20);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum00 = vmlaq_f32(_sum00, _k00, _r00);
_sum00 = vmlaq_f32(_sum00, _k01, _r01);
_sum00 = vmlaq_f32(_sum00, _k02, _r02);
_sum00 = vmlaq_f32(_sum00, _k03, _r03);
_sum00 = vmlaq_f32(_sum00, _k04, _r04);
_sum01 = vmlaq_f32(_sum01, _k00, _r01);
_sum01 = vmlaq_f32(_sum01, _k01, _r02);
_sum01 = vmlaq_f32(_sum01, _k02, _r03);
_sum01 = vmlaq_f32(_sum01, _k03, _r04);
_sum01 = vmlaq_f32(_sum01, _k04, _r05);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _r15 = vld1q_f32(r1 + 20);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum10 = vmlaq_f32(_sum10, _k00, _r10);
_sum10 = vmlaq_f32(_sum10, _k01, _r11);
_sum10 = vmlaq_f32(_sum10, _k02, _r12);
_sum10 = vmlaq_f32(_sum10, _k03, _r13);
_sum10 = vmlaq_f32(_sum10, _k04, _r14);
_sum11 = vmlaq_f32(_sum11, _k00, _r11);
_sum11 = vmlaq_f32(_sum11, _k01, _r12);
_sum11 = vmlaq_f32(_sum11, _k02, _r13);
_sum11 = vmlaq_f32(_sum11, _k03, _r14);
_sum11 = vmlaq_f32(_sum11, _k04, _r15);
_sum00 = vmlaq_f32(_sum00, _k10, _r10);
_sum00 = vmlaq_f32(_sum00, _k11, _r11);
_sum00 = vmlaq_f32(_sum00, _k12, _r12);
_sum00 = vmlaq_f32(_sum00, _k13, _r13);
_sum00 = vmlaq_f32(_sum00, _k14, _r14);
_sum01 = vmlaq_f32(_sum01, _k10, _r11);
_sum01 = vmlaq_f32(_sum01, _k11, _r12);
_sum01 = vmlaq_f32(_sum01, _k12, _r13);
_sum01 = vmlaq_f32(_sum01, _k13, _r14);
_sum01 = vmlaq_f32(_sum01, _k14, _r15);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _r25 = vld1q_f32(r2 + 20);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum10 = vmlaq_f32(_sum10, _k10, _r20);
_sum10 = vmlaq_f32(_sum10, _k11, _r21);
_sum10 = vmlaq_f32(_sum10, _k12, _r22);
_sum10 = vmlaq_f32(_sum10, _k13, _r23);
_sum10 = vmlaq_f32(_sum10, _k14, _r24);
_sum11 = vmlaq_f32(_sum11, _k10, _r21);
_sum11 = vmlaq_f32(_sum11, _k11, _r22);
_sum11 = vmlaq_f32(_sum11, _k12, _r23);
_sum11 = vmlaq_f32(_sum11, _k13, _r24);
_sum11 = vmlaq_f32(_sum11, _k14, _r25);
_sum00 = vmlaq_f32(_sum00, _k20, _r20);
_sum00 = vmlaq_f32(_sum00, _k21, _r21);
_sum00 = vmlaq_f32(_sum00, _k22, _r22);
_sum00 = vmlaq_f32(_sum00, _k23, _r23);
_sum00 = vmlaq_f32(_sum00, _k24, _r24);
_sum01 = vmlaq_f32(_sum01, _k20, _r21);
_sum01 = vmlaq_f32(_sum01, _k21, _r22);
_sum01 = vmlaq_f32(_sum01, _k22, _r23);
_sum01 = vmlaq_f32(_sum01, _k23, _r24);
_sum01 = vmlaq_f32(_sum01, _k24, _r25);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _r35 = vld1q_f32(r3 + 20);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum10 = vmlaq_f32(_sum10, _k20, _r30);
_sum10 = vmlaq_f32(_sum10, _k21, _r31);
_sum10 = vmlaq_f32(_sum10, _k22, _r32);
_sum10 = vmlaq_f32(_sum10, _k23, _r33);
_sum10 = vmlaq_f32(_sum10, _k24, _r34);
_sum11 = vmlaq_f32(_sum11, _k20, _r31);
_sum11 = vmlaq_f32(_sum11, _k21, _r32);
_sum11 = vmlaq_f32(_sum11, _k22, _r33);
_sum11 = vmlaq_f32(_sum11, _k23, _r34);
_sum11 = vmlaq_f32(_sum11, _k24, _r35);
_sum00 = vmlaq_f32(_sum00, _k30, _r30);
_sum00 = vmlaq_f32(_sum00, _k31, _r31);
_sum00 = vmlaq_f32(_sum00, _k32, _r32);
_sum00 = vmlaq_f32(_sum00, _k33, _r33);
_sum00 = vmlaq_f32(_sum00, _k34, _r34);
_sum01 = vmlaq_f32(_sum01, _k30, _r31);
_sum01 = vmlaq_f32(_sum01, _k31, _r32);
_sum01 = vmlaq_f32(_sum01, _k32, _r33);
_sum01 = vmlaq_f32(_sum01, _k33, _r34);
_sum01 = vmlaq_f32(_sum01, _k34, _r35);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _r45 = vld1q_f32(r4 + 20);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum10 = vmlaq_f32(_sum10, _k30, _r40);
_sum10 = vmlaq_f32(_sum10, _k31, _r41);
_sum10 = vmlaq_f32(_sum10, _k32, _r42);
_sum10 = vmlaq_f32(_sum10, _k33, _r43);
_sum10 = vmlaq_f32(_sum10, _k34, _r44);
_sum11 = vmlaq_f32(_sum11, _k30, _r41);
_sum11 = vmlaq_f32(_sum11, _k31, _r42);
_sum11 = vmlaq_f32(_sum11, _k32, _r43);
_sum11 = vmlaq_f32(_sum11, _k33, _r44);
_sum11 = vmlaq_f32(_sum11, _k34, _r45);
_sum00 = vmlaq_f32(_sum00, _k40, _r40);
_sum00 = vmlaq_f32(_sum00, _k41, _r41);
_sum00 = vmlaq_f32(_sum00, _k42, _r42);
_sum00 = vmlaq_f32(_sum00, _k43, _r43);
_sum00 = vmlaq_f32(_sum00, _k44, _r44);
_sum01 = vmlaq_f32(_sum01, _k40, _r41);
_sum01 = vmlaq_f32(_sum01, _k41, _r42);
_sum01 = vmlaq_f32(_sum01, _k42, _r43);
_sum01 = vmlaq_f32(_sum01, _k43, _r44);
_sum01 = vmlaq_f32(_sum01, _k44, _r45);
float32x4_t _r50 = vld1q_f32(r5);
float32x4_t _r51 = vld1q_f32(r5 + 4);
float32x4_t _r52 = vld1q_f32(r5 + 8);
float32x4_t _r53 = vld1q_f32(r5 + 12);
float32x4_t _r54 = vld1q_f32(r5 + 16);
float32x4_t _r55 = vld1q_f32(r5 + 20);
_sum10 = vmlaq_f32(_sum10, _k40, _r50);
_sum10 = vmlaq_f32(_sum10, _k41, _r51);
_sum10 = vmlaq_f32(_sum10, _k42, _r52);
_sum10 = vmlaq_f32(_sum10, _k43, _r53);
_sum10 = vmlaq_f32(_sum10, _k44, _r54);
_sum11 = vmlaq_f32(_sum11, _k40, _r51);
_sum11 = vmlaq_f32(_sum11, _k41, _r52);
_sum11 = vmlaq_f32(_sum11, _k42, _r53);
_sum11 = vmlaq_f32(_sum11, _k43, _r54);
_sum11 = vmlaq_f32(_sum11, _k44, _r55);
vst1q_f32(outptr0, _sum00);
vst1q_f32(outptr0 + 4, _sum01);
vst1q_f32(outptr1, _sum10);
vst1q_f32(outptr1 + 4, _sum11);
r0 += 8;
r1 += 8;
r2 += 8;
r3 += 8;
r4 += 8;
r5 += 8;
outptr0 += 8;
outptr1 += 8;
}
for (; j < outw; j++)
{
float32x4_t _sum0 = _bias0;
float32x4_t _sum1 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k00, _r00);
_sum0 = vmlaq_f32(_sum0, _k01, _r01);
_sum0 = vmlaq_f32(_sum0, _k02, _r02);
_sum0 = vmlaq_f32(_sum0, _k03, _r03);
_sum0 = vmlaq_f32(_sum0, _k04, _r04);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum1 = vmlaq_f32(_sum1, _k00, _r10);
_sum1 = vmlaq_f32(_sum1, _k01, _r11);
_sum1 = vmlaq_f32(_sum1, _k02, _r12);
_sum1 = vmlaq_f32(_sum1, _k03, _r13);
_sum1 = vmlaq_f32(_sum1, _k04, _r14);
_sum0 = vmlaq_f32(_sum0, _k10, _r10);
_sum0 = vmlaq_f32(_sum0, _k11, _r11);
_sum0 = vmlaq_f32(_sum0, _k12, _r12);
_sum0 = vmlaq_f32(_sum0, _k13, _r13);
_sum0 = vmlaq_f32(_sum0, _k14, _r14);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum1 = vmlaq_f32(_sum1, _k10, _r20);
_sum1 = vmlaq_f32(_sum1, _k11, _r21);
_sum1 = vmlaq_f32(_sum1, _k12, _r22);
_sum1 = vmlaq_f32(_sum1, _k13, _r23);
_sum1 = vmlaq_f32(_sum1, _k14, _r24);
_sum0 = vmlaq_f32(_sum0, _k20, _r20);
_sum0 = vmlaq_f32(_sum0, _k21, _r21);
_sum0 = vmlaq_f32(_sum0, _k22, _r22);
_sum0 = vmlaq_f32(_sum0, _k23, _r23);
_sum0 = vmlaq_f32(_sum0, _k24, _r24);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum1 = vmlaq_f32(_sum1, _k20, _r30);
_sum1 = vmlaq_f32(_sum1, _k21, _r31);
_sum1 = vmlaq_f32(_sum1, _k22, _r32);
_sum1 = vmlaq_f32(_sum1, _k23, _r33);
_sum1 = vmlaq_f32(_sum1, _k24, _r34);
_sum0 = vmlaq_f32(_sum0, _k30, _r30);
_sum0 = vmlaq_f32(_sum0, _k31, _r31);
_sum0 = vmlaq_f32(_sum0, _k32, _r32);
_sum0 = vmlaq_f32(_sum0, _k33, _r33);
_sum0 = vmlaq_f32(_sum0, _k34, _r34);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum1 = vmlaq_f32(_sum1, _k30, _r40);
_sum1 = vmlaq_f32(_sum1, _k31, _r41);
_sum1 = vmlaq_f32(_sum1, _k32, _r42);
_sum1 = vmlaq_f32(_sum1, _k33, _r43);
_sum1 = vmlaq_f32(_sum1, _k34, _r44);
_sum0 = vmlaq_f32(_sum0, _k40, _r40);
_sum0 = vmlaq_f32(_sum0, _k41, _r41);
_sum0 = vmlaq_f32(_sum0, _k42, _r42);
_sum0 = vmlaq_f32(_sum0, _k43, _r43);
_sum0 = vmlaq_f32(_sum0, _k44, _r44);
float32x4_t _r50 = vld1q_f32(r5);
float32x4_t _r51 = vld1q_f32(r5 + 4);
float32x4_t _r52 = vld1q_f32(r5 + 8);
float32x4_t _r53 = vld1q_f32(r5 + 12);
float32x4_t _r54 = vld1q_f32(r5 + 16);
_sum1 = vmlaq_f32(_sum1, _k40, _r50);
_sum1 = vmlaq_f32(_sum1, _k41, _r51);
_sum1 = vmlaq_f32(_sum1, _k42, _r52);
_sum1 = vmlaq_f32(_sum1, _k43, _r53);
_sum1 = vmlaq_f32(_sum1, _k44, _r54);
vst1q_f32(outptr0, _sum0);
vst1q_f32(outptr1, _sum1);
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
r5 += 4;
outptr0 += 4;
outptr1 += 4;
}
r0 += 4 * 4 + w * 4;
r1 += 4 * 4 + w * 4;
r2 += 4 * 4 + w * 4;
r3 += 4 * 4 + w * 4;
r4 += 4 * 4 + w * 4;
r5 += 4 * 4 + w * 4;
outptr0 += outw * 4;
outptr1 += outw * 4;
}
#endif // __aarch64__
for (; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
float32x4_t _sum0 = _bias0;
float32x4_t _sum1 = _bias0;
float32x4_t _sum2 = _bias0;
float32x4_t _sum3 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _r05 = vld1q_f32(r0 + 20);
float32x4_t _r06 = vld1q_f32(r0 + 24);
float32x4_t _r07 = vld1q_f32(r0 + 28);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k00, _r00);
_sum0 = vmlaq_f32(_sum0, _k01, _r01);
_sum0 = vmlaq_f32(_sum0, _k02, _r02);
_sum0 = vmlaq_f32(_sum0, _k03, _r03);
_sum0 = vmlaq_f32(_sum0, _k04, _r04);
_sum1 = vmlaq_f32(_sum1, _k00, _r01);
_sum1 = vmlaq_f32(_sum1, _k01, _r02);
_sum1 = vmlaq_f32(_sum1, _k02, _r03);
_sum1 = vmlaq_f32(_sum1, _k03, _r04);
_sum1 = vmlaq_f32(_sum1, _k04, _r05);
_sum2 = vmlaq_f32(_sum2, _k00, _r02);
_sum2 = vmlaq_f32(_sum2, _k01, _r03);
_sum2 = vmlaq_f32(_sum2, _k02, _r04);
_sum2 = vmlaq_f32(_sum2, _k03, _r05);
_sum2 = vmlaq_f32(_sum2, _k04, _r06);
_sum3 = vmlaq_f32(_sum3, _k00, _r03);
_sum3 = vmlaq_f32(_sum3, _k01, _r04);
_sum3 = vmlaq_f32(_sum3, _k02, _r05);
_sum3 = vmlaq_f32(_sum3, _k03, _r06);
_sum3 = vmlaq_f32(_sum3, _k04, _r07);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _r15 = vld1q_f32(r1 + 20);
float32x4_t _r16 = vld1q_f32(r1 + 24);
float32x4_t _r17 = vld1q_f32(r1 + 28);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k10, _r10);
_sum0 = vmlaq_f32(_sum0, _k11, _r11);
_sum0 = vmlaq_f32(_sum0, _k12, _r12);
_sum0 = vmlaq_f32(_sum0, _k13, _r13);
_sum0 = vmlaq_f32(_sum0, _k14, _r14);
_sum1 = vmlaq_f32(_sum1, _k10, _r11);
_sum1 = vmlaq_f32(_sum1, _k11, _r12);
_sum1 = vmlaq_f32(_sum1, _k12, _r13);
_sum1 = vmlaq_f32(_sum1, _k13, _r14);
_sum1 = vmlaq_f32(_sum1, _k14, _r15);
_sum2 = vmlaq_f32(_sum2, _k10, _r12);
_sum2 = vmlaq_f32(_sum2, _k11, _r13);
_sum2 = vmlaq_f32(_sum2, _k12, _r14);
_sum2 = vmlaq_f32(_sum2, _k13, _r15);
_sum2 = vmlaq_f32(_sum2, _k14, _r16);
_sum3 = vmlaq_f32(_sum3, _k10, _r13);
_sum3 = vmlaq_f32(_sum3, _k11, _r14);
_sum3 = vmlaq_f32(_sum3, _k12, _r15);
_sum3 = vmlaq_f32(_sum3, _k13, _r16);
_sum3 = vmlaq_f32(_sum3, _k14, _r17);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _r25 = vld1q_f32(r2 + 20);
float32x4_t _r26 = vld1q_f32(r2 + 24);
float32x4_t _r27 = vld1q_f32(r2 + 28);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k20, _r20);
_sum0 = vmlaq_f32(_sum0, _k21, _r21);
_sum0 = vmlaq_f32(_sum0, _k22, _r22);
_sum0 = vmlaq_f32(_sum0, _k23, _r23);
_sum0 = vmlaq_f32(_sum0, _k24, _r24);
_sum1 = vmlaq_f32(_sum1, _k20, _r21);
_sum1 = vmlaq_f32(_sum1, _k21, _r22);
_sum1 = vmlaq_f32(_sum1, _k22, _r23);
_sum1 = vmlaq_f32(_sum1, _k23, _r24);
_sum1 = vmlaq_f32(_sum1, _k24, _r25);
_sum2 = vmlaq_f32(_sum2, _k20, _r22);
_sum2 = vmlaq_f32(_sum2, _k21, _r23);
_sum2 = vmlaq_f32(_sum2, _k22, _r24);
_sum2 = vmlaq_f32(_sum2, _k23, _r25);
_sum2 = vmlaq_f32(_sum2, _k24, _r26);
_sum3 = vmlaq_f32(_sum3, _k20, _r23);
_sum3 = vmlaq_f32(_sum3, _k21, _r24);
_sum3 = vmlaq_f32(_sum3, _k22, _r25);
_sum3 = vmlaq_f32(_sum3, _k23, _r26);
_sum3 = vmlaq_f32(_sum3, _k24, _r27);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _r35 = vld1q_f32(r3 + 20);
float32x4_t _r36 = vld1q_f32(r3 + 24);
float32x4_t _r37 = vld1q_f32(r3 + 28);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k30, _r30);
_sum0 = vmlaq_f32(_sum0, _k31, _r31);
_sum0 = vmlaq_f32(_sum0, _k32, _r32);
_sum0 = vmlaq_f32(_sum0, _k33, _r33);
_sum0 = vmlaq_f32(_sum0, _k34, _r34);
_sum1 = vmlaq_f32(_sum1, _k30, _r31);
_sum1 = vmlaq_f32(_sum1, _k31, _r32);
_sum1 = vmlaq_f32(_sum1, _k32, _r33);
_sum1 = vmlaq_f32(_sum1, _k33, _r34);
_sum1 = vmlaq_f32(_sum1, _k34, _r35);
_sum2 = vmlaq_f32(_sum2, _k30, _r32);
_sum2 = vmlaq_f32(_sum2, _k31, _r33);
_sum2 = vmlaq_f32(_sum2, _k32, _r34);
_sum2 = vmlaq_f32(_sum2, _k33, _r35);
_sum2 = vmlaq_f32(_sum2, _k34, _r36);
_sum3 = vmlaq_f32(_sum3, _k30, _r33);
_sum3 = vmlaq_f32(_sum3, _k31, _r34);
_sum3 = vmlaq_f32(_sum3, _k32, _r35);
_sum3 = vmlaq_f32(_sum3, _k33, _r36);
_sum3 = vmlaq_f32(_sum3, _k34, _r37);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _r45 = vld1q_f32(r4 + 20);
float32x4_t _r46 = vld1q_f32(r4 + 24);
float32x4_t _r47 = vld1q_f32(r4 + 28);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum0 = vmlaq_f32(_sum0, _k40, _r40);
_sum0 = vmlaq_f32(_sum0, _k41, _r41);
_sum0 = vmlaq_f32(_sum0, _k42, _r42);
_sum0 = vmlaq_f32(_sum0, _k43, _r43);
_sum0 = vmlaq_f32(_sum0, _k44, _r44);
_sum1 = vmlaq_f32(_sum1, _k40, _r41);
_sum1 = vmlaq_f32(_sum1, _k41, _r42);
_sum1 = vmlaq_f32(_sum1, _k42, _r43);
_sum1 = vmlaq_f32(_sum1, _k43, _r44);
_sum1 = vmlaq_f32(_sum1, _k44, _r45);
_sum2 = vmlaq_f32(_sum2, _k40, _r42);
_sum2 = vmlaq_f32(_sum2, _k41, _r43);
_sum2 = vmlaq_f32(_sum2, _k42, _r44);
_sum2 = vmlaq_f32(_sum2, _k43, _r45);
_sum2 = vmlaq_f32(_sum2, _k44, _r46);
_sum3 = vmlaq_f32(_sum3, _k40, _r43);
_sum3 = vmlaq_f32(_sum3, _k41, _r44);
_sum3 = vmlaq_f32(_sum3, _k42, _r45);
_sum3 = vmlaq_f32(_sum3, _k43, _r46);
_sum3 = vmlaq_f32(_sum3, _k44, _r47);
vst1q_f32(outptr0, _sum0);
vst1q_f32(outptr0 + 4, _sum1);
vst1q_f32(outptr0 + 8, _sum2);
vst1q_f32(outptr0 + 12, _sum3);
r0 += 16;
r1 += 16;
r2 += 16;
r3 += 16;
r4 += 16;
outptr0 += 16;
}
for (; j + 1 < outw; j += 2)
{
float32x4_t _sum0 = _bias0;
float32x4_t _sum1 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _r05 = vld1q_f32(r0 + 20);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k00, _r00);
_sum0 = vmlaq_f32(_sum0, _k01, _r01);
_sum0 = vmlaq_f32(_sum0, _k02, _r02);
_sum0 = vmlaq_f32(_sum0, _k03, _r03);
_sum0 = vmlaq_f32(_sum0, _k04, _r04);
_sum1 = vmlaq_f32(_sum1, _k00, _r01);
_sum1 = vmlaq_f32(_sum1, _k01, _r02);
_sum1 = vmlaq_f32(_sum1, _k02, _r03);
_sum1 = vmlaq_f32(_sum1, _k03, _r04);
_sum1 = vmlaq_f32(_sum1, _k04, _r05);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _r15 = vld1q_f32(r1 + 20);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k10, _r10);
_sum0 = vmlaq_f32(_sum0, _k11, _r11);
_sum0 = vmlaq_f32(_sum0, _k12, _r12);
_sum0 = vmlaq_f32(_sum0, _k13, _r13);
_sum0 = vmlaq_f32(_sum0, _k14, _r14);
_sum1 = vmlaq_f32(_sum1, _k10, _r11);
_sum1 = vmlaq_f32(_sum1, _k11, _r12);
_sum1 = vmlaq_f32(_sum1, _k12, _r13);
_sum1 = vmlaq_f32(_sum1, _k13, _r14);
_sum1 = vmlaq_f32(_sum1, _k14, _r15);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _r25 = vld1q_f32(r2 + 20);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k20, _r20);
_sum0 = vmlaq_f32(_sum0, _k21, _r21);
_sum0 = vmlaq_f32(_sum0, _k22, _r22);
_sum0 = vmlaq_f32(_sum0, _k23, _r23);
_sum0 = vmlaq_f32(_sum0, _k24, _r24);
_sum1 = vmlaq_f32(_sum1, _k20, _r21);
_sum1 = vmlaq_f32(_sum1, _k21, _r22);
_sum1 = vmlaq_f32(_sum1, _k22, _r23);
_sum1 = vmlaq_f32(_sum1, _k23, _r24);
_sum1 = vmlaq_f32(_sum1, _k24, _r25);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _r35 = vld1q_f32(r3 + 20);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k30, _r30);
_sum0 = vmlaq_f32(_sum0, _k31, _r31);
_sum0 = vmlaq_f32(_sum0, _k32, _r32);
_sum0 = vmlaq_f32(_sum0, _k33, _r33);
_sum0 = vmlaq_f32(_sum0, _k34, _r34);
_sum1 = vmlaq_f32(_sum1, _k30, _r31);
_sum1 = vmlaq_f32(_sum1, _k31, _r32);
_sum1 = vmlaq_f32(_sum1, _k32, _r33);
_sum1 = vmlaq_f32(_sum1, _k33, _r34);
_sum1 = vmlaq_f32(_sum1, _k34, _r35);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _r45 = vld1q_f32(r4 + 20);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum0 = vmlaq_f32(_sum0, _k40, _r40);
_sum0 = vmlaq_f32(_sum0, _k41, _r41);
_sum0 = vmlaq_f32(_sum0, _k42, _r42);
_sum0 = vmlaq_f32(_sum0, _k43, _r43);
_sum0 = vmlaq_f32(_sum0, _k44, _r44);
_sum1 = vmlaq_f32(_sum1, _k40, _r41);
_sum1 = vmlaq_f32(_sum1, _k41, _r42);
_sum1 = vmlaq_f32(_sum1, _k42, _r43);
_sum1 = vmlaq_f32(_sum1, _k43, _r44);
_sum1 = vmlaq_f32(_sum1, _k44, _r45);
vst1q_f32(outptr0, _sum0);
vst1q_f32(outptr0 + 4, _sum1);
r0 += 8;
r1 += 8;
r2 += 8;
r3 += 8;
r4 += 8;
outptr0 += 8;
}
for (; j < outw; j++)
{
float32x4_t _sum0 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k00, _r00);
_sum0 = vmlaq_f32(_sum0, _k01, _r01);
_sum0 = vmlaq_f32(_sum0, _k02, _r02);
_sum0 = vmlaq_f32(_sum0, _k03, _r03);
_sum0 = vmlaq_f32(_sum0, _k04, _r04);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k10, _r10);
_sum0 = vmlaq_f32(_sum0, _k11, _r11);
_sum0 = vmlaq_f32(_sum0, _k12, _r12);
_sum0 = vmlaq_f32(_sum0, _k13, _r13);
_sum0 = vmlaq_f32(_sum0, _k14, _r14);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k20, _r20);
_sum0 = vmlaq_f32(_sum0, _k21, _r21);
_sum0 = vmlaq_f32(_sum0, _k22, _r22);
_sum0 = vmlaq_f32(_sum0, _k23, _r23);
_sum0 = vmlaq_f32(_sum0, _k24, _r24);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k30, _r30);
_sum0 = vmlaq_f32(_sum0, _k31, _r31);
_sum0 = vmlaq_f32(_sum0, _k32, _r32);
_sum0 = vmlaq_f32(_sum0, _k33, _r33);
_sum0 = vmlaq_f32(_sum0, _k34, _r34);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum0 = vmlaq_f32(_sum0, _k40, _r40);
_sum0 = vmlaq_f32(_sum0, _k41, _r41);
_sum0 = vmlaq_f32(_sum0, _k42, _r42);
_sum0 = vmlaq_f32(_sum0, _k43, _r43);
_sum0 = vmlaq_f32(_sum0, _k44, _r44);
vst1q_f32(outptr0, _sum0);
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
outptr0 += 4;
}
r0 += 4 * 4;
r1 += 4 * 4;
r2 += 4 * 4;
r3 += 4 * 4;
r4 += 4 * 4;
}
}
}
static void convdw5x5s2_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int outw = top_blob.w;
int outh = top_blob.h;
const int group = bottom_blob.c;
const int tailstep = (w - 2 * outw + w) * 4;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int g = 0; g < group; g++)
{
Mat out = top_blob.channel(g);
float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + g * 4) : vdupq_n_f32(0.f);
const float* k0 = kernel.row(g);
float* outptr0 = out;
const Mat img0 = bottom_blob.channel(g);
const float* r0 = img0.row(0);
const float* r1 = img0.row(1);
const float* r2 = img0.row(2);
const float* r3 = img0.row(3);
const float* r4 = img0.row(4);
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
float32x4_t _sum0 = _bias0;
float32x4_t _sum1 = _bias0;
float32x4_t _sum2 = _bias0;
float32x4_t _sum3 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _r05 = vld1q_f32(r0 + 20);
float32x4_t _r06 = vld1q_f32(r0 + 24);
float32x4_t _r07 = vld1q_f32(r0 + 28);
float32x4_t _r08 = vld1q_f32(r0 + 32);
float32x4_t _r09 = vld1q_f32(r0 + 36);
float32x4_t _r010 = vld1q_f32(r0 + 40);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k00, _r00);
_sum0 = vmlaq_f32(_sum0, _k01, _r01);
_sum0 = vmlaq_f32(_sum0, _k02, _r02);
_sum0 = vmlaq_f32(_sum0, _k03, _r03);
_sum0 = vmlaq_f32(_sum0, _k04, _r04);
_sum1 = vmlaq_f32(_sum1, _k00, _r02);
_sum1 = vmlaq_f32(_sum1, _k01, _r03);
_sum1 = vmlaq_f32(_sum1, _k02, _r04);
_sum1 = vmlaq_f32(_sum1, _k03, _r05);
_sum1 = vmlaq_f32(_sum1, _k04, _r06);
_sum2 = vmlaq_f32(_sum2, _k00, _r04);
_sum2 = vmlaq_f32(_sum2, _k01, _r05);
_sum2 = vmlaq_f32(_sum2, _k02, _r06);
_sum2 = vmlaq_f32(_sum2, _k03, _r07);
_sum2 = vmlaq_f32(_sum2, _k04, _r08);
_sum3 = vmlaq_f32(_sum3, _k00, _r06);
_sum3 = vmlaq_f32(_sum3, _k01, _r07);
_sum3 = vmlaq_f32(_sum3, _k02, _r08);
_sum3 = vmlaq_f32(_sum3, _k03, _r09);
_sum3 = vmlaq_f32(_sum3, _k04, _r010);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _r15 = vld1q_f32(r1 + 20);
float32x4_t _r16 = vld1q_f32(r1 + 24);
float32x4_t _r17 = vld1q_f32(r1 + 28);
float32x4_t _r18 = vld1q_f32(r1 + 32);
float32x4_t _r19 = vld1q_f32(r1 + 36);
float32x4_t _r110 = vld1q_f32(r1 + 40);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k10, _r10);
_sum0 = vmlaq_f32(_sum0, _k11, _r11);
_sum0 = vmlaq_f32(_sum0, _k12, _r12);
_sum0 = vmlaq_f32(_sum0, _k13, _r13);
_sum0 = vmlaq_f32(_sum0, _k14, _r14);
_sum1 = vmlaq_f32(_sum1, _k10, _r12);
_sum1 = vmlaq_f32(_sum1, _k11, _r13);
_sum1 = vmlaq_f32(_sum1, _k12, _r14);
_sum1 = vmlaq_f32(_sum1, _k13, _r15);
_sum1 = vmlaq_f32(_sum1, _k14, _r16);
_sum2 = vmlaq_f32(_sum2, _k10, _r14);
_sum2 = vmlaq_f32(_sum2, _k11, _r15);
_sum2 = vmlaq_f32(_sum2, _k12, _r16);
_sum2 = vmlaq_f32(_sum2, _k13, _r17);
_sum2 = vmlaq_f32(_sum2, _k14, _r18);
_sum3 = vmlaq_f32(_sum3, _k10, _r16);
_sum3 = vmlaq_f32(_sum3, _k11, _r17);
_sum3 = vmlaq_f32(_sum3, _k12, _r18);
_sum3 = vmlaq_f32(_sum3, _k13, _r19);
_sum3 = vmlaq_f32(_sum3, _k14, _r110);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _r25 = vld1q_f32(r2 + 20);
float32x4_t _r26 = vld1q_f32(r2 + 24);
float32x4_t _r27 = vld1q_f32(r2 + 28);
float32x4_t _r28 = vld1q_f32(r2 + 32);
float32x4_t _r29 = vld1q_f32(r2 + 36);
float32x4_t _r210 = vld1q_f32(r2 + 40);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k20, _r20);
_sum0 = vmlaq_f32(_sum0, _k21, _r21);
_sum0 = vmlaq_f32(_sum0, _k22, _r22);
_sum0 = vmlaq_f32(_sum0, _k23, _r23);
_sum0 = vmlaq_f32(_sum0, _k24, _r24);
_sum1 = vmlaq_f32(_sum1, _k20, _r22);
_sum1 = vmlaq_f32(_sum1, _k21, _r23);
_sum1 = vmlaq_f32(_sum1, _k22, _r24);
_sum1 = vmlaq_f32(_sum1, _k23, _r25);
_sum1 = vmlaq_f32(_sum1, _k24, _r26);
_sum2 = vmlaq_f32(_sum2, _k20, _r24);
_sum2 = vmlaq_f32(_sum2, _k21, _r25);
_sum2 = vmlaq_f32(_sum2, _k22, _r26);
_sum2 = vmlaq_f32(_sum2, _k23, _r27);
_sum2 = vmlaq_f32(_sum2, _k24, _r28);
_sum3 = vmlaq_f32(_sum3, _k20, _r26);
_sum3 = vmlaq_f32(_sum3, _k21, _r27);
_sum3 = vmlaq_f32(_sum3, _k22, _r28);
_sum3 = vmlaq_f32(_sum3, _k23, _r29);
_sum3 = vmlaq_f32(_sum3, _k24, _r210);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _r35 = vld1q_f32(r3 + 20);
float32x4_t _r36 = vld1q_f32(r3 + 24);
float32x4_t _r37 = vld1q_f32(r3 + 28);
float32x4_t _r38 = vld1q_f32(r3 + 32);
float32x4_t _r39 = vld1q_f32(r3 + 36);
float32x4_t _r310 = vld1q_f32(r3 + 40);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k30, _r30);
_sum0 = vmlaq_f32(_sum0, _k31, _r31);
_sum0 = vmlaq_f32(_sum0, _k32, _r32);
_sum0 = vmlaq_f32(_sum0, _k33, _r33);
_sum0 = vmlaq_f32(_sum0, _k34, _r34);
_sum1 = vmlaq_f32(_sum1, _k30, _r32);
_sum1 = vmlaq_f32(_sum1, _k31, _r33);
_sum1 = vmlaq_f32(_sum1, _k32, _r34);
_sum1 = vmlaq_f32(_sum1, _k33, _r35);
_sum1 = vmlaq_f32(_sum1, _k34, _r36);
_sum2 = vmlaq_f32(_sum2, _k30, _r34);
_sum2 = vmlaq_f32(_sum2, _k31, _r35);
_sum2 = vmlaq_f32(_sum2, _k32, _r36);
_sum2 = vmlaq_f32(_sum2, _k33, _r37);
_sum2 = vmlaq_f32(_sum2, _k34, _r38);
_sum3 = vmlaq_f32(_sum3, _k30, _r36);
_sum3 = vmlaq_f32(_sum3, _k31, _r37);
_sum3 = vmlaq_f32(_sum3, _k32, _r38);
_sum3 = vmlaq_f32(_sum3, _k33, _r39);
_sum3 = vmlaq_f32(_sum3, _k34, _r310);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _r45 = vld1q_f32(r4 + 20);
float32x4_t _r46 = vld1q_f32(r4 + 24);
float32x4_t _r47 = vld1q_f32(r4 + 28);
float32x4_t _r48 = vld1q_f32(r4 + 32);
float32x4_t _r49 = vld1q_f32(r4 + 36);
float32x4_t _r410 = vld1q_f32(r4 + 40);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum0 = vmlaq_f32(_sum0, _k40, _r40);
_sum0 = vmlaq_f32(_sum0, _k41, _r41);
_sum0 = vmlaq_f32(_sum0, _k42, _r42);
_sum0 = vmlaq_f32(_sum0, _k43, _r43);
_sum0 = vmlaq_f32(_sum0, _k44, _r44);
_sum1 = vmlaq_f32(_sum1, _k40, _r42);
_sum1 = vmlaq_f32(_sum1, _k41, _r43);
_sum1 = vmlaq_f32(_sum1, _k42, _r44);
_sum1 = vmlaq_f32(_sum1, _k43, _r45);
_sum1 = vmlaq_f32(_sum1, _k44, _r46);
_sum2 = vmlaq_f32(_sum2, _k40, _r44);
_sum2 = vmlaq_f32(_sum2, _k41, _r45);
_sum2 = vmlaq_f32(_sum2, _k42, _r46);
_sum2 = vmlaq_f32(_sum2, _k43, _r47);
_sum2 = vmlaq_f32(_sum2, _k44, _r48);
_sum3 = vmlaq_f32(_sum3, _k40, _r46);
_sum3 = vmlaq_f32(_sum3, _k41, _r47);
_sum3 = vmlaq_f32(_sum3, _k42, _r48);
_sum3 = vmlaq_f32(_sum3, _k43, _r49);
_sum3 = vmlaq_f32(_sum3, _k44, _r410);
vst1q_f32(outptr0, _sum0);
vst1q_f32(outptr0 + 4, _sum1);
vst1q_f32(outptr0 + 8, _sum2);
vst1q_f32(outptr0 + 12, _sum3);
r0 += 8 * 4;
r1 += 8 * 4;
r2 += 8 * 4;
r3 += 8 * 4;
r4 += 8 * 4;
outptr0 += 16;
}
for (; j + 1 < outw; j += 2)
{
float32x4_t _sum0 = _bias0;
float32x4_t _sum1 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _r05 = vld1q_f32(r0 + 20);
float32x4_t _r06 = vld1q_f32(r0 + 24);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k00, _r00);
_sum0 = vmlaq_f32(_sum0, _k01, _r01);
_sum0 = vmlaq_f32(_sum0, _k02, _r02);
_sum0 = vmlaq_f32(_sum0, _k03, _r03);
_sum0 = vmlaq_f32(_sum0, _k04, _r04);
_sum1 = vmlaq_f32(_sum1, _k00, _r02);
_sum1 = vmlaq_f32(_sum1, _k01, _r03);
_sum1 = vmlaq_f32(_sum1, _k02, _r04);
_sum1 = vmlaq_f32(_sum1, _k03, _r05);
_sum1 = vmlaq_f32(_sum1, _k04, _r06);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _r15 = vld1q_f32(r1 + 20);
float32x4_t _r16 = vld1q_f32(r1 + 24);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k10, _r10);
_sum0 = vmlaq_f32(_sum0, _k11, _r11);
_sum0 = vmlaq_f32(_sum0, _k12, _r12);
_sum0 = vmlaq_f32(_sum0, _k13, _r13);
_sum0 = vmlaq_f32(_sum0, _k14, _r14);
_sum1 = vmlaq_f32(_sum1, _k10, _r12);
_sum1 = vmlaq_f32(_sum1, _k11, _r13);
_sum1 = vmlaq_f32(_sum1, _k12, _r14);
_sum1 = vmlaq_f32(_sum1, _k13, _r15);
_sum1 = vmlaq_f32(_sum1, _k14, _r16);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _r25 = vld1q_f32(r2 + 20);
float32x4_t _r26 = vld1q_f32(r2 + 24);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k20, _r20);
_sum0 = vmlaq_f32(_sum0, _k21, _r21);
_sum0 = vmlaq_f32(_sum0, _k22, _r22);
_sum0 = vmlaq_f32(_sum0, _k23, _r23);
_sum0 = vmlaq_f32(_sum0, _k24, _r24);
_sum1 = vmlaq_f32(_sum1, _k20, _r22);
_sum1 = vmlaq_f32(_sum1, _k21, _r23);
_sum1 = vmlaq_f32(_sum1, _k22, _r24);
_sum1 = vmlaq_f32(_sum1, _k23, _r25);
_sum1 = vmlaq_f32(_sum1, _k24, _r26);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _r35 = vld1q_f32(r3 + 20);
float32x4_t _r36 = vld1q_f32(r3 + 24);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k30, _r30);
_sum0 = vmlaq_f32(_sum0, _k31, _r31);
_sum0 = vmlaq_f32(_sum0, _k32, _r32);
_sum0 = vmlaq_f32(_sum0, _k33, _r33);
_sum0 = vmlaq_f32(_sum0, _k34, _r34);
_sum1 = vmlaq_f32(_sum1, _k30, _r32);
_sum1 = vmlaq_f32(_sum1, _k31, _r33);
_sum1 = vmlaq_f32(_sum1, _k32, _r34);
_sum1 = vmlaq_f32(_sum1, _k33, _r35);
_sum1 = vmlaq_f32(_sum1, _k34, _r36);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _r45 = vld1q_f32(r4 + 20);
float32x4_t _r46 = vld1q_f32(r4 + 24);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum0 = vmlaq_f32(_sum0, _k40, _r40);
_sum0 = vmlaq_f32(_sum0, _k41, _r41);
_sum0 = vmlaq_f32(_sum0, _k42, _r42);
_sum0 = vmlaq_f32(_sum0, _k43, _r43);
_sum0 = vmlaq_f32(_sum0, _k44, _r44);
_sum1 = vmlaq_f32(_sum1, _k40, _r42);
_sum1 = vmlaq_f32(_sum1, _k41, _r43);
_sum1 = vmlaq_f32(_sum1, _k42, _r44);
_sum1 = vmlaq_f32(_sum1, _k43, _r45);
_sum1 = vmlaq_f32(_sum1, _k44, _r46);
vst1q_f32(outptr0, _sum0);
vst1q_f32(outptr0 + 4, _sum1);
r0 += 4 * 4;
r1 += 4 * 4;
r2 += 4 * 4;
r3 += 4 * 4;
r4 += 4 * 4;
outptr0 += 8;
}
for (; j < outw; j++)
{
float32x4_t _sum0 = _bias0;
float32x4_t _r00 = vld1q_f32(r0);
float32x4_t _r01 = vld1q_f32(r0 + 4);
float32x4_t _r02 = vld1q_f32(r0 + 8);
float32x4_t _r03 = vld1q_f32(r0 + 12);
float32x4_t _r04 = vld1q_f32(r0 + 16);
float32x4_t _k00 = vld1q_f32(k0);
float32x4_t _k01 = vld1q_f32(k0 + 4);
float32x4_t _k02 = vld1q_f32(k0 + 8);
float32x4_t _k03 = vld1q_f32(k0 + 12);
float32x4_t _k04 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k00, _r00);
_sum0 = vmlaq_f32(_sum0, _k01, _r01);
_sum0 = vmlaq_f32(_sum0, _k02, _r02);
_sum0 = vmlaq_f32(_sum0, _k03, _r03);
_sum0 = vmlaq_f32(_sum0, _k04, _r04);
float32x4_t _r10 = vld1q_f32(r1);
float32x4_t _r11 = vld1q_f32(r1 + 4);
float32x4_t _r12 = vld1q_f32(r1 + 8);
float32x4_t _r13 = vld1q_f32(r1 + 12);
float32x4_t _r14 = vld1q_f32(r1 + 16);
float32x4_t _k10 = vld1q_f32(k0);
float32x4_t _k11 = vld1q_f32(k0 + 4);
float32x4_t _k12 = vld1q_f32(k0 + 8);
float32x4_t _k13 = vld1q_f32(k0 + 12);
float32x4_t _k14 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k10, _r10);
_sum0 = vmlaq_f32(_sum0, _k11, _r11);
_sum0 = vmlaq_f32(_sum0, _k12, _r12);
_sum0 = vmlaq_f32(_sum0, _k13, _r13);
_sum0 = vmlaq_f32(_sum0, _k14, _r14);
float32x4_t _r20 = vld1q_f32(r2);
float32x4_t _r21 = vld1q_f32(r2 + 4);
float32x4_t _r22 = vld1q_f32(r2 + 8);
float32x4_t _r23 = vld1q_f32(r2 + 12);
float32x4_t _r24 = vld1q_f32(r2 + 16);
float32x4_t _k20 = vld1q_f32(k0);
float32x4_t _k21 = vld1q_f32(k0 + 4);
float32x4_t _k22 = vld1q_f32(k0 + 8);
float32x4_t _k23 = vld1q_f32(k0 + 12);
float32x4_t _k24 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k20, _r20);
_sum0 = vmlaq_f32(_sum0, _k21, _r21);
_sum0 = vmlaq_f32(_sum0, _k22, _r22);
_sum0 = vmlaq_f32(_sum0, _k23, _r23);
_sum0 = vmlaq_f32(_sum0, _k24, _r24);
float32x4_t _r30 = vld1q_f32(r3);
float32x4_t _r31 = vld1q_f32(r3 + 4);
float32x4_t _r32 = vld1q_f32(r3 + 8);
float32x4_t _r33 = vld1q_f32(r3 + 12);
float32x4_t _r34 = vld1q_f32(r3 + 16);
float32x4_t _k30 = vld1q_f32(k0);
float32x4_t _k31 = vld1q_f32(k0 + 4);
float32x4_t _k32 = vld1q_f32(k0 + 8);
float32x4_t _k33 = vld1q_f32(k0 + 12);
float32x4_t _k34 = vld1q_f32(k0 + 16);
k0 += 20;
_sum0 = vmlaq_f32(_sum0, _k30, _r30);
_sum0 = vmlaq_f32(_sum0, _k31, _r31);
_sum0 = vmlaq_f32(_sum0, _k32, _r32);
_sum0 = vmlaq_f32(_sum0, _k33, _r33);
_sum0 = vmlaq_f32(_sum0, _k34, _r34);
float32x4_t _r40 = vld1q_f32(r4);
float32x4_t _r41 = vld1q_f32(r4 + 4);
float32x4_t _r42 = vld1q_f32(r4 + 8);
float32x4_t _r43 = vld1q_f32(r4 + 12);
float32x4_t _r44 = vld1q_f32(r4 + 16);
float32x4_t _k40 = vld1q_f32(k0);
float32x4_t _k41 = vld1q_f32(k0 + 4);
float32x4_t _k42 = vld1q_f32(k0 + 8);
float32x4_t _k43 = vld1q_f32(k0 + 12);
float32x4_t _k44 = vld1q_f32(k0 + 16);
k0 -= 80;
_sum0 = vmlaq_f32(_sum0, _k40, _r40);
_sum0 = vmlaq_f32(_sum0, _k41, _r41);
_sum0 = vmlaq_f32(_sum0, _k42, _r42);
_sum0 = vmlaq_f32(_sum0, _k43, _r43);
_sum0 = vmlaq_f32(_sum0, _k44, _r44);
vst1q_f32(outptr0, _sum0);
r0 += 2 * 4;
r1 += 2 * 4;
r2 += 2 * 4;
r3 += 2 * 4;
r4 += 2 * 4;
outptr0 += 4;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
r3 += tailstep;
r4 += tailstep;
}
}
}
|
GB_unop__identity_int16_fp32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_int16_fp32)
// op(A') function: GB (_unop_tran__identity_int16_fp32)
// C type: int16_t
// A type: float
// cast: int16_t cij = GB_cast_to_int16_t ((double) (aij))
// unaryop: cij = aij
#define GB_ATYPE \
float
#define GB_CTYPE \
int16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
int16_t z = GB_cast_to_int16_t ((double) (aij)) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
float aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
int16_t z = GB_cast_to_int16_t ((double) (aij)) ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_int16_fp32)
(
int16_t *Cx, // Cx and Ax may be aliased
const float *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
// 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] ;
int16_t z = GB_cast_to_int16_t ((double) (aij)) ;
Cx [p] = z ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
float aij = Ax [p] ;
int16_t z = GB_cast_to_int16_t ((double) (aij)) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_int16_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
|
stream.c | /*-----------------------------------------------------------------------*/
/* Program: STREAM */
/* Revision: $Id: stream.c,v 5.10 2013/01/17 16:01:06 mccalpin Exp mccalpin $ */
/* Original code developed by John D. McCalpin */
/* Programmers: John D. McCalpin */
/* Joe R. Zagar */
/* */
/* This program measures memory transfer rates in MB/s for simple */
/* computational kernels coded in C. */
/*-----------------------------------------------------------------------*/
/* Copyright 1991-2013: John D. McCalpin */
/*-----------------------------------------------------------------------*/
/* License: */
/* 1. You are free to use this program and/or to redistribute */
/* this program. */
/* 2. You are free to modify this program for your own use, */
/* including commercial use, subject to the publication */
/* restrictions in item 3. */
/* 3. You are free to publish results obtained from running this */
/* program, or from works that you derive from this program, */
/* with the following limitations: */
/* 3a. In order to be referred to as "STREAM benchmark results", */
/* published results must be in conformance to the STREAM */
/* Run Rules, (briefly reviewed below) published at */
/* http://www.cs.virginia.edu/stream/ref.html */
/* and incorporated herein by reference. */
/* As the copyright holder, John McCalpin retains the */
/* right to determine conformity with the Run Rules. */
/* 3b. Results based on modified source code or on runs not in */
/* accordance with the STREAM Run Rules must be clearly */
/* labelled whenever they are published. Examples of */
/* proper labelling include: */
/* "tuned STREAM benchmark results" */
/* "based on a variant of the STREAM benchmark code" */
/* Other comparable, clear, and reasonable labelling is */
/* acceptable. */
/* 3c. Submission of results to the STREAM benchmark web site */
/* is encouraged, but not required. */
/* 4. Use of this program or creation of derived works based on this */
/* program constitutes acceptance of these licensing restrictions. */
/* 5. Absolutely no warranty is expressed or implied. */
/*-----------------------------------------------------------------------*/
# include <stdio.h>
# include <unistd.h>
# include <math.h>
# include <float.h>
# include <limits.h>
# include <sys/time.h>
/*-----------------------------------------------------------------------
* INSTRUCTIONS:
*
* 1) STREAM requires different amounts of memory to run on different
* systems, depending on both the system cache size(s) and the
* granularity of the system timer.
* You should adjust the value of 'STREAM_ARRAY_SIZE' (below)
* to meet *both* of the following criteria:
* (a) Each array must be at least 4 times the size of the
* available cache memory. I don't worry about the difference
* between 10^6 and 2^20, so in practice the minimum array size
* is about 3.8 times the cache size.
* Example 1: One Xeon E3 with 8 MB L3 cache
* STREAM_ARRAY_SIZE should be >= 4 million, giving
* an array size of 30.5 MB and a total memory requirement
* of 91.5 MB.
* Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP)
* STREAM_ARRAY_SIZE should be >= 20 million, giving
* an array size of 153 MB and a total memory requirement
* of 458 MB.
* (b) The size should be large enough so that the 'timing calibration'
* output by the program is at least 20 clock-ticks.
* Example: most versions of Windows have a 10 millisecond timer
* granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds.
* If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec.
* This means the each array must be at least 1 GB, or 128M elements.
*
* Version 5.10 increases the default array size from 2 million
* elements to 10 million elements in response to the increasing
* size of L3 caches. The new default size is large enough for caches
* up to 20 MB.
* Version 5.10 changes the loop index variables from "register int"
* to "ssize_t", which allows array indices >2^32 (4 billion)
* on properly configured 64-bit systems. Additional compiler options
* (such as "-mcmodel=medium") may be required for large memory runs.
*
* Array size can be set at compile time without modifying the source
* code for the (many) compilers that support preprocessor definitions
* on the compile line. E.g.,
* gcc -O -DSTREAM_ARRAY_SIZE=100000000 stream.c -o stream.100M
* will override the default size of 10M with a new size of 100M elements
* per array.
*/
#ifndef STREAM_ARRAY_SIZE
# define STREAM_ARRAY_SIZE 10000000
#endif
/* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result
* for any iteration after the first, therefore the minimum value
* for NTIMES is 2.
* There are no rules on maximum allowable values for NTIMES, but
* values larger than the default are unlikely to noticeably
* increase the reported performance.
* NTIMES can also be set on the compile line without changing the source
* code using, for example, "-DNTIMES=7".
*/
#ifdef NTIMES
#if NTIMES<=1
# define NTIMES 10
#endif
#endif
#ifndef NTIMES
# define NTIMES 10
#endif
/* Users are allowed to modify the "OFFSET" variable, which *may* change the
* relative alignment of the arrays (though compilers may change the
* effective offset by making the arrays non-contiguous on some systems).
* Use of non-zero values for OFFSET can be especially helpful if the
* STREAM_ARRAY_SIZE is set to a value close to a large power of 2.
* OFFSET can also be set on the compile line without changing the source
* code using, for example, "-DOFFSET=56".
*/
#ifndef OFFSET
# define OFFSET 0
#endif
/*
* 3) Compile the code with optimization. Many compilers generate
* unreasonably bad code before the optimizer tightens things up.
* If the results are unreasonably good, on the other hand, the
* optimizer might be too smart for me!
*
* For a simple single-core version, try compiling with:
* cc -O stream.c -o stream
* This is known to work on many, many systems....
*
* To use multiple cores, you need to tell the compiler to obey the OpenMP
* directives in the code. This varies by compiler, but a common example is
* gcc -O -fopenmp stream.c -o stream_omp
* The environment variable OMP_NUM_THREADS allows runtime control of the
* number of threads/cores used when the resulting "stream_omp" program
* is executed.
*
* To run with single-precision variables and arithmetic, simply add
* -DSTREAM_TYPE=float
* to the compile line.
* Note that this changes the minimum array sizes required --- see (1) above.
*
* The preprocessor directive "TUNED" does not do much -- it simply causes the
* code to call separate functions to execute each kernel. Trivial versions
* of these functions are provided, but they are *not* tuned -- they just
* provide predefined interfaces to be replaced with tuned code.
*
*
* 4) Optional: Mail the results to mccalpin@cs.virginia.edu
* Be sure to include info that will help me understand:
* a) the computer hardware configuration (e.g., processor model, memory type)
* b) the compiler name/version and compilation flags
* c) any run-time information (such as OMP_NUM_THREADS)
* d) all of the output from the test case.
*
* Thanks!
*
*-----------------------------------------------------------------------*/
# define HLINE "-------------------------------------------------------------\n"
# ifndef MIN
# define MIN(x,y) ((x)<(y)?(x):(y))
# endif
# ifndef MAX
# define MAX(x,y) ((x)>(y)?(x):(y))
# endif
#ifndef STREAM_TYPE
#define STREAM_TYPE double
#endif
static STREAM_TYPE a[STREAM_ARRAY_SIZE+OFFSET],
b[STREAM_ARRAY_SIZE+OFFSET],
c[STREAM_ARRAY_SIZE+OFFSET];
static double avgtime[4] = {0}, maxtime[4] = {0},
mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};
static char *label[4] = {"Copy: ", "Scale: ",
"Add: ", "Triad: "};
static double bytes[4] = {
2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
2 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE,
3 * sizeof(STREAM_TYPE) * STREAM_ARRAY_SIZE
};
extern double mysecond();
extern void checkSTREAMresults();
#ifdef TUNED
extern void tuned_STREAM_Copy();
extern void tuned_STREAM_Scale(STREAM_TYPE scalar);
extern void tuned_STREAM_Add();
extern void tuned_STREAM_Triad(STREAM_TYPE scalar);
#endif
#ifdef _OPENMP
extern int omp_get_num_threads();
#endif
int
main()
{
int quantum, checktick();
int BytesPerWord;
int k;
ssize_t j;
STREAM_TYPE scalar;
double t, times[4][NTIMES];
/* --- SETUP --- determine precision and check timing --- */
printf(HLINE);
printf("STREAM version $Revision: 5.10 $\n");
printf(HLINE);
BytesPerWord = sizeof(STREAM_TYPE);
printf("This system uses %d bytes per array element.\n",
BytesPerWord);
printf(HLINE);
#ifdef N
printf("***** WARNING: ******\n");
printf(" It appears that you set the preprocessor variable N when compiling this code.\n");
printf(" This version of the code uses the preprocesor variable STREAM_ARRAY_SIZE to control the array size\n");
printf(" Reverting to default value of STREAM_ARRAY_SIZE=%llu\n",(unsigned long long) STREAM_ARRAY_SIZE);
printf("***** WARNING: ******\n");
#endif
printf("Array size = %llu (elements), Offset = %d (elements)\n" , (unsigned long long) STREAM_ARRAY_SIZE, OFFSET);
printf("Memory per array = %.1f MiB (= %.1f GiB).\n",
BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0),
BytesPerWord * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.0/1024.0));
printf("Total memory required = %.1f MiB (= %.1f GiB).\n",
(3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024.),
(3.0 * BytesPerWord) * ( (double) STREAM_ARRAY_SIZE / 1024.0/1024./1024.));
printf("Each kernel will be executed %d times.\n", NTIMES);
printf(" The *best* time for each kernel (excluding the first iteration)\n");
printf(" will be used to compute the reported bandwidth.\n");
#ifdef _OPENMP
printf(HLINE);
#pragma omp parallel
{
#pragma omp master
{
k = omp_get_num_threads();
printf ("Number of Threads requested = %i\n",k);
}
}
#endif
#ifdef _OPENMP
k = 0;
#pragma omp parallel
#pragma omp atomic
k++;
printf ("Number of Threads counted = %i\n",k);
#endif
/* Get initial value for system clock. */
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
a[j] = 1.0;
b[j] = 2.0;
c[j] = 0.0;
}
printf(HLINE);
if ( (quantum = checktick()) >= 1)
printf("Your clock granularity/precision appears to be "
"%d microseconds.\n", quantum);
else {
printf("Your clock granularity appears to be "
"less than one microsecond.\n");
quantum = 1;
}
t = mysecond();
#pragma omp parallel for
for (j = 0; j < STREAM_ARRAY_SIZE; j++)
a[j] = 2.0E0 * a[j];
t = 1.0E6 * (mysecond() - t);
printf("Each test below will take on the order"
" of %d microseconds.\n", (int) t );
printf(" (= %d clock ticks)\n", (int) (t/quantum) );
printf("Increase the size of the arrays if this shows that\n");
printf("you are not getting at least 20 clock ticks per test.\n");
printf(HLINE);
printf("WARNING -- The above is only a rough guideline.\n");
printf("For best results, please be sure you know the\n");
printf("precision of your system timer.\n");
printf(HLINE);
/* --- MAIN LOOP --- repeat test cases NTIMES times --- */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
times[0][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Copy();
#else
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j];
#endif
times[0][k] = mysecond() - times[0][k];
times[1][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Scale(scalar);
#else
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
b[j] = scalar*c[j];
#endif
times[1][k] = mysecond() - times[1][k];
times[2][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Add();
#else
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j]+b[j];
#endif
times[2][k] = mysecond() - times[2][k];
times[3][k] = mysecond();
#ifdef TUNED
tuned_STREAM_Triad(scalar);
#else
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
a[j] = b[j]+scalar*c[j];
#endif
times[3][k] = mysecond() - times[3][k];
}
/* --- SUMMARY --- */
for (k=1; k<NTIMES; k++) /* note -- skip first iteration */
{
for (j=0; j<4; j++)
{
avgtime[j] = avgtime[j] + times[j][k];
mintime[j] = MIN(mintime[j], times[j][k]);
maxtime[j] = MAX(maxtime[j], times[j][k]);
}
}
printf("Function Best Rate MB/s Avg time Min time Max time\n");
for (j=0; j<4; j++) {
avgtime[j] = avgtime[j]/(double)(NTIMES-1);
printf("%s%12.1f %11.6f %11.6f %11.6f\n", label[j],
1.0E-06 * bytes[j]/mintime[j],
avgtime[j],
mintime[j],
maxtime[j]);
}
printf(HLINE);
/* --- Check Results --- */
checkSTREAMresults();
printf(HLINE);
return 0;
}
# define M 20
int
checktick()
{
int i, minDelta, Delta;
double t1, t2, timesfound[M];
/* Collect a sequence of M unique time values from the system. */
for (i = 0; i < M; i++) {
t1 = mysecond();
while( ((t2=mysecond()) - t1) < 1.0E-6 )
;
timesfound[i] = t1 = t2;
}
/*
* Determine the minimum difference between these M values.
* This result will be our estimate (in microseconds) for the
* clock granularity.
*/
minDelta = 1000000;
for (i = 1; i < M; i++) {
Delta = (int)( 1.0E6 * (timesfound[i]-timesfound[i-1]));
minDelta = MIN(minDelta, MAX(Delta,0));
}
return(minDelta);
}
/* A gettimeofday routine to give access to the wall
clock timer on most UNIX-like systems. */
#include <sys/time.h>
double mysecond()
{
struct timeval tp;
struct timezone tzp;
int i;
i = gettimeofday(&tp,&tzp);
return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 );
}
#ifndef abs
#define abs(a) ((a) >= 0 ? (a) : -(a))
#endif
void checkSTREAMresults ()
{
STREAM_TYPE aj,bj,cj,scalar;
STREAM_TYPE aSumErr,bSumErr,cSumErr;
STREAM_TYPE aAvgErr,bAvgErr,cAvgErr;
double epsilon;
ssize_t j;
int k,ierr,err;
/* reproduce initialization */
aj = 1.0;
bj = 2.0;
cj = 0.0;
/* a[] is modified during timing check */
aj = 2.0E0 * aj;
/* now execute timing loop */
scalar = 3.0;
for (k=0; k<NTIMES; k++)
{
cj = aj;
bj = scalar*cj;
cj = aj+bj;
aj = bj+scalar*cj;
}
/* accumulate deltas between observed and expected results */
aSumErr = 0.0;
bSumErr = 0.0;
cSumErr = 0.0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
aSumErr += abs(a[j] - aj);
bSumErr += abs(b[j] - bj);
cSumErr += abs(c[j] - cj);
// if (j == 417) printf("Index 417: c[j]: %f, cj: %f\n",c[j],cj); // MCCALPIN
}
aAvgErr = aSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
bAvgErr = bSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
cAvgErr = cSumErr / (STREAM_TYPE) STREAM_ARRAY_SIZE;
if (sizeof(STREAM_TYPE) == 4) {
epsilon = 1.e-6;
}
else if (sizeof(STREAM_TYPE) == 8) {
epsilon = 1.e-13;
}
else {
printf("WEIRD: sizeof(STREAM_TYPE) = %lu\n",sizeof(STREAM_TYPE));
epsilon = 1.e-6;
}
err = 0;
if (abs(aAvgErr/aj) > epsilon) {
err++;
printf ("Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",aj,aAvgErr,abs(aAvgErr)/aj);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(a[j]/aj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array a: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,aj,a[j],abs((aj-a[j])/aAvgErr));
}
#endif
}
}
printf(" For array a[], %d errors were found.\n",ierr);
}
if (abs(bAvgErr/bj) > epsilon) {
err++;
printf ("Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",bj,bAvgErr,abs(bAvgErr)/bj);
printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(b[j]/bj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array b: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,bj,b[j],abs((bj-b[j])/bAvgErr));
}
#endif
}
}
printf(" For array b[], %d errors were found.\n",ierr);
}
if (abs(cAvgErr/cj) > epsilon) {
err++;
printf ("Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",epsilon);
printf (" Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",cj,cAvgErr,abs(cAvgErr)/cj);
printf (" AvgRelAbsErr > Epsilon (%e)\n",epsilon);
ierr = 0;
for (j=0; j<STREAM_ARRAY_SIZE; j++) {
if (abs(c[j]/cj-1.0) > epsilon) {
ierr++;
#ifdef VERBOSE
if (ierr < 10) {
printf(" array c: index: %ld, expected: %e, observed: %e, relative error: %e\n",
j,cj,c[j],abs((cj-c[j])/cAvgErr));
}
#endif
}
}
printf(" For array c[], %d errors were found.\n",ierr);
}
if (err == 0) {
printf ("Solution Validates: avg error less than %e on all three arrays\n",epsilon);
}
#ifdef VERBOSE
printf ("Results Validation Verbose Results: \n");
printf (" Expected a(1), b(1), c(1): %f %f %f \n",aj,bj,cj);
printf (" Observed a(1), b(1), c(1): %f %f %f \n",a[1],b[1],c[1]);
printf (" Rel Errors on a, b, c: %e %e %e \n",abs(aAvgErr/aj),abs(bAvgErr/bj),abs(cAvgErr/cj));
#endif
}
#ifdef TUNED
/* stubs for "tuned" versions of the kernels */
void tuned_STREAM_Copy()
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j];
}
void tuned_STREAM_Scale(STREAM_TYPE scalar)
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
b[j] = scalar*c[j];
}
void tuned_STREAM_Add()
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
c[j] = a[j]+b[j];
}
void tuned_STREAM_Triad(STREAM_TYPE scalar)
{
ssize_t j;
#pragma omp parallel for
for (j=0; j<STREAM_ARRAY_SIZE; j++)
a[j] = b[j]+scalar*c[j];
}
/* end of stubs for the "tuned" versions of the kernels */
#endif |
convolution_3x3_int8.h | // SenseNets is pleased to support the open source community by supporting ncnn available.
//
// Copyright (C) 2018 SenseNets Technology Ltd. All rights reserved.
// Copyright (C) 2018 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.
#if __ARM_NEON
#include <arm_neon.h>
#endif // __ARM_NEON
static void conv3x3s1_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch)
{
kernel_tm.create(4*9, inch, outch/4 + outch%4, (size_t)1u);
const signed char* kernel = _kernel;
int p=0;
for (; p+3<outch; p+=4)
{
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;
signed char* ktmp = kernel_tm.channel(p/4);
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;
}
k0 += 9;
k1 += 9;
k2 += 9;
k3 += 9;
}
}
for (; p<outch; p++)
{
const signed char* k0 = kernel + (p+0)*inch*9;
signed char* ktmp = kernel_tm.channel(p/4 + p%4);
for (int q=0; q<inch; q++)
{
for (int k=0; k<9; k++)
{
ktmp[k] = k0[k];
}
ktmp += 9;
k0 += 9;
}
}
}
#if __aarch64__
static void conv3x3s1_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 signed char* kernel = _kernel;
int nn_outch = outch >> 1;
int remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p+1);
out0.fill(0);
out1.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
const signed char* kernel1 = (const signed char *)kernel + (p + 1) * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr0n = outptr0 + outw;
int* outptr1n = outptr1 + outw;
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;
const signed char* r3 = img0 + w * 3;
int i = 0;
int8x8_t _k00 = vdup_n_s8(kernel0[0]);
int8x8_t _k01 = vdup_n_s8(kernel0[1]);
int8x8_t _k02 = vdup_n_s8(kernel0[2]);
int8x8_t _k03 = vdup_n_s8(kernel0[3]);
int8x8_t _k04 = vdup_n_s8(kernel0[4]);
int8x8_t _k05 = vdup_n_s8(kernel0[5]);
int8x8_t _k06 = vdup_n_s8(kernel0[6]);
int8x8_t _k07 = vdup_n_s8(kernel0[7]);
int8x8_t _k08 = vdup_n_s8(kernel0[8]);
int8x8_t _k10 = vdup_n_s8(kernel1[0]);
int8x8_t _k11 = vdup_n_s8(kernel1[1]);
int8x8_t _k12 = vdup_n_s8(kernel1[2]);
int8x8_t _k13 = vdup_n_s8(kernel1[3]);
int8x8_t _k14 = vdup_n_s8(kernel1[4]);
int8x8_t _k15 = vdup_n_s8(kernel1[5]);
int8x8_t _k16 = vdup_n_s8(kernel1[6]);
int8x8_t _k17 = vdup_n_s8(kernel1[7]);
int8x8_t _k18 = vdup_n_s8(kernel1[8]);
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn > 0; nn--)
{
// outch 0
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int16x8_t _sum1 = vmull_s8(_r1, _k00);
_sum1 = vmlal_s8(_sum1, _r11, _k01);
_sum1 = vmlal_s8(_sum1, _r12, _k02);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
_sum1 = vmlal_s8(_sum1, _r2, _k03);
_sum1 = vmlal_s8(_sum1, _r21, _k04);
_sum1 = vmlal_s8(_sum1, _r22, _k05);
int8x8_t _r3 = vld1_s8(r3);
int8x8_t _r3n = vld1_s8(r3+8);
int8x8_t _r31 = vext_s8(_r3, _r3n, 1);
int8x8_t _r32 = vext_s8(_r3, _r3n, 2);
_sum1 = vmlal_s8(_sum1, _r3, _k06);
_sum1 = vmlal_s8(_sum1, _r31, _k07);
_sum1 = vmlal_s8(_sum1, _r32, _k08);
int32x4_t sum0_s32 = vld1q_s32(outptr0);
int32x4_t sum0n_s32 = vld1q_s32(outptr0+4);
sum0_s32 = vaddw_s16(sum0_s32, vget_low_s16(_sum0));
sum0n_s32 = vaddw_s16(sum0n_s32, vget_high_s16(_sum0));
vst1q_s32(outptr0, sum0_s32);
vst1q_s32(outptr0+4, sum0n_s32);
int32x4_t sum1_s32 = vld1q_s32(outptr0n);
int32x4_t sum1n_s32 = vld1q_s32(outptr0n+4);
sum1_s32 = vaddw_s16(sum1_s32, vget_low_s16(_sum1));
sum1n_s32 = vaddw_s16(sum1n_s32, vget_high_s16(_sum1));
vst1q_s32(outptr0n, sum1_s32);
vst1q_s32(outptr0n+4, sum1n_s32);
// outch 1
_sum0 = vmull_s8(_r0, _k10);
_sum0 = vmlal_s8(_sum0, _r01, _k11);
_sum0 = vmlal_s8(_sum0, _r02, _k12);
_sum0 = vmlal_s8(_sum0, _r1, _k13);
_sum0 = vmlal_s8(_sum0, _r11, _k14);
_sum0 = vmlal_s8(_sum0, _r12, _k15);
_sum0 = vmlal_s8(_sum0, _r2, _k16);
_sum0 = vmlal_s8(_sum0, _r21, _k17);
_sum0 = vmlal_s8(_sum0, _r22, _k18);
_sum1 = vmull_s8(_r1, _k10);
_sum1 = vmlal_s8(_sum1, _r11, _k11);
_sum1 = vmlal_s8(_sum1, _r12, _k12);
_sum1 = vmlal_s8(_sum1, _r2, _k13);
_sum1 = vmlal_s8(_sum1, _r21, _k14);
_sum1 = vmlal_s8(_sum1, _r22, _k15);
_sum1 = vmlal_s8(_sum1, _r3, _k16);
_sum1 = vmlal_s8(_sum1, _r31, _k17);
_sum1 = vmlal_s8(_sum1, _r32, _k18);
sum0_s32 = vld1q_s32(outptr1);
sum0n_s32 = vld1q_s32(outptr1+4);
sum0_s32 = vaddw_s16(sum0_s32, vget_low_s16(_sum0));
sum0n_s32 = vaddw_s16(sum0n_s32, vget_high_s16(_sum0));
vst1q_s32(outptr1, sum0_s32);
vst1q_s32(outptr1+4, sum0n_s32);
sum1_s32 = vld1q_s32(outptr1n);
sum1n_s32 = vld1q_s32(outptr1n+4);
sum1_s32 = vaddw_s16(sum1_s32, vget_low_s16(_sum1));
sum1n_s32 = vaddw_s16(sum1n_s32, vget_high_s16(_sum1));
vst1q_s32(outptr1n, sum1_s32);
vst1q_s32(outptr1n+4, sum1n_s32);
r0 += 8;
r1 += 8;
r2 += 8;
r3 += 8;
outptr0 += 8;
outptr1 += 8;
outptr0n += 8;
outptr1n += 8;
}
for (; remain>0; remain--)
{
int sum0 = 0;
int sum0n = 0;
int sum1 = 0;
int sum1n = 0;
//ToDo Neon
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
sum1 += (int)r0[0] * kernel1[0];
sum1 += (int)r0[1] * kernel1[1];
sum1 += (int)r0[2] * kernel1[2];
sum1 += (int)r1[0] * kernel1[3];
sum1 += (int)r1[1] * kernel1[4];
sum1 += (int)r1[2] * kernel1[5];
sum1 += (int)r2[0] * kernel1[6];
sum1 += (int)r2[1] * kernel1[7];
sum1 += (int)r2[2] * kernel1[8];
sum0n += (int)r1[0] * kernel0[0];
sum0n += (int)r1[1] * kernel0[1];
sum0n += (int)r1[2] * kernel0[2];
sum0n += (int)r2[0] * kernel0[3];
sum0n += (int)r2[1] * kernel0[4];
sum0n += (int)r2[2] * kernel0[5];
sum0n += (int)r3[0] * kernel0[6];
sum0n += (int)r3[1] * kernel0[7];
sum0n += (int)r3[2] * kernel0[8];
sum1n += (int)r1[0] * kernel1[0];
sum1n += (int)r1[1] * kernel1[1];
sum1n += (int)r1[2] * kernel1[2];
sum1n += (int)r2[0] * kernel1[3];
sum1n += (int)r2[1] * kernel1[4];
sum1n += (int)r2[2] * kernel1[5];
sum1n += (int)r3[0] * kernel1[6];
sum1n += (int)r3[1] * kernel1[7];
sum1n += (int)r3[2] * kernel1[8];
*outptr0 += sum0;
*outptr1 += sum1;
*outptr0n += sum0n;
*outptr1n += sum1n;
r0++;
r1++;
r2++;
r3++;
outptr0++;
outptr1++;
outptr0n++;
outptr1n++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr1 += outw;
outptr0n += outw;
outptr1n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn > 0; nn--)
{
// outch 0
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
int32x4_t sum0_s32 = vld1q_s32(outptr0);
int32x4_t sum0n_s32 = vld1q_s32(outptr0+4);
sum0_s32 = vaddw_s16(sum0_s32, vget_low_s16(_sum0));
sum0n_s32 = vaddw_s16(sum0n_s32, vget_high_s16(_sum0));
vst1q_s32(outptr0, sum0_s32);
vst1q_s32(outptr0+4, sum0n_s32);
// outch 1
_sum0 = vmull_s8(_r0, _k10);
_sum0 = vmlal_s8(_sum0, _r01, _k11);
_sum0 = vmlal_s8(_sum0, _r02, _k12);
_sum0 = vmlal_s8(_sum0, _r1, _k13);
_sum0 = vmlal_s8(_sum0, _r11, _k14);
_sum0 = vmlal_s8(_sum0, _r12, _k15);
_sum0 = vmlal_s8(_sum0, _r2, _k16);
_sum0 = vmlal_s8(_sum0, _r21, _k17);
_sum0 = vmlal_s8(_sum0, _r22, _k18);
sum0_s32 = vld1q_s32(outptr1);
sum0n_s32 = vld1q_s32(outptr1+4);
sum0_s32 = vaddw_s16(sum0_s32, vget_low_s16(_sum0));
sum0n_s32 = vaddw_s16(sum0n_s32, vget_high_s16(_sum0));
vst1q_s32(outptr1, sum0_s32);
vst1q_s32(outptr1+4, sum0n_s32);
r0 += 8;
r1 += 8;
r2 += 8;
outptr0 += 8;
outptr1 += 8;
}
for (; remain>0; remain--)
{
int sum0 = 0;
int sum1 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
sum1 += (int)r0[0] * kernel1[0];
sum1 += (int)r0[1] * kernel1[1];
sum1 += (int)r0[2] * kernel1[2];
sum1 += (int)r1[0] * kernel1[3];
sum1 += (int)r1[1] * kernel1[4];
sum1 += (int)r1[2] * kernel1[5];
sum1 += (int)r2[0] * kernel1[6];
sum1 += (int)r2[1] * kernel1[7];
sum1 += (int)r2[2] * kernel1[8];
*outptr0 += sum0;
*outptr1 += sum1;
r0++;
r1++;
r2++;
outptr0++;
outptr1++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
kernel1 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr0n = outptr0 + outw;
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;
const signed char* r3 = img0 + w * 3;
int i = 0;
int8x8_t _k00 = vdup_n_s8(kernel0[0]);
int8x8_t _k01 = vdup_n_s8(kernel0[1]);
int8x8_t _k02 = vdup_n_s8(kernel0[2]);
int8x8_t _k03 = vdup_n_s8(kernel0[3]);
int8x8_t _k04 = vdup_n_s8(kernel0[4]);
int8x8_t _k05 = vdup_n_s8(kernel0[5]);
int8x8_t _k06 = vdup_n_s8(kernel0[6]);
int8x8_t _k07 = vdup_n_s8(kernel0[7]);
int8x8_t _k08 = vdup_n_s8(kernel0[8]);
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn > 0; nn--)
{
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int16x8_t _sum1 = vmull_s8(_r1, _k00);
_sum1 = vmlal_s8(_sum1, _r11, _k01);
_sum1 = vmlal_s8(_sum1, _r12, _k02);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
_sum1 = vmlal_s8(_sum1, _r2, _k03);
_sum1 = vmlal_s8(_sum1, _r21, _k04);
_sum1 = vmlal_s8(_sum1, _r22, _k05);
int8x8_t _r3 = vld1_s8(r3);
int8x8_t _r3n = vld1_s8(r3+8);
int8x8_t _r31 = vext_s8(_r3, _r3n, 1);
int8x8_t _r32 = vext_s8(_r3, _r3n, 2);
_sum1 = vmlal_s8(_sum1, _r3, _k06);
_sum1 = vmlal_s8(_sum1, _r31, _k07);
_sum1 = vmlal_s8(_sum1, _r32, _k08);
int32x4_t sum0_s32 = vld1q_s32(outptr0);
int32x4_t sum0n_s32 = vld1q_s32(outptr0+4);
sum0_s32 = vaddw_s16(sum0_s32, vget_low_s16(_sum0));
sum0n_s32 = vaddw_s16(sum0n_s32, vget_high_s16(_sum0));
vst1q_s32(outptr0, sum0_s32);
vst1q_s32(outptr0+4, sum0n_s32);
int32x4_t sum1_s32 = vld1q_s32(outptr0n);
int32x4_t sum1n_s32 = vld1q_s32(outptr0n+4);
sum1_s32 = vaddw_s16(sum1_s32, vget_low_s16(_sum1));
sum1n_s32 = vaddw_s16(sum1n_s32, vget_high_s16(_sum1));
vst1q_s32(outptr0n, sum1_s32);
vst1q_s32(outptr0n+4, sum1n_s32);
r0 += 8;
r1 += 8;
r2 += 8;
r3 += 8;
outptr0 += 8;
outptr0n += 8;
}
for (; remain>0; remain--)
{
// Todo neon
int sum0 = 0;
int sum0n = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
sum0n += (int)r1[0] * kernel0[0];
sum0n += (int)r1[1] * kernel0[1];
sum0n += (int)r1[2] * kernel0[2];
sum0n += (int)r2[0] * kernel0[3];
sum0n += (int)r2[1] * kernel0[4];
sum0n += (int)r2[2] * kernel0[5];
sum0n += (int)r3[0] * kernel0[6];
sum0n += (int)r3[1] * kernel0[7];
sum0n += (int)r3[2] * kernel0[8];
*outptr0 += sum0;
*outptr0n += sum0n;
r0++;
r1++;
r2++;
r3++;
outptr0++;
outptr0n++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr0n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
for (; nn > 0; nn--)
{
int8x8_t _r0 = vld1_s8(r0);
int8x8_t _r0n = vld1_s8(r0+8);
int8x8_t _r01 = vext_s8(_r0, _r0n, 1);
int8x8_t _r02 = vext_s8(_r0, _r0n, 2);
int16x8_t _sum0 = vmull_s8(_r0, _k00);
_sum0 = vmlal_s8(_sum0, _r01, _k01);
_sum0 = vmlal_s8(_sum0, _r02, _k02);
int8x8_t _r1 = vld1_s8(r1);
int8x8_t _r1n = vld1_s8(r1+8);
int8x8_t _r11 = vext_s8(_r1, _r1n, 1);
int8x8_t _r12 = vext_s8(_r1, _r1n, 2);
_sum0 = vmlal_s8(_sum0, _r1, _k03);
_sum0 = vmlal_s8(_sum0, _r11, _k04);
_sum0 = vmlal_s8(_sum0, _r12, _k05);
int8x8_t _r2 = vld1_s8(r2);
int8x8_t _r2n = vld1_s8(r2+8);
int8x8_t _r21 = vext_s8(_r2, _r2n, 1);
int8x8_t _r22 = vext_s8(_r2, _r2n, 2);
_sum0 = vmlal_s8(_sum0, _r2, _k06);
_sum0 = vmlal_s8(_sum0, _r21, _k07);
_sum0 = vmlal_s8(_sum0, _r22, _k08);
int32x4_t sum0_s32 = vld1q_s32(outptr0);
int32x4_t sum0n_s32 = vld1q_s32(outptr0+4);
sum0_s32 = vaddw_s16(sum0_s32, vget_low_s16(_sum0));
sum0n_s32 = vaddw_s16(sum0n_s32, vget_high_s16(_sum0));
vst1q_s32(outptr0, sum0_s32);
vst1q_s32(outptr0+4, sum0n_s32);
r0 += 8;
r1 += 8;
r2 += 8;
outptr0 += 8;
}
for (; remain>0; remain--)
{
int sum0 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
*outptr0 += sum0;
r0++;
r1++;
r2++;
outptr0++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
}
}
}
static void conv3x3s2_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2 * outw + w;
const signed char* kernel = _kernel;
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 4;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p + 1);
Mat out2 = top_blob.channel(p + 2);
Mat out3 = top_blob.channel(p + 3);
out0.fill(0.f);
out1.fill(0.f);
out2.fill(0.f);
out3.fill(0.f);
const signed char* kernel0 = (const signed char*)kernel + p * inch * 9;
const signed char* kernel1 = (const signed char*)kernel + (p + 1) * inch * 9;
const signed char* kernel2 = (const signed char*)kernel + (p + 2) * inch * 9;
const signed char* kernel3 = (const signed char*)kernel + (p + 3) * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr2 = out2;
int* outptr3 = out3;
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;
int8x16_t _k0 = vld1q_s8(kernel0);
int8x16_t _k1 = vld1q_s8(kernel1);
int8x16_t _k2 = vld1q_s8(kernel2);
int8x16_t _k3 = vld1q_s8(kernel3);
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
if (nn > 0)
{
asm volatile(
"0: \n"
// r0
"prfm pldl1keep, [%5, #128] \n"
"ld2 {v4.8b, v5.8b}, [%5], #16 \n"
"ld2 {v6.8b, v7.8b}, [%5] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[0] \n"
"dup v10.8b, %17.b[0] \n"
"dup v11.8b, %18.b[0] \n"
"dup v12.8b, %19.b[0] \n"
"smull v13.8h, v4.8b, v9.8b \n"
"smull v14.8h, v4.8b, v10.8b \n"
"smull v15.8h, v4.8b, v11.8b \n"
"smull v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[1] \n"
"dup v10.8b, %17.b[1] \n"
"dup v11.8b, %18.b[1] \n"
"dup v12.8b, %19.b[1] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[2] \n"
"dup v10.8b, %17.b[2] \n"
"dup v11.8b, %18.b[2] \n"
"dup v12.8b, %19.b[2] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// r1
"prfm pldl1keep, [%6, #128] \n"
"ld2 {v4.8b, v5.8b}, [%6], #16 \n"
"ld2 {v6.8b, v7.8b}, [%6] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[3] \n"
"dup v10.8b, %17.b[3] \n"
"dup v11.8b, %18.b[3] \n"
"dup v12.8b, %19.b[3] \n"
"smlal v13.8h, v4.8b, v9.8b \n"
"smlal v14.8h, v4.8b, v10.8b \n"
"smlal v15.8h, v4.8b, v11.8b \n"
"smlal v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[4] \n"
"dup v10.8b, %17.b[4] \n"
"dup v11.8b, %18.b[4] \n"
"dup v12.8b, %19.b[4] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[5] \n"
"dup v10.8b, %17.b[5] \n"
"dup v11.8b, %18.b[5] \n"
"dup v12.8b, %19.b[5] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// r2
"prfm pldl1keep, [%7, #128] \n"
"ld2 {v4.8b, v5.8b}, [%7], #16 \n"
"ld2 {v6.8b, v7.8b}, [%7] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[6] \n"
"dup v10.8b, %17.b[6] \n"
"dup v11.8b, %18.b[6] \n"
"dup v12.8b, %19.b[6] \n"
"smlal v13.8h, v4.8b, v9.8b \n"
"smlal v14.8h, v4.8b, v10.8b \n"
"smlal v15.8h, v4.8b, v11.8b \n"
"smlal v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[7] \n"
"dup v10.8b, %17.b[7] \n"
"dup v11.8b, %18.b[7] \n"
"dup v12.8b, %19.b[7] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[8] \n"
"dup v10.8b, %17.b[8] \n"
"dup v11.8b, %18.b[8] \n"
"dup v12.8b, %19.b[8] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// sum0 - sum3
"prfm pldl1keep, [%1, #128] \n"
"prfm pldl1keep, [%2, #128] \n"
"prfm pldl1keep, [%3, #128] \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v17.4s, v18.4s}, [%1] \n"
"ld1 {v19.4s, v20.4s}, [%2] \n"
"ld1 {v21.4s, v22.4s}, [%3] \n"
"ld1 {v23.4s, v24.4s}, [%4] \n"
"saddw v17.4s, v17.4s, v13.4h \n"
"saddw2 v18.4s, v18.4s, v13.8h \n"
"saddw v19.4s, v19.4s, v14.4h \n"
"saddw2 v20.4s, v20.4s, v14.8h \n"
"saddw v21.4s, v21.4s, v15.4h \n"
"saddw2 v22.4s, v22.4s, v15.8h \n"
"saddw v23.4s, v23.4s, v16.4h \n"
"saddw2 v24.4s, v24.4s, v16.8h \n"
"st1 {v17.4s, v18.4s}, [%1], #32\n"
"st1 {v19.4s, v20.4s}, [%2], #32\n"
"st1 {v21.4s, v22.4s}, [%3], #32\n"
"st1 {v23.4s, v24.4s}, [%4], #32\n"
"subs %w0, %w0, #1 \n"
"bne 0b \n"
: "=r"(nn), //%0
"=r"(outptr0), //%1
"=r"(outptr1), //%2
"=r"(outptr2), //%3
"=r"(outptr3), //%4
"=r"(r0), //%5
"=r"(r1), //%6
"=r"(r2) //%7
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"6"(r1),
"7"(r2),
"w"(_k0), //%16
"w"(_k1), //%17
"w"(_k2), //%18
"w"(_k3) //%19
: "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24"
);
}
if (remain >= 4)
{
remain -= 4;
asm volatile(
// r0
"prfm pldl1keep, [%5, #128] \n"
"ld2 {v4.8b, v5.8b}, [%5], #16 \n"
"ld2 {v6.8b, v7.8b}, [%5] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[0] \n"
"dup v10.8b, %17.b[0] \n"
"dup v11.8b, %18.b[0] \n"
"dup v12.8b, %19.b[0] \n"
"smull v13.8h, v4.8b, v9.8b \n"
"smull v14.8h, v4.8b, v10.8b \n"
"smull v15.8h, v4.8b, v11.8b \n"
"smull v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[1] \n"
"dup v10.8b, %17.b[1] \n"
"dup v11.8b, %18.b[1] \n"
"dup v12.8b, %19.b[1] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[2] \n"
"dup v10.8b, %17.b[2] \n"
"dup v11.8b, %18.b[2] \n"
"dup v12.8b, %19.b[2] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// r1
"prfm pldl1keep, [%6, #128] \n"
"ld2 {v4.8b, v5.8b}, [%6], #16 \n"
"ld2 {v6.8b, v7.8b}, [%6] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[3] \n"
"dup v10.8b, %17.b[3] \n"
"dup v11.8b, %18.b[3] \n"
"dup v12.8b, %19.b[3] \n"
"smlal v13.8h, v4.8b, v9.8b \n"
"smlal v14.8h, v4.8b, v10.8b \n"
"smlal v15.8h, v4.8b, v11.8b \n"
"smlal v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[4] \n"
"dup v10.8b, %17.b[4] \n"
"dup v11.8b, %18.b[4] \n"
"dup v12.8b, %19.b[4] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[5] \n"
"dup v10.8b, %17.b[5] \n"
"dup v11.8b, %18.b[5] \n"
"dup v12.8b, %19.b[5] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// r2
"prfm pldl1keep, [%7, #128] \n"
"ld2 {v4.8b, v5.8b}, [%7], #16 \n"
"ld2 {v6.8b, v7.8b}, [%7] \n"
"ext v8.8b, v4.8b, v6.8b, #1 \n"
"dup v9.8b, %16.b[6] \n"
"dup v10.8b, %17.b[6] \n"
"dup v11.8b, %18.b[6] \n"
"dup v12.8b, %19.b[6] \n"
"smlal v13.8h, v4.8b, v9.8b \n"
"smlal v14.8h, v4.8b, v10.8b \n"
"smlal v15.8h, v4.8b, v11.8b \n"
"smlal v16.8h, v4.8b, v12.8b \n"
"dup v9.8b, %16.b[7] \n"
"dup v10.8b, %17.b[7] \n"
"dup v11.8b, %18.b[7] \n"
"dup v12.8b, %19.b[7] \n"
"smlal v13.8h, v5.8b, v9.8b \n"
"smlal v14.8h, v5.8b, v10.8b \n"
"smlal v15.8h, v5.8b, v11.8b \n"
"smlal v16.8h, v5.8b, v12.8b \n"
"dup v9.8b, %16.b[8] \n"
"dup v10.8b, %17.b[8] \n"
"dup v11.8b, %18.b[8] \n"
"dup v12.8b, %19.b[8] \n"
"smlal v13.8h, v8.8b, v9.8b \n"
"smlal v14.8h, v8.8b, v10.8b \n"
"smlal v15.8h, v8.8b, v11.8b \n"
"smlal v16.8h, v8.8b, v12.8b \n"
// sum0 - sum3
"prfm pldl1keep, [%1, #128] \n"
"prfm pldl1keep, [%2, #128] \n"
"prfm pldl1keep, [%3, #128] \n"
"prfm pldl1keep, [%4, #128] \n"
"ld1 {v17.4s}, [%1] \n"
"ld1 {v19.4s}, [%2] \n"
"ld1 {v21.4s}, [%3] \n"
"ld1 {v23.4s}, [%4] \n"
"saddw v17.4s, v17.4s, v13.4h \n"
"saddw v19.4s, v19.4s, v14.4h \n"
"saddw v21.4s, v21.4s, v15.4h \n"
"saddw v23.4s, v23.4s, v16.4h \n"
"st1 {v17.4s}, [%1], #16 \n"
"st1 {v19.4s}, [%2], #16 \n"
"st1 {v21.4s}, [%3], #16 \n"
"st1 {v23.4s}, [%4], #16 \n"
"sub %5, %5, #8 \n"
"sub %6, %6, #8 \n"
"sub %7, %7, #8 \n"
: "=r"(nn), //%0
"=r"(outptr0), //%1
"=r"(outptr1), //%2
"=r"(outptr2), //%3
"=r"(outptr3), //%4
"=r"(r0), //%5
"=r"(r1), //%6
"=r"(r2) //%7
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"6"(r1),
"7"(r2),
"w"(_k0), //%16
"w"(_k1), //%17
"w"(_k2), //%18
"w"(_k3) //%19
: "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24"
);
}
for (; remain>0; remain--)
{
int sum0 = 0;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
sum1 += (int)r0[0] * kernel1[0];
sum1 += (int)r0[1] * kernel1[1];
sum1 += (int)r0[2] * kernel1[2];
sum1 += (int)r1[0] * kernel1[3];
sum1 += (int)r1[1] * kernel1[4];
sum1 += (int)r1[2] * kernel1[5];
sum1 += (int)r2[0] * kernel1[6];
sum1 += (int)r2[1] * kernel1[7];
sum1 += (int)r2[2] * kernel1[8];
sum2 += (int)r0[0] * kernel2[0];
sum2 += (int)r0[1] * kernel2[1];
sum2 += (int)r0[2] * kernel2[2];
sum2 += (int)r1[0] * kernel2[3];
sum2 += (int)r1[1] * kernel2[4];
sum2 += (int)r1[2] * kernel2[5];
sum2 += (int)r2[0] * kernel2[6];
sum2 += (int)r2[1] * kernel2[7];
sum2 += (int)r2[2] * kernel2[8];
sum3 += (int)r0[0] * kernel3[0];
sum3 += (int)r0[1] * kernel3[1];
sum3 += (int)r0[2] * kernel3[2];
sum3 += (int)r1[0] * kernel3[3];
sum3 += (int)r1[1] * kernel3[4];
sum3 += (int)r1[2] * kernel3[5];
sum3 += (int)r2[0] * kernel3[6];
sum3 += (int)r2[1] * kernel3[7];
sum3 += (int)r2[2] * kernel3[8];
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
r0 += 2;
r1 += 2;
r2 += 2;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
kernel0 += 9;
kernel1 += 9;
kernel2 += 9;
kernel3 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0.f);
const signed char* kernel0 = (const signed char*)kernel + p * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
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;
int8x8_t _k0 = vdup_n_s8(kernel[0]);
int8x8_t _k1 = vdup_n_s8(kernel[1]);
int8x8_t _k2 = vdup_n_s8(kernel[2]);
int8x8_t _k3 = vdup_n_s8(kernel[3]);
int8x8_t _k4 = vdup_n_s8(kernel[4]);
int8x8_t _k5 = vdup_n_s8(kernel[5]);
int8x8_t _k6 = vdup_n_s8(kernel[6]);
int8x8_t _k7 = vdup_n_s8(kernel[7]);
int8x8_t _k8 = vdup_n_s8(kernel[8]);
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
remain = outw;
for (; nn >0; nn--)
{
int8x8x2_t _r0 = vld2_s8(r0);
int8x8x2_t _r0n = vld2_s8(r0+16);
int8x8_t _r00 = _r0.val[0];
int8x8_t _r01 = _r0.val[1];
int8x8_t _r02 = vext_s8(_r00, _r0n.val[0], 1);
int16x8_t _sum = vmull_s8(_r00, _k0);
_sum = vmlal_s8(_sum, _r01, _k1);
_sum = vmlal_s8(_sum, _r02, _k2);
int8x8x2_t _r1 = vld2_s8(r1);
int8x8x2_t _r1n = vld2_s8(r1+16);
int8x8_t _r10 = _r1.val[0];
int8x8_t _r11 = _r1.val[1];
int8x8_t _r12 = vext_s8(_r10, _r1n.val[0], 1);
_sum = vmlal_s8(_sum, _r10, _k3);
_sum = vmlal_s8(_sum, _r11, _k4);
_sum = vmlal_s8(_sum, _r12, _k5);
int8x8x2_t _r2 = vld2_s8(r2);
int8x8x2_t _r2n = vld2_s8(r2+16);
int8x8_t _r20 = _r2.val[0];
int8x8_t _r21 = _r2.val[1];
int8x8_t _r22 = vext_s8(_r20, _r2n.val[0], 1);
_sum = vmlal_s8(_sum, _r20, _k6);
_sum = vmlal_s8(_sum, _r21, _k7);
_sum = vmlal_s8(_sum, _r22, _k8);
int32x4_t sum0_s32 = vld1q_s32(outptr0);
int32x4_t sum0n_s32 = vld1q_s32(outptr0+4);
sum0_s32 = vaddw_s16(sum0_s32, vget_low_s16(_sum));
sum0n_s32 = vaddw_s16(sum0n_s32, vget_high_s16(_sum));
vst1q_s32(outptr0, sum0_s32);
vst1q_s32(outptr0+4, sum0n_s32);
r0 += 16;
r1 += 16;
r2 += 16;
outptr0 += 8;
}
if (remain >= 4)
{
remain -= 4;
int8x8x2_t _r0 = vld2_s8(r0);
int8x8x2_t _r0n = vld2_s8(r0+16);
int8x8_t _r00 = _r0.val[0];
int8x8_t _r01 = _r0.val[1];
int8x8_t _r02 = vext_s8(_r00, _r0n.val[0], 1);
int16x8_t _sum = vmull_s8(_r00, _k0);
_sum = vmlal_s8(_sum, _r01, _k1);
_sum = vmlal_s8(_sum, _r02, _k2);
int8x8x2_t _r1 = vld2_s8(r1);
int8x8x2_t _r1n = vld2_s8(r1+16);
int8x8_t _r10 = _r1.val[0];
int8x8_t _r11 = _r1.val[1];
int8x8_t _r12 = vext_s8(_r10, _r1n.val[0], 1);
_sum = vmlal_s8(_sum, _r10, _k3);
_sum = vmlal_s8(_sum, _r11, _k4);
_sum = vmlal_s8(_sum, _r12, _k5);
int8x8x2_t _r2 = vld2_s8(r2);
int8x8x2_t _r2n = vld2_s8(r2+16);
int8x8_t _r20 = _r2.val[0];
int8x8_t _r21 = _r2.val[1];
int8x8_t _r22 = vext_s8(_r20, _r2n.val[0], 1);
_sum = vmlal_s8(_sum, _r20, _k6);
_sum = vmlal_s8(_sum, _r21, _k7);
_sum = vmlal_s8(_sum, _r22, _k8);
int32x4_t sum0_s32 = vld1q_s32(outptr0);
sum0_s32 = vaddw_s16(sum0_s32, vget_low_s16(_sum));
vst1q_s32(outptr0, sum0_s32);
r0 += 8;
r1 += 8;
r2 += 8;
outptr0 += 4;
}
for (; remain>0; remain--)
{
int sum0 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
*outptr0 += sum0;
r0 += 2;
r1 += 2;
r2 += 2;
outptr0++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
kernel0 += 9;
}
}
}
#else // __aarch64__
static void conv3x3s1_neon_s8(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, 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 signed char* kernel = _kernel;
int nn_outch = outch >> 1;
int remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p+1);
out0.fill(0);
out1.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
const signed char* kernel1 = (const signed char *)kernel + (p + 1) * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr0n = outptr0 + outw;
int* outptr1n = outptr1 + outw;
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;
const signed char* r3 = img0 + w * 3;
const signed char* k00 = kernel0;
const signed char* k03 = kernel0 + 3;
const signed char* k06 = kernel0 + 6;
const signed char* k10 = kernel1;
const signed char* k13 = kernel1 + 3;
const signed char* k16 = kernel1 + 6;
int i = 0;
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
if (nn > 0)
{
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
"vld1.8 {d28-d29}, [%1] \n"
: "=r"(kernel0), // %0
"=r"(kernel1) // %1
: "0"(kernel0),
"1"(kernel1)
: "cc", "memory"
);
asm volatile(
"0: \n"
"pld [%5, #128] \n"
"vld1.32 {d0-d1}, [%5] \n"// r0
"add %5, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%6, #128] \n"
"vld1.32 {d6-d7}, [%6] \n"// r1
"add %6, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%7, #128] \n"
"vld1.32 {d10-d11}, [%7] \n"// r2
"add %7, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%8, #128] \n"
"vld1.32 {d14-d15}, [%8] \n"// r3
"add %8, #8 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d30 \n"// k1n
"vmlal.s8 q2, d3, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d30 \n"// k4n
"vmlal.s8 q2, d9, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d30 \n"// k7n
"vmlal.s8 q2, d13, d31 \n"// k8n
"pld [%3, #128] \n"
"vld1.32 {d18-d21}, [%3] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%3]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0n
"vmlal.s8 q2, d8, d30 \n"// k1n
"vmlal.s8 q2, d9, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3n
"vmlal.s8 q2, d12, d30 \n"// k4n
"vmlal.s8 q2, d13, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6n
"vmlal.s8 q2, d16, d30 \n"// k7n
"vmlal.s8 q2, d17, d31 \n"// k8n
"pld [%4, #128] \n"
"vld1.32 {d18-d21}, [%4] \n"// sum1n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%4]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(outptr1), // %3
"=r"(outptr1n), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3) // %8
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(outptr1),
"4"(outptr1n),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q15"
);
}
for (; remain>0; remain--)
{
int sum0 = 0;
int sum0n = 0;
int sum1 = 0;
int sum1n = 0;
//ToDo Neon
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
sum1 += (int)r0[0] * kernel1[0];
sum1 += (int)r0[1] * kernel1[1];
sum1 += (int)r0[2] * kernel1[2];
sum1 += (int)r1[0] * kernel1[3];
sum1 += (int)r1[1] * kernel1[4];
sum1 += (int)r1[2] * kernel1[5];
sum1 += (int)r2[0] * kernel1[6];
sum1 += (int)r2[1] * kernel1[7];
sum1 += (int)r2[2] * kernel1[8];
sum0n += (int)r1[0] * kernel0[0];
sum0n += (int)r1[1] * kernel0[1];
sum0n += (int)r1[2] * kernel0[2];
sum0n += (int)r2[0] * kernel0[3];
sum0n += (int)r2[1] * kernel0[4];
sum0n += (int)r2[2] * kernel0[5];
sum0n += (int)r3[0] * kernel0[6];
sum0n += (int)r3[1] * kernel0[7];
sum0n += (int)r3[2] * kernel0[8];
sum1n += (int)r1[0] * kernel1[0];
sum1n += (int)r1[1] * kernel1[1];
sum1n += (int)r1[2] * kernel1[2];
sum1n += (int)r2[0] * kernel1[3];
sum1n += (int)r2[1] * kernel1[4];
sum1n += (int)r2[2] * kernel1[5];
sum1n += (int)r3[0] * kernel1[6];
sum1n += (int)r3[1] * kernel1[7];
sum1n += (int)r3[2] * kernel1[8];
*outptr0 += sum0;
*outptr1 += sum1;
*outptr0n += sum0n;
*outptr1n += sum1n;
r0++;
r1++;
r2++;
r3++;
outptr0++;
outptr1++;
outptr0n++;
outptr1n++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr1 += outw;
outptr0n += outw;
outptr1n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
if (nn > 0)
{
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
"vld1.8 {d28-d29}, [%1] \n"
: "=r"(kernel0), // %0
"=r"(kernel1) // %1
: "0"(kernel0),
"1"(kernel1)
: "cc", "memory"
);
asm volatile(
"0: \n"
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d7, d28[1] \n"
"vdup.s8 d11, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d7 \n"// k1n
"vmlal.s8 q2, d3, d11 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d7, d28[4] \n"
"vdup.s8 d11, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d7 \n"// k4n
"vmlal.s8 q2, d9, d11 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d7, d28[7] \n"
"vdup.s8 d11, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d7 \n"// k7n
"vmlal.s8 q2, d13, d11 \n"// k8n
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
for (; remain>0; remain--)
{
int sum0 = 0;
int sum1 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
sum1 += (int)r0[0] * kernel1[0];
sum1 += (int)r0[1] * kernel1[1];
sum1 += (int)r0[2] * kernel1[2];
sum1 += (int)r1[0] * kernel1[3];
sum1 += (int)r1[1] * kernel1[4];
sum1 += (int)r1[2] * kernel1[5];
sum1 += (int)r2[0] * kernel1[6];
sum1 += (int)r2[1] * kernel1[7];
sum1 += (int)r2[2] * kernel1[8];
*outptr0 += sum0;
*outptr1 += sum1;
r0++;
r1++;
r2++;
outptr0++;
outptr1++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
kernel1 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr0n = outptr0 + outw;
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;
const signed char* r3 = img0 + w * 3;
const signed char* k00 = kernel0;
const signed char* k03 = kernel0 + 3;
const signed char* k06 = kernel0 + 6;
int i = 0;
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
if (nn > 0)
{
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
: "=r"(kernel0) // %0
: "0"(kernel0)
: "cc", "memory"
);
asm volatile(
"0: \n"
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%6, #128] \n"
"vld1.32 {d14-d15}, [%6] \n"// r3
"add %6, #8 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
for (; remain>0; remain--)
{
//Todo Neon
int sum0 = 0;
int sum0n = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
sum0n += (int)r1[0] * kernel0[0];
sum0n += (int)r1[1] * kernel0[1];
sum0n += (int)r1[2] * kernel0[2];
sum0n += (int)r2[0] * kernel0[3];
sum0n += (int)r2[1] * kernel0[4];
sum0n += (int)r2[2] * kernel0[5];
sum0n += (int)r3[0] * kernel0[6];
sum0n += (int)r3[1] * kernel0[7];
sum0n += (int)r3[2] * kernel0[8];
*outptr0 += sum0;
*outptr0n += sum0n;
r0++;
r1++;
r2++;
r3++;
outptr0++;
outptr0n++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr0n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
if (nn > 0)
{
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
: "=r"(kernel0) // %0
: "0"(kernel0)
: "cc", "memory"
);
asm volatile(
"0: \n"
"pld [%2, #128] \n"
"vld1.32 {d0-d1}, [%2] \n"// r0
"add %2, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%3, #128] \n"
"vld1.32 {d6-d7}, [%3] \n"// r1
"add %3, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%4, #128] \n"
"vld1.32 {d10-d11}, [%4] \n"// r2
"add %4, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
for (; remain>0; remain--)
{
int sum0 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
*outptr0 += sum0;
r0++;
r1++;
r2++;
outptr0++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
}
}
}
static void conv3x3s1_neon_s8_left4(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, 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* kernel = _kernel;
int nn_outch = outch >> 1;
int remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p+1);
out0.fill(0);
out1.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
const signed char* kernel1 = (const signed char *)kernel + (p + 1) * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr0n = outptr0 + outw;
int* outptr1n = outptr1 + outw;
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;
const signed char* r3 = img0 + w*3;
const signed char* k00 = kernel0;
const signed char* k03 = kernel0 + 3;
const signed char* k06 = kernel0 + 6;
const signed char* k10 = kernel1;
const signed char* k13 = kernel1 + 3;
const signed char* k16 = kernel1 + 6;
int i = 0;
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.8 {d26-d27}, [%0] \n" // k00 k01 k02 k03 k04 k05 k06 k07 k08
"vld1.8 {d28-d29}, [%1] \n" // k10 k11 k12 k13 k14 k15 k16 k17 k18
: "=r"(kernel0), // %0
"=r"(kernel1) // %1
: "0"(kernel0),
"1"(kernel1)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%5, #128] \n"
"vld1.32 {d0-d1}, [%5] \n"// r0
"add %5, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%6, #128] \n"
"vld1.32 {d6-d7}, [%6] \n"// r1
"add %6, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%7, #128] \n"
"vld1.32 {d10-d11}, [%7] \n"// r2
"add %7, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%8, #128] \n"
"vld1.32 {d14-d15}, [%8] \n"// r3
"add %8, #8 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d30 \n"// k1n
"vmlal.s8 q2, d3, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d30 \n"// k4n
"vmlal.s8 q2, d9, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d30 \n"// k7n
"vmlal.s8 q2, d13, d31 \n"// k8n
"pld [%3, #128] \n"
"vld1.32 {d18-d21}, [%3] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%3]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0n
"vmlal.s8 q2, d8, d30 \n"// k1n
"vmlal.s8 q2, d9, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3n
"vmlal.s8 q2, d12, d30 \n"// k4n
"vmlal.s8 q2, d13, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6n
"vmlal.s8 q2, d16, d30 \n"// k7n
"vmlal.s8 q2, d17, d31 \n"// k8n
"pld [%4, #128] \n"
"vld1.32 {d18-d21}, [%4] \n"// sum1n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%4]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(outptr1), // %3
"=r"(outptr1n), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3) // %8
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(outptr1),
"4"(outptr1n),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q15"
);
}
asm volatile(
"pld [%5, #128] \n"
"vld1.32 {d0-d1}, [%5] \n"// r0
"add %5, #4 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%6, #128] \n"
"vld1.32 {d6-d7}, [%6] \n"// r1
"add %6, #4 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%7, #128] \n"
"vld1.32 {d10-d11}, [%7] \n"// r2
"add %7, #4 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%8, #128] \n"
"vld1.32 {d14-d15}, [%8] \n"// r3
"add %8, #4 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d19}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d19}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%2]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d30 \n"// k1n
"vmlal.s8 q2, d3, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d30 \n"// k4n
"vmlal.s8 q2, d9, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d30 \n"// k7n
"vmlal.s8 q2, d13, d31 \n"// k8n
"pld [%3, #128] \n"
"vld1.32 {d18-d19}, [%3] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%3]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0n
"vmlal.s8 q2, d8, d30 \n"// k1n
"vmlal.s8 q2, d9, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3n
"vmlal.s8 q2, d12, d30 \n"// k4n
"vmlal.s8 q2, d13, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6n
"vmlal.s8 q2, d16, d30 \n"// k7n
"vmlal.s8 q2, d17, d31 \n"// k8n
"pld [%4, #128] \n"
"vld1.32 {d18-d19}, [%4] \n"// sum1n
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%4]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(outptr1), // %3
"=r"(outptr1n), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3) // %8
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(outptr1),
"4"(outptr1n),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q15"
);
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr1 += outw;
outptr0n += outw;
outptr1n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
"vld1.8 {d28-d29}, [%1] \n"
: "=r"(kernel0), // %0
"=r"(kernel1) // %1
: "0"(kernel0),
"1"(kernel1)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d7, d28[1] \n"
"vdup.s8 d11, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d7 \n"// k1n
"vmlal.s8 q2, d3, d11 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d7, d28[4] \n"
"vdup.s8 d11, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d7 \n"// k4n
"vmlal.s8 q2, d9, d11 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d7, d28[7] \n"
"vdup.s8 d11, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d7 \n"// k7n
"vmlal.s8 q2, d13, d11 \n"// k8n
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
asm volatile(
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #4 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #4 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #4 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d19}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%1]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d7, d28[1] \n"
"vdup.s8 d11, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d7 \n"// k1n
"vmlal.s8 q2, d3, d11 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d7, d28[4] \n"
"vdup.s8 d11, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d7 \n"// k4n
"vmlal.s8 q2, d9, d11 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d7, d28[7] \n"
"vdup.s8 d11, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d7 \n"// k7n
"vmlal.s8 q2, d13, d11 \n"// k8n
"pld [%2, #128] \n"
"vld1.32 {d18-d19}, [%2] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%2]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
kernel1 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr0n = outptr0 + outw;
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;
const signed char* r3 = img0 + w*3;
const signed char* k00 = kernel0;
const signed char* k03 = kernel0 + 3;
const signed char* k06 = kernel0 + 6;
int i = 0;
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
: "=r"(kernel0) // %0
: "0"(kernel0)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%6, #128] \n"
"vld1.32 {d14-d15}, [%6] \n"// r3
"add %6, #8 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
asm volatile(
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #4 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #4 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #4 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%6, #128] \n"
"vld1.32 {d14-d15}, [%6] \n"// r3
"add %6, #4 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d19}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d19}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%2]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr0n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
: "=r"(kernel0) // %0
: "0"(kernel0)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%2, #128] \n"
"vld1.32 {d0-d1}, [%2] \n"// r0
"add %2, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%3, #128] \n"
"vld1.32 {d6-d7}, [%3] \n"// r1
"add %3, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%4, #128] \n"
"vld1.32 {d10-d11}, [%4] \n"// r2
"add %4, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
asm volatile(
"pld [%2, #128] \n"
"vld1.32 {d0-d1}, [%2] \n"// r0
"add %2, #4 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%3, #128] \n"
"vld1.32 {d6-d7}, [%3] \n"// r1
"add %3, #4 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%4, #128] \n"
"vld1.32 {d10-d11}, [%4] \n"// r2
"add %4, #4 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d19}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vst1.32 {d18-d19}, [%1]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
}
}
}
static void conv3x3s1_neon_s8_left6(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, 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* kernel = _kernel;
int nn_outch = outch >> 1;
int remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p+1);
out0.fill(0);
out1.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
const signed char* kernel1 = (const signed char *)kernel + (p + 1) * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr0n = outptr0 + outw;
int* outptr1n = outptr1 + outw;
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;
const signed char* r3 = img0 + w*3;
const signed char* k00 = kernel0;
const signed char* k03 = kernel0 + 3;
const signed char* k06 = kernel0 + 6;
const signed char* k10 = kernel1;
const signed char* k13 = kernel1 + 3;
const signed char* k16 = kernel1 + 6;
int i = 0;
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.8 {d26-d27}, [%0] \n" // k00 k01 k02 k03 k04 k05 k06 k07 k08
"vld1.8 {d28-d29}, [%1] \n" // k10 k11 k12 k13 k14 k15 k16 k17 k18
: "=r"(kernel0), // %0
"=r"(kernel1) // %1
: "0"(kernel0),
"1"(kernel1)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%5, #128] \n"
"vld1.32 {d0-d1}, [%5] \n"// r0
"add %5, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%6, #128] \n"
"vld1.32 {d6-d7}, [%6] \n"// r1
"add %6, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%7, #128] \n"
"vld1.32 {d10-d11}, [%7] \n"// r2
"add %7, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%8, #128] \n"
"vld1.32 {d14-d15}, [%8] \n"// r3
"add %8, #8 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d30 \n"// k1n
"vmlal.s8 q2, d3, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d30 \n"// k4n
"vmlal.s8 q2, d9, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d30 \n"// k7n
"vmlal.s8 q2, d13, d31 \n"// k8n
"pld [%3, #128] \n"
"vld1.32 {d18-d21}, [%3] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%3]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0n
"vmlal.s8 q2, d8, d30 \n"// k1n
"vmlal.s8 q2, d9, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3n
"vmlal.s8 q2, d12, d30 \n"// k4n
"vmlal.s8 q2, d13, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6n
"vmlal.s8 q2, d16, d30 \n"// k7n
"vmlal.s8 q2, d17, d31 \n"// k8n
"pld [%4, #128] \n"
"vld1.32 {d18-d21}, [%4] \n"// sum1n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%4]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(outptr1), // %3
"=r"(outptr1n), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3) // %8
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(outptr1),
"4"(outptr1n),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q15"
);
}
asm volatile(
"pld [%5, #128] \n"
"vld1.32 {d0-d1}, [%5] \n"// r0
"add %5, #6 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%6, #128] \n"
"vld1.32 {d6-d7}, [%6] \n"// r1
"add %6, #6 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%7, #128] \n"
"vld1.32 {d10-d11}, [%7] \n"// r2
"add %7, #6 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%8, #128] \n"
"vld1.32 {d14-d15}, [%8] \n"// r3
"add %8, #6 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d20}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d20}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%2]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d30 \n"// k1n
"vmlal.s8 q2, d3, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d30 \n"// k4n
"vmlal.s8 q2, d9, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d30 \n"// k7n
"vmlal.s8 q2, d13, d31 \n"// k8n
"pld [%3, #128] \n"
"vld1.32 {d18-d20}, [%3] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%3]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d30, d28[1] \n"
"vdup.s8 d31, d28[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0n
"vmlal.s8 q2, d8, d30 \n"// k1n
"vmlal.s8 q2, d9, d31 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d30, d28[4] \n"
"vdup.s8 d31, d28[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3n
"vmlal.s8 q2, d12, d30 \n"// k4n
"vmlal.s8 q2, d13, d31 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d30, d28[7] \n"
"vdup.s8 d31, d29[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6n
"vmlal.s8 q2, d16, d30 \n"// k7n
"vmlal.s8 q2, d17, d31 \n"// k8n
"pld [%4, #128] \n"
"vld1.32 {d18-d20}, [%4] \n"// sum1n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%4]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(outptr1), // %3
"=r"(outptr1n), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3) // %8
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(outptr1),
"4"(outptr1n),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q15"
);
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr1 += outw;
outptr0n += outw;
outptr1n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
"vld1.8 {d28-d29}, [%1] \n"
: "=r"(kernel0), // %0
"=r"(kernel1) // %1
: "0"(kernel0),
"1"(kernel1)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d7, d28[1] \n"
"vdup.s8 d11, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d7 \n"// k1n
"vmlal.s8 q2, d3, d11 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d7, d28[4] \n"
"vdup.s8 d11, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d7 \n"// k4n
"vmlal.s8 q2, d9, d11 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d7, d28[7] \n"
"vdup.s8 d11, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d7 \n"// k7n
"vmlal.s8 q2, d13, d11 \n"// k8n
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
asm volatile(
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #6 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #6 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #6 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d20}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%1]! \n"
"vdup.s8 d1, d28[0] \n"
"vdup.s8 d7, d28[1] \n"
"vdup.s8 d11, d28[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0n
"vmlal.s8 q2, d2, d7 \n"// k1n
"vmlal.s8 q2, d3, d11 \n"// k2n
"vdup.s8 d1, d28[3] \n"
"vdup.s8 d7, d28[4] \n"
"vdup.s8 d11, d28[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3n
"vmlal.s8 q2, d8, d7 \n"// k4n
"vmlal.s8 q2, d9, d11 \n"// k5n
"vdup.s8 d1, d28[6] \n"
"vdup.s8 d7, d28[7] \n"
"vdup.s8 d11, d29[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6n
"vmlal.s8 q2, d12, d7 \n"// k7n
"vmlal.s8 q2, d13, d11 \n"// k8n
"pld [%2, #128] \n"
"vld1.32 {d18-d20}, [%2] \n"// sum1
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%2]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
kernel1 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
const signed char* kernel0 = (const signed char *)kernel + p * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr0n = outptr0 + outw;
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;
const signed char* r3 = img0 + w * 3;
const signed char* k00 = kernel0;
const signed char* k03 = kernel0 + 3;
const signed char* k06 = kernel0 + 6;
int i = 0;
for (; i+1 < outh; i+=2)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
: "=r"(kernel0) // %0
: "0"(kernel0)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%6, #128] \n"
"vld1.32 {d14-d15}, [%6] \n"// r3
"add %6, #8 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d21}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
asm volatile(
"pld [%3, #128] \n"
"vld1.32 {d0-d1}, [%3] \n"// r0
"add %3, #6 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%4, #128] \n"
"vld1.32 {d6-d7}, [%4] \n"// r1
"add %4, #6 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%5, #128] \n"
"vld1.32 {d10-d11}, [%5] \n"// r2
"add %5, #6 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%6, #128] \n"
"vld1.32 {d14-d15}, [%6] \n"// r3
"add %6, #6 \n"
"vext.8 d16, d14, d15, #1 \n"
"vext.8 d17, d14, d15, #2 \n"
"pld [%1, #128] \n"
"vld1.32 {d18-d20}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%1]! \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d6, d1 \n"// k0
"vmlal.s8 q2, d8, d30 \n"// k1
"vmlal.s8 q2, d9, d31 \n"// k2
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d10, d1 \n"// k3
"vmlal.s8 q2, d12, d30 \n"// k4
"vmlal.s8 q2, d13, d31 \n"// k5
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d14, d1 \n"// k6
"vmlal.s8 q2, d16, d30 \n"// k7
"vmlal.s8 q2, d17, d31 \n"// k8
"pld [%2, #128] \n"
"vld1.32 {d18-d20}, [%2] \n"// sum0n
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%2]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr0n += outw;
}
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.8 {d26-d27}, [%0] \n"
: "=r"(kernel0) // %0
: "0"(kernel0)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%2, #128] \n"
"vld1.32 {d0-d1}, [%2] \n"// r0
"add %2, #8 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%3, #128] \n"
"vld1.32 {d6-d7}, [%3] \n"// r1
"add %3, #8 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%4, #128] \n"
"vld1.32 {d10-d11}, [%4] \n"// r2
"add %4, #8 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d21}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d21}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
asm volatile(
"pld [%2, #128] \n"
"vld1.32 {d0-d1}, [%2] \n"// r0
"add %2, #6 \n"
"vext.8 d2, d0, d1, #1 \n"
"vext.8 d3, d0, d1, #2 \n"
"vdup.s8 d1, d26[0] \n"
"vdup.s8 d30, d26[1] \n"
"vdup.s8 d31, d26[2] \n"
"vmull.s8 q2, d0, d1 \n"// k0
"vmlal.s8 q2, d2, d30 \n"// k1
"vmlal.s8 q2, d3, d31 \n"// k2
"pld [%3, #128] \n"
"vld1.32 {d6-d7}, [%3] \n"// r1
"add %3, #6 \n"
"vext.8 d8, d6, d7, #1 \n"
"vext.8 d9, d6, d7, #2 \n"
"vdup.s8 d1, d26[3] \n"
"vdup.s8 d30, d26[4] \n"
"vdup.s8 d31, d26[5] \n"
"vmlal.s8 q2, d6, d1 \n"// k3
"vmlal.s8 q2, d8, d30 \n"// k4
"vmlal.s8 q2, d9, d31 \n"// k5
"pld [%4, #128] \n"
"vld1.32 {d10-d11}, [%4] \n"// r2
"add %4, #6 \n"
"vext.8 d12, d10, d11, #1 \n"
"vext.8 d13, d10, d11, #2 \n"
"vdup.s8 d1, d26[6] \n"
"vdup.s8 d30, d26[7] \n"
"vdup.s8 d31, d27[0] \n"
"vmlal.s8 q2, d10, d1 \n"// k6
"vmlal.s8 q2, d12, d30 \n"// k7
"vmlal.s8 q2, d13, d31 \n"// k8
"pld [%1, #128] \n"
"vld1.32 {d18-d20}, [%1] \n"// sum0
"vaddw.s16 q9, q9, d4 \n"
"vaddw.s16 q10, q10, d5 \n"
"vst1.32 {d18-d20}, [%1]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
r0 += 2;
r1 += 2;
r2 += 2;
}
kernel0 += 9;
}
}
}
static void conv3x3s2_neon_s8(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, 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 int tailstep = w - 2 * outw + w;
const signed char* kernel = _kernel;
int nn_outch = outch >> 1;
int remain_outch_start = nn_outch << 1;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 2;
Mat out0 = top_blob.channel(p);
Mat out1 = top_blob.channel(p + 1);
out0.fill(0.f);
out1.fill(0.f);
const signed char* kernel0 = (const signed char*)kernel + p * inch * 9;
const signed char* kernel1 = (const signed char*)kernel + (p + 1) * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
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;
const signed char* k00 = kernel0;
const signed char* k01 = kernel0 + 3;
const signed char* k02 = kernel0 + 6;
const signed char* k10 = kernel1;
const signed char* k11 = kernel1 + 3;
const signed char* k12 = kernel1 + 6;
int i = 0;
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.s8 {d22-d23}, [%0] \n"
"vld1.s8 {d24-d25}, [%1] \n"
: "=r"(kernel0), // %0
"=r"(kernel1) // %1
: "0"(kernel0),
"1"(kernel1)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%3, #192] \n"
"vld2.s8 {d0-d1}, [%3]! \n" // r0
"vld2.s8 {d2-d3}, [%3] \n"
"vext.8 d3, d0, d2, #1 \n"
"vdup.s8 d26, d22[0] \n"
"vdup.s8 d27, d22[1] \n"
"vdup.s8 d28, d22[2] \n"
"vmull.s8 q2, d0, d26 \n" // k00
"vmlal.s8 q2, d1, d27 \n" // k01
"vmlal.s8 q2, d3, d28 \n" // k02
"pld [%4, #192] \n"
"vld2.s8 {d6-d7}, [%4]! \n" // r1
"vld2.s8 {d8-d9}, [%4] \n"
"vext.8 d9, d6, d8, #1 \n"
"vdup.s8 d26, d22[3] \n"
"vdup.s8 d27, d22[4] \n"
"vdup.s8 d28, d22[5] \n"
"vmlal.s8 q2, d6, d26 \n" // k03
"vmlal.s8 q2, d7, d27 \n" // k04
"vmlal.s8 q2, d9, d28 \n" // k05
"pld [%5, #192] \n"
"vld2.s8 {d10-d11}, [%5]! \n" // r2
"vld2.s8 {d12-d13}, [%5] \n"
"vext.8 d13, d10, d12, #1 \n"
"vdup.s8 d26, d22[6] \n"
"vdup.s8 d27, d22[7] \n"
"vdup.s8 d28, d23[0] \n"
"vmlal.s8 q2, d10, d26 \n" // k06
"vmlal.s8 q2, d11, d27 \n" // k07
"vmlal.s8 q2, d13, d28 \n" // k08
"pld [%1, #256] \n"
"vld1.32 {d14-d17}, [%1] \n" //sum0
"vaddw.s16 q7, q7, d4 \n"
"vaddw.s16 q8, q8, d5 \n"
"vst1.32 {d14-d17}, [%1]! \n"
"vdup.s8 d26, d24[0] \n"
"vdup.s8 d27, d24[1] \n"
"vdup.s8 d28, d24[2] \n"
"vmull.s8 q2, d0, d26 \n" // k00
"vmlal.s8 q2, d1, d27 \n" // k01
"vmlal.s8 q2, d3, d28 \n" // k02
"vdup.s8 d26, d24[3] \n"
"vdup.s8 d27, d24[4] \n"
"vdup.s8 d28, d24[5] \n"
"vmlal.s8 q2, d6, d26 \n" // k03
"vmlal.s8 q2, d7, d27 \n" // k04
"vmlal.s8 q2, d9, d28 \n" // k05
"vdup.s8 d26, d24[6] \n"
"vdup.s8 d27, d24[7] \n"
"vdup.s8 d28, d25[0] \n"
"vmlal.s8 q2, d10, d26 \n" // k06
"vmlal.s8 q2, d11, d27 \n" // k07
"vmlal.s8 q2, d13, d28 \n" // k08
"pld [%2, #256] \n"
"vld1.32 {d14-d17}, [%2] \n" //sum1
"vaddw.s16 q7, q7, d4 \n"
"vaddw.s16 q8, q8, d5 \n"
"vst1.32 {d14-d17}, [%2]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q13", "q14", "q15"
);
}
if (remain >= 4)
{
remain -= 4;
asm volatile(
"pld [%3, #192] \n"
"vld2.s8 {d0-d1}, [%3]! \n" // r0
"vld2.s8 {d2-d3}, [%3] \n"
"vext.8 d3, d0, d2, #1 \n"
"vdup.s8 d26, d22[0] \n"
"vdup.s8 d27, d22[1] \n"
"vdup.s8 d28, d22[2] \n"
"vmull.s8 q2, d0, d26 \n" // k00
"vmlal.s8 q2, d1, d27 \n" // k01
"vmlal.s8 q2, d3, d28 \n" // k02
"pld [%4, #192] \n"
"vld2.s8 {d6-d7}, [%4]! \n" // r1
"vld2.s8 {d8-d9}, [%4] \n"
"vext.8 d9, d6, d8, #1 \n"
"vdup.s8 d26, d22[3] \n"
"vdup.s8 d27, d22[4] \n"
"vdup.s8 d28, d22[5] \n"
"vmlal.s8 q2, d6, d26 \n" // k03
"vmlal.s8 q2, d7, d27 \n" // k04
"vmlal.s8 q2, d9, d28 \n" // k05
"pld [%5, #192] \n"
"vld2.s8 {d10-d11}, [%5]! \n" // r2
"vld2.s8 {d12-d13}, [%5] \n"
"vext.8 d13, d10, d12, #1 \n"
"sub %3, #8 \n"
"sub %4, #8 \n"
"sub %5, #8 \n"
"vdup.s8 d26, d22[6] \n"
"vdup.s8 d27, d22[7] \n"
"vdup.s8 d28, d23[0] \n"
"vmlal.s8 q2, d10, d26 \n" // k06
"vmlal.s8 q2, d11, d27 \n" // k07
"vmlal.s8 q2, d13, d28 \n" // k08
"pld [%1, #128] \n"
"vld1.32 {d14-d15}, [%1] \n" //sum0
"vaddw.s16 q7, q7, d4 \n"
"vst1.32 {d14-d15}, [%1]! \n"
"vdup.s8 d26, d24[0] \n"
"vdup.s8 d27, d24[1] \n"
"vdup.s8 d28, d24[2] \n"
"vmull.s8 q2, d0, d26 \n" // k00
"vmlal.s8 q2, d1, d27 \n" // k01
"vmlal.s8 q2, d3, d28 \n" // k02
"vdup.s8 d26, d24[3] \n"
"vdup.s8 d27, d24[4] \n"
"vdup.s8 d28, d24[5] \n"
"vmlal.s8 q2, d6, d26 \n" // k03
"vmlal.s8 q2, d7, d27 \n" // k04
"vmlal.s8 q2, d9, d28 \n" // k05
"vdup.s8 d26, d24[6] \n"
"vdup.s8 d27, d24[7] \n"
"vdup.s8 d28, d25[0] \n"
"vmlal.s8 q2, d10, d26 \n" // k06
"vmlal.s8 q2, d11, d27 \n" // k07
"vmlal.s8 q2, d13, d28 \n" // k08
"pld [%2, #128] \n"
"vld1.32 {d14-d15}, [%2] \n" //sum1
"vaddw.s16 q7, q7, d4 \n"
"vst1.32 {d14-d15}, [%2]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2) // %5
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(r0),
"4"(r1),
"5"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q13", "q14", "q15"
);
}
for (; remain>0; remain--)
{
int sum0 = 0;
int sum1 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
sum1 += (int)r0[0] * kernel1[0];
sum1 += (int)r0[1] * kernel1[1];
sum1 += (int)r0[2] * kernel1[2];
sum1 += (int)r1[0] * kernel1[3];
sum1 += (int)r1[1] * kernel1[4];
sum1 += (int)r1[2] * kernel1[5];
sum1 += (int)r2[0] * kernel1[6];
sum1 += (int)r2[1] * kernel1[7];
sum1 += (int)r2[2] * kernel1[8];
*outptr0 += sum0;
*outptr1 += sum1;
r0 += 2;
r1 += 2;
r2 += 2;
outptr0++;
outptr1++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
kernel0 += 9;
kernel1 += 9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0.f);
const signed char* kernel0 = (const signed char*)kernel + p * inch * 9;
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
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;
const signed char* k00 = kernel0;
const signed char* k01 = kernel0 + 3;
const signed char* k02 = kernel0 + 6;
int i = 0;
for (; i < outh; i++)
{
int nn = outw >> 3;
int remain = outw & 7;
asm volatile(
"vld1.s8 {d22-d23}, [%0] \n"
: "=r"(kernel0) // %0
: "0"(kernel0)
: "cc", "memory"
);
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%2, #192] \n"
"vld2.s8 {d0-d1}, [%2]! \n" // r0
"vld2.s8 {d2-d3}, [%2] \n"
"vext.8 d3, d0, d2, #1 \n"
"vdup.s8 d26, d22[0] \n"
"vdup.s8 d27, d22[1] \n"
"vdup.s8 d28, d22[2] \n"
"vmull.s8 q2, d0, d26 \n" // k00
"vmlal.s8 q2, d1, d27 \n" // k01
"vmlal.s8 q2, d3, d28 \n" // k02
"pld [%3, #192] \n"
"vld2.s8 {d6-d7}, [%3]! \n" // r1
"vld2.s8 {d8-d9}, [%3] \n"
"vext.8 d9, d6, d8, #1 \n"
"vdup.s8 d26, d22[3] \n"
"vdup.s8 d27, d22[4] \n"
"vdup.s8 d28, d22[5] \n"
"vmlal.s8 q2, d6, d26 \n" // k03
"vmlal.s8 q2, d7, d27 \n" // k04
"vmlal.s8 q2, d9, d28 \n" // k05
"pld [%4, #192] \n"
"vld2.s8 {d10-d11}, [%4]! \n" // r2
"vld2.s8 {d12-d13}, [%4] \n"
"vext.8 d13, d10, d12, #1 \n"
"vdup.s8 d26, d22[6] \n"
"vdup.s8 d27, d22[7] \n"
"vdup.s8 d28, d23[0] \n"
"vmlal.s8 q2, d10, d26 \n" // k06
"vmlal.s8 q2, d11, d27 \n" // k07
"vmlal.s8 q2, d13, d28 \n" // k08
"pld [%1, #256] \n"
"vld1.32 {d14-d17}, [%1] \n" //sum0
"vaddw.s16 q7, q7, d4 \n"
"vaddw.s16 q8, q8, d5 \n"
"vst1.32 {d14-d17}, [%1]! \n"
"subs %0, #1 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q12", "q13", "q14"
);
}
if (remain >= 4)
{
remain -= 4;
asm volatile(
"pld [%2, #192] \n"
"vld2.s8 {d0-d1}, [%2]! \n" // r0
"vld2.s8 {d2-d3}, [%2] \n"
"vext.8 d3, d0, d2, #1 \n"
"vdup.s8 d26, d22[0] \n"
"vdup.s8 d27, d22[1] \n"
"vdup.s8 d28, d22[2] \n"
"vmull.s8 q2, d0, d26 \n" // k00
"vmlal.s8 q2, d1, d27 \n" // k01
"vmlal.s8 q2, d3, d28 \n" // k02
"pld [%3, #192] \n"
"vld2.s8 {d6-d7}, [%3]! \n" // r1
"vld2.s8 {d8-d9}, [%3] \n"
"vext.8 d9, d6, d8, #1 \n"
"vdup.s8 d26, d22[3] \n"
"vdup.s8 d27, d22[4] \n"
"vdup.s8 d28, d22[5] \n"
"vmlal.s8 q2, d6, d26 \n" // k03
"vmlal.s8 q2, d7, d27 \n" // k04
"vmlal.s8 q2, d9, d28 \n" // k05
"pld [%4, #192] \n"
"vld2.s8 {d10-d11}, [%4]! \n" // r2
"vld2.s8 {d12-d13}, [%4] \n"
"vext.8 d13, d10, d12, #1 \n"
"sub %2, #8 \n"
"sub %3, #8 \n"
"sub %4, #8 \n"
"vdup.s8 d26, d22[6] \n"
"vdup.s8 d27, d22[7] \n"
"vdup.s8 d28, d23[0] \n"
"vmlal.s8 q2, d10, d26 \n" // k06
"vmlal.s8 q2, d11, d27 \n" // k07
"vmlal.s8 q2, d13, d28 \n" // k08
"pld [%1, #128] \n"
"vld1.32 {d14-d15}, [%1] \n" //sum0
"vaddw.s16 q7, q7, d4 \n"
"vst1.32 {d14-d15}, [%1]! \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q12", "q13", "q14"
);
}
for (; remain>0; remain--)
{
int sum0 = 0;
sum0 += (int)r0[0] * kernel0[0];
sum0 += (int)r0[1] * kernel0[1];
sum0 += (int)r0[2] * kernel0[2];
sum0 += (int)r1[0] * kernel0[3];
sum0 += (int)r1[1] * kernel0[4];
sum0 += (int)r1[2] * kernel0[5];
sum0 += (int)r2[0] * kernel0[6];
sum0 += (int)r2[1] * kernel0[7];
sum0 += (int)r2[2] * kernel0[8];
*outptr0 += sum0;
r0 += 2;
r1 += 2;
r2 += 2;
outptr0++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
kernel0 += 9;
}
}
}
static void conv3x3s1_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int outw = top_blob.w;
int remain = outw & 7;
typedef void (*conv_func_int8)(const Mat&, Mat&, const Mat&, const Option&);
conv_func_int8 conv_func_table[8] =
{
conv3x3s1_neon_s8, //0
conv3x3s1_neon_s8, //1
conv3x3s1_neon_s8, //2
conv3x3s1_neon_s8, //3
conv3x3s1_neon_s8_left4, //4
conv3x3s1_neon_s8, //5
conv3x3s1_neon_s8_left6, //6
conv3x3s1_neon_s8, //7
};
conv_func_int8 conv = conv_func_table[remain];
conv(bottom_blob, top_blob, _kernel, opt);
return;
}
static void conv3x3s1_packed_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, 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;
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp < nn_outch; pp++)
{
int p = pp * 4;
Mat out0 = top_blob.channel(p+0);
Mat out1 = top_blob.channel(p+1);
Mat out2 = top_blob.channel(p+2);
Mat out3 = top_blob.channel(p+3);
out0.fill(0);
out1.fill(0);
out2.fill(0);
out3.fill(0);
const signed char* ktmp = _kernel.channel(p/4);
for (int q = 0; q < inch; q++)
{
int* outptr0 = out0;
int* outptr1 = out1;
int* outptr2 = out2;
int* outptr3 = out3;
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;
const signed char *r3 = img0 + w * 3;
int i = 0;
for (; i+1 < outh; i+=2)
{
#if __ARM_NEON
int nn = outw >> 3;
int remain = outw & 7;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
if (nn > 0)
{
asm volatile(
"0: \n"
// "pld [%9, #256] \n"
"vld1.s8 {d0-d3}, [%9]! \n"// d0=k00 k01 d1=k02 k10 d2=k11 k12 d3=k20 k21
"pld [%5, #128] \n"
"vld1.s8 {d4-d5}, [%5] \n"// d4=r00 d5=r00n
"add %5, #8 \n"
"vdup.s8 d8, d0[0] \n"
"vdup.s8 d9, d0[1] \n"
"pld [%6, #128] \n"
"vld1.s8 {d6-d7}, [%6] \n"// d6=r10 d7=r10n
"add %6, #8 \n"
"vdup.s8 d10, d0[2] \n"
"vdup.s8 d11, d0[3] \n"
"vmull.s8 q8, d4, d8 \n"
"vmull.s8 q9, d4, d9 \n"
"vdup.s8 d12, d0[4] \n"
"vdup.s8 d13, d0[5] \n"
"vmull.s8 q10, d4, d10 \n"
"vmull.s8 q11, d4, d11 \n"
"vdup.s8 d14, d0[6] \n"
"vdup.s8 d15, d0[7] \n"
"vmull.s8 q12, d6, d8 \n"
"vmull.s8 q13, d6, d9 \n"
"vext.s8 q2, q2, q2, #1 \n"// d4=r01
"vmull.s8 q14, d6, d10 \n"
"vmull.s8 q15, d6, d11 \n"
"vext.s8 q3, q3, q3, #1 \n"// d6=r11
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q9, d4, d13 \n"
"vdup.s8 d8, d1[0] \n"
"vdup.s8 d9, d1[1] \n"
"vmlal.s8 q10, d4, d14 \n"
"vmlal.s8 q11, d4, d15 \n"
"vdup.s8 d10, d1[2] \n"
"vdup.s8 d11, d1[3] \n"
"vmlal.s8 q12, d6, d12 \n"
"vmlal.s8 q13, d6, d13 \n"
"vext.s8 q2, q2, q2, #1 \n"// d4=r02
"vmlal.s8 q14, d6, d14 \n"
"vmlal.s8 q15, d6, d15 \n"
"vext.s8 q3, q3, q3, #1 \n"// d6=r12
"vmlal.s8 q8, d4, d8 \n"
"vmlal.s8 q9, d4, d9 \n"
"vdup.s8 d12, d1[4] \n"
"vdup.s8 d13, d1[5] \n"
"vmlal.s8 q10, d4, d10 \n"
"vmlal.s8 q11, d4, d11 \n"
"vdup.s8 d14, d1[6] \n"
"vdup.s8 d15, d1[7] \n"
"vmlal.s8 q12, d6, d8 \n"
"vmlal.s8 q13, d6, d9 \n"
"pld [%7, #128] \n"
"vld1.s8 {d4-d5}, [%7] \n"// d4=r20 d5=r20n
"add %7, #8 \n"
"vmlal.s8 q14, d6, d10 \n"
"vmlal.s8 q15, d6, d11 \n"
///
"vext.s8 q3, q3, q3, #14 \n"// d6=r10
"vmlal.s8 q8, d6, d12 \n"
"vmlal.s8 q9, d6, d13 \n"
"vdup.s8 d8, d2[0] \n"
"vdup.s8 d9, d2[1] \n"
"vmlal.s8 q10, d6, d14 \n"
"vmlal.s8 q11, d6, d15 \n"
"vdup.s8 d10, d2[2] \n"
"vdup.s8 d11, d2[3] \n"
"vmlal.s8 q12, d4, d12 \n"
"vmlal.s8 q13, d4, d13 \n"
"vext.s8 q3, q3, q3, #1 \n"// d6=r11
"vmlal.s8 q14, d4, d14 \n"
"vmlal.s8 q15, d4, d15 \n"
"vext.s8 q2, q2, q2, #1 \n"// d4=r21
"vmlal.s8 q8, d6, d8 \n"
"vmlal.s8 q9, d6, d9 \n"
"vdup.s8 d12, d2[4] \n"
"vdup.s8 d13, d2[5] \n"
"vmlal.s8 q10, d6, d10 \n"
"vmlal.s8 q11, d6, d11 \n"
"vdup.s8 d14, d2[6] \n"
"vdup.s8 d15, d2[7] \n"
"vmlal.s8 q12, d4, d8 \n"
"vmlal.s8 q13, d4, d9 \n"
"vext.s8 q3, q3, q3, #1 \n"// d6=r12
"vmlal.s8 q14, d4, d10 \n"
"vmlal.s8 q15, d4, d11 \n"
"vext.s8 q2, q2, q2, #1 \n"// d4=r22
"vmlal.s8 q8, d6, d12 \n"
"vmlal.s8 q9, d6, d13 \n"
"vdup.s8 d8, d3[0] \n"
"vdup.s8 d9, d3[1] \n"
"vmlal.s8 q10, d6, d14 \n"
"vmlal.s8 q11, d6, d15 \n"
"vdup.s8 d10, d3[2] \n"
"vdup.s8 d11, d3[3] \n"
"vmlal.s8 q12, d4, d12 \n"
"vmlal.s8 q13, d4, d13 \n"
"pld [%8, #128] \n"
"vld1.s8 {d6-d7}, [%8] \n"// d6=r30 d6=r30n
"add %8, #8 \n"
"vmlal.s8 q14, d4, d14 \n"
"vmlal.s8 q15, d4, d15 \n"
///
"vext.s8 q2, q2, q2, #14 \n"// d4=r20
"vmlal.s8 q8, d4, d8 \n"
"vmlal.s8 q9, d4, d9 \n"
"vdup.s8 d12, d3[4] \n"
"vdup.s8 d13, d3[5] \n"
"vmlal.s8 q10, d4, d10 \n"
"vmlal.s8 q11, d4, d11 \n"
"vdup.s8 d14, d3[6] \n"
"vdup.s8 d15, d3[7] \n"
"vmlal.s8 q12, d6, d8 \n"
"vmlal.s8 q13, d6, d9 \n"
"vext.s8 q2, q2, q2, #1 \n"// d4=r21
"vmlal.s8 q14, d6, d10 \n"
"vmlal.s8 q15, d6, d11 \n"
"vext.s8 q3, q3, q3, #1 \n"// d6=r31
// "pld [%9, #128] \n"
"vld1.s8 {d0}, [%9] \n"
"add %9, #4 \n"
"vmlal.s8 q8, d4, d12 \n"
"vmlal.s8 q9, d4, d13 \n"
"vdup.s8 d8, d0[0] \n"
"vdup.s8 d9, d0[1] \n"
"vmlal.s8 q10, d4, d14 \n"
"vmlal.s8 q11, d4, d15 \n"
"vdup.s8 d10, d0[2] \n"
"vdup.s8 d11, d0[3] \n"
"vmlal.s8 q12, d6, d12 \n"
"vmlal.s8 q13, d6, d13 \n"
"vext.s8 q2, q2, q2, #1 \n"// d4=r22
"vmlal.s8 q14, d6, d14 \n"
"vmlal.s8 q15, d6, d15 \n"
"vext.s8 q3, q3, q3, #1 \n"// d6=r32
"vmlal.s8 q8, d4, d8 \n"
"vmlal.s8 q9, d4, d9 \n"
"pld [%1, #256] \n"
"vld1.s32 {d12-d15}, [%1] \n"
"vmlal.s8 q10, d4, d10 \n"
"vmlal.s8 q11, d4, d11 \n"
"pld [%2, #256] \n"
"vld1.s32 {d0-d3}, [%2] \n"
"vaddw.s16 q6, q6, d16 \n"
"vaddw.s16 q7, q7, d17 \n"
"vaddw.s16 q0, q0, d18 \n"
"vaddw.s16 q1, q1, d19 \n"
"pld [%3, #256] \n"
"vld1.s32 {d16-d19}, [%3] \n"
"vmlal.s8 q12, d6, d8 \n"
"vmlal.s8 q13, d6, d9 \n"
"vst1.s32 {d12-d15}, [%1] \n"
"add %1, %1, %20, lsl #2 \n"
"vmlal.s8 q14, d6, d10 \n"
"vmlal.s8 q15, d6, d11 \n"
"pld [%4, #256] \n"
"vld1.s32 {d4-d7}, [%4] \n"
"vst1.s32 {d0-d3}, [%2] \n"
"add %2, %2, %20, lsl #2 \n"
"vaddw.s16 q8, q8, d20 \n"
"vaddw.s16 q9, q9, d21 \n"
"pld [%1, #256] \n"
"vld1.s32 {d12-d15}, [%1] \n"
"vaddw.s16 q2, q2, d22 \n"
"vaddw.s16 q3, q3, d23 \n"
///
"pld [%2, #256] \n"
"vld1.s32 {d0-d3}, [%2] \n"
"vaddw.s16 q6, q6, d24 \n"
"vst1.s32 {d16-d19}, [%3] \n"
"add %3, %3, %20, lsl #2 \n"
"vaddw.s16 q7, q7, d25 \n"
"pld [%3, #256] \n"
"vld1.s32 {d8-d11}, [%3] \n"
"vaddw.s16 q0, q0, d26 \n"
"vst1.s32 {d4-d7}, [%4] \n"
"add %4, %4, %20, lsl #2 \n"
///
"vaddw.s16 q1, q1, d27 \n"
"pld [%4, #256] \n"
"vld1.s32 {d4-d7}, [%4] \n"
"vaddw.s16 q4, q4, d28 \n"
"vst1.s32 {d12-d15}, [%1]! \n"
"vaddw.s16 q5, q5, d29 \n"
"vst1.s32 {d0-d3}, [%2]! \n"
"vaddw.s16 q2, q2, d30 \n"
"vst1.s32 {d8-d11}, [%3]! \n"
"vaddw.s16 q3, q3, d31 \n"
"sub %9, #36 \n"
"subs %0, #1 \n"
"sub %1, %1, %20, lsl #2 \n"
"sub %2, %2, %20, lsl #2 \n"
"sub %3, %3, %20, lsl #2 \n"
"vst1.s32 {d4-d7}, [%4]! \n"
"sub %4, %4, %20, lsl #2 \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr1), // %2
"=r"(outptr2), // %3
"=r"(outptr3), // %4
"=r"(r0), // %5
"=r"(r1), // %6
"=r"(r2), // %7
"=r"(r3), // %8
"=r"(ktmp) // %9
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(r3),
"9"(ktmp),
"r"(outw) // %20
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
#endif
#if __ARM_NEON
if (remain >= 4)
{
remain -= 4;
asm volatile(
"vld1.s8 {d0}, [%4] \n"// d0 = r00 r00n
"add %4, #4 \n"
"vld1.s8 {d2}, [%5] \n"// d2 = r10 r10n
"add %5, #4 \n"
"vld1.s8 {d1}, [%6] \n"// d1 = r20 r20n
"add %6, #4 \n"
"vld1.s8 {d3}, [%7] \n"// d3 = r30 r30n
"add %7, #4 \n"
"vext.s8 d4, d0, d0, #1 \n"// d4 = r01
"vext.s8 d6, d2, d2, #1 \n"// d6 = r11
"vext.s8 d5, d1, d1, #1 \n"// d5 = r21
"vext.s8 d7, d3, d3, #1 \n"// d7 = r31
"vext.s8 d8, d0, d0, #2 \n"// d8 = r02
"vext.s8 d10, d2, d2, #2 \n"// d10 = r12
"vext.s8 d9, d1, d1, #2 \n"// d9 = r22
"vext.s8 d11, d3, d3, #2 \n"// d11 = r32
"vld1.s8 {d12-d15}, [%8]! \n"// d12=k00 k01 d13=k02 k10 d14=k11 k12 d15=k20 k21
"vsli.64 q0, q1, #32 \n"// d0 = r00 r10 d1 = r20 r30
/// r00 r20 r10
"vdup.s8 d24, d12[0] \n"
"vdup.s8 d25, d12[1] \n"
"vdup.s8 d26, d12[2] \n"
"vdup.s8 d27, d12[3] \n"
"vmull.s8 q8, d0, d24 \n"
"vmull.s8 q9, d0, d25 \n"
"vdup.s8 d28, d15[0] \n"
"vdup.s8 d29, d15[1] \n"
"vmull.s8 q10, d0, d26 \n"
"vmull.s8 q11, d0, d27 \n"
"vdup.s8 d30, d15[2] \n"
"vdup.s8 d31, d15[3] \n"
"vmlal.s8 q8, d1, d28 \n"
"vmlal.s8 q9, d1, d29 \n"
"vext.s8 d0, d0, d1, #4 \n"// d0 = r10 r20
"vdup.s8 d24, d13[4] \n"
"vdup.s8 d25, d13[5] \n"
"vmlal.s8 q10, d1, d30 \n"
"vmlal.s8 q11, d1, d31 \n"
"vdup.s8 d26, d13[6] \n"
"vdup.s8 d27, d13[7] \n"
"vmlal.s8 q8, d0, d24 \n"
"vmlal.s8 q9, d0, d25 \n"
/// r01 r21 r11
"vsli.64 q2, q3, #32 \n"// d4 = r01 r11 d5 = r21 r31
"vdup.s8 d28, d12[4] \n"
"vdup.s8 d29, d12[5] \n"
"vmlal.s8 q10, d0, d26 \n"
"vmlal.s8 q11, d0, d27 \n"
"vdup.s8 d30, d12[6] \n"
"vdup.s8 d31, d12[7] \n"
"vmlal.s8 q8, d4, d28 \n"
"vmlal.s8 q9, d4, d29 \n"
"vdup.s8 d24, d15[4] \n"
"vdup.s8 d25, d15[5] \n"
"vmlal.s8 q10, d4, d30 \n"
"vmlal.s8 q11, d4, d31 \n"
"vdup.s8 d26, d15[6] \n"
"vdup.s8 d27, d15[7] \n"
"vmlal.s8 q8, d5, d24 \n"
"vmlal.s8 q9, d5, d25 \n"
"vext.s8 d4, d4, d5, #4 \n"// d4 = r11 r21
"vdup.s8 d28, d14[0] \n"
"vdup.s8 d29, d14[1] \n"
"vmlal.s8 q10, d5, d26 \n"
"vmlal.s8 q11, d5, d27 \n"
"vdup.s8 d30, d14[2] \n"
"vdup.s8 d31, d14[3] \n"
"vmlal.s8 q8, d4, d28 \n"
"vmlal.s8 q9, d4, d29 \n"
/// r02 r22 r12
"vsli.64 q4, q5, #32 \n"// d8 = r02 r12 d9 = r22 r32
"vld1.s8 {d12}, [%8] \n"// d12=k22
"add %8, #4 \n"
"vdup.s8 d24, d13[0] \n"
"vdup.s8 d25, d13[1] \n"
"vmlal.s8 q10, d4, d30 \n"
"vmlal.s8 q11, d4, d31 \n"
"vdup.s8 d26, d13[2] \n"
"vdup.s8 d27, d13[3] \n"
"vmlal.s8 q8, d8, d24 \n"
"vmlal.s8 q9, d8, d25 \n"
"vdup.s8 d28, d12[0] \n"
"vdup.s8 d29, d12[1] \n"
"vmlal.s8 q10, d8, d26 \n"
"vmlal.s8 q11, d8, d27 \n"
"vdup.s8 d30, d12[2] \n"
"vdup.s8 d31, d12[3] \n"
"vmlal.s8 q8, d9, d28 \n"
"vmlal.s8 q9, d9, d29 \n"
"vext.s8 d8, d8, d9, #4 \n"// d8 = r12 r22
"vdup.s8 d24, d14[4] \n"
"vdup.s8 d25, d14[5] \n"
"vld1.s32 {d0-d1}, [%0] \n"
"vmlal.s8 q10, d9, d30 \n"
"vmlal.s8 q11, d9, d31 \n"
"vdup.s8 d26, d14[6] \n"
"vdup.s8 d27, d14[7] \n"
"vld1.s32 {d2-d3}, [%1] \n"
"vmlal.s8 q8, d8, d24 \n"
"vmlal.s8 q9, d8, d25 \n"
"vld1.s32 {d4-d5}, [%2] \n"
"vmlal.s8 q10, d8, d26 \n"
"vmlal.s8 q11, d8, d27 \n"
"vld1.s32 {d6-d7}, [%3] \n"
"vaddw.s16 q0, q0, d16 \n"
"vaddw.s16 q1, q1, d18 \n"
"vst1.s32 {d0-d1}, [%0] \n"
"add %0, %0, %18, lsl #2 \n"
"vaddw.s16 q2, q2, d20 \n"
"vst1.s32 {d2-d3}, [%1] \n"
"add %1, %1, %18, lsl #2 \n"
"vaddw.s16 q3, q3, d22 \n"
"vld1.s32 {d8-d9}, [%0] \n"
"vld1.s32 {d10-d11}, [%1] \n"
"vst1.s32 {d4-d5}, [%2] \n"
"add %2, %2, %18, lsl #2 \n"
"vst1.s32 {d6-d7}, [%3] \n"
"add %3, %3, %18, lsl #2 \n"
"vld1.s32 {d28-d29}, [%2] \n"
"vld1.s32 {d30-d31}, [%3] \n"
"vaddw.s16 q4, q4, d17 \n"
"vaddw.s16 q5, q5, d19 \n"
"sub %8, #36 \n"
"vst1.s32 {d8-d9}, [%0]! \n"
"vaddw.s16 q14, q14, d21 \n"
"vaddw.s16 q15, q15, d23 \n"
"vst1.s32 {d10-d11}, [%1]! \n"
"sub %0, %0, %18, lsl #2 \n"
"sub %1, %1, %18, lsl #2 \n"
"vst1.s32 {d28-d29}, [%2]! \n"
"vst1.s32 {d30-d31}, [%3]! \n"
"sub %2, %2, %18, lsl #2 \n"
"sub %3, %3, %18, lsl #2 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(r0), // %4
"=r"(r1), // %5
"=r"(r2), // %6
"=r"(r3), // %7
"=r"(ktmp) // %8
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(r0),
"5"(r1),
"6"(r2),
"7"(r3),
"8"(ktmp),
"r"(outw) // %18
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
#endif
for (; remain>0; remain--)
{
#if __ARM_NEON
asm volatile(
"vld1.s8 {d0[]}, [%4]! \n"// d0 = 00 00
"vld1.s8 {d1[]}, [%4]! \n"// d1 = 01 01
"vld1.s8 {d2[]}, [%4] \n"// d2 = 02 02
"sub %4, %4, #2 \n"
"vld1.s8 {d3[]}, [%5]! \n"// d3 = 10 10
"vld1.s8 {d4[]}, [%5]! \n"// d4 = 11 11
"vld1.s8 {d5[]}, [%5] \n"// d5 = 12 12
"sub %5, %5, #2 \n"
"vld1.s8 {d6[]}, [%6]! \n"// d6 = 20 20
"vld1.s8 {d7[]}, [%6]! \n"// d7 = 21 21
"vld1.s8 {d8[]}, [%6] \n"// d8 = 22 22
"sub %6, %6, #2 \n"
"vld1.s8 {d9[]}, [%7]! \n"// d9 = 30 30
"vld1.s8 {d10[]}, [%7]! \n"// d10 = 31 31
"vld1.s8 {d11[]}, [%7] \n"// d11 = 32 32
"sub %7, %7, #2 \n"
"vld1.s8 {d12-d15}, [%8]! \n"// d12 d13 d14 d15 = 0~7
"vsli.64 d0, d1, #32 \n"// d0 = 00 01
"vsli.64 d3, d4, #32 \n"// d3 = 10 11
"vmull.s8 q8, d0, d12 \n"
"vsli.64 d2, d3, #32 \n"// d2 = 02 10
"vmull.s8 q9, d3, d12 \n"
"vsli.64 d5, d6, #32 \n"// d5 = 12 20
"vmlal.s8 q8, d2, d13 \n"
"vsli.64 d4, d5, #32 \n"// d4 = 11 12
"vmlal.s8 q9, d5, d13 \n"
"vsli.64 d7, d8, #32 \n"// d7 = 21 22
"vmlal.s8 q8, d4, d14 \n"
"vsli.64 d6, d7, #32 \n"// d6 = 20 21
"vmlal.s8 q9, d7, d14 \n"
"vsli.64 d9, d10, #32 \n"// d9 = 30 31
"vld1.s32 {d20[0]}, [%0] \n"
"vld1.s32 {d20[1]}, [%1] \n"
"add %0, %0, %18, lsl #2 \n"
"add %1, %1, %18, lsl #2 \n"
"vmlal.s8 q8, d6, d15 \n"
"vsli.64 d8, d11, #32 \n"// d8 = 22 32
"vmlal.s8 q9, d9, d15 \n"
"vld1.s8 {d14}, [%8] \n"
"add %8, #4 \n"
"vld1.s32 {d21[0]}, [%2] \n"
"vld1.s32 {d21[1]}, [%3] \n"
"add %2, %2, %18, lsl #2 \n"
"add %3, %3, %18, lsl #2 \n"
"vadd.s16 d12, d16, d17 \n"
"vadd.s16 d13, d18, d19 \n"// q6 = sum0123 sum0123n
"vsli.64 d14, d14, #32 \n"// d14 = 0~3 0~3
"vld1.s32 {d22[0]}, [%0] \n"
"vld1.s32 {d22[1]}, [%1] \n"
"vmlal.s8 q6, d8, d14 \n"
"sub %8, #36 \n"
///
"vld1.s32 {d23[0]}, [%2] \n"
"vld1.s32 {d23[1]}, [%3] \n"
"sub %0, %0, %18, lsl #2 \n"
"sub %1, %1, %18, lsl #2 \n"
// addw
"vaddw.s16 q10, q10, d12 \n"
"vaddw.s16 q11, q11, d13 \n"
"sub %2, %2, %18, lsl #2 \n"
"sub %3, %3, %18, lsl #2 \n"
"vst1.s32 {d20[0]}, [%0] \n"
"vst1.s32 {d20[1]}, [%1] \n"
"add %0, %0, %18, lsl #2 \n"
"add %1, %1, %18, lsl #2 \n"
"vst1.s32 {d21[0]}, [%2] \n"
"vst1.s32 {d21[1]}, [%3] \n"
"add %2, %2, %18, lsl #2 \n"
"add %3, %3, %18, lsl #2 \n"
"vst1.s32 {d22[0]}, [%0]! \n"
"vst1.s32 {d22[1]}, [%1]! \n"
"sub %0, %0, %18, lsl #2 \n"
"sub %1, %1, %18, lsl #2 \n"
"vst1.s32 {d23[0]}, [%2]! \n"
"vst1.s32 {d23[1]}, [%3]! \n"
"sub %2, %2, %18, lsl #2 \n"
"sub %3, %3, %18, lsl #2 \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(r0), // %4
"=r"(r1), // %5
"=r"(r2), // %6
"=r"(r3), // %7
"=r"(ktmp) // %8
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(r0),
"5"(r1),
"6"(r2),
"7"(r3),
"8"(ktmp),
"r"(outw) // %18
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"
);
#else
int sum0 = 0;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
int sum0n = 0;
int sum1n = 0;
int sum2n = 0;
int sum3n = 0;
sum0 += r0[0] * ktmp[0];
sum1 += r0[0] * ktmp[1];
sum2 += r0[0] * ktmp[2];
sum3 += r0[0] * ktmp[3];
sum0 += r0[1] * ktmp[4];
sum1 += r0[1] * ktmp[5];
sum2 += r0[1] * ktmp[6];
sum3 += r0[1] * ktmp[7];
sum0n += r1[0] * ktmp[0];
sum1n += r1[0] * ktmp[1];
sum2n += r1[0] * ktmp[2];
sum3n += r1[0] * ktmp[3];
sum0n += r1[1] * ktmp[4];
sum1n += r1[1] * ktmp[5];
sum2n += r1[1] * ktmp[6];
sum3n += r1[1] * ktmp[7];
ktmp += 8;
sum0 += r0[2] * ktmp[0];
sum1 += r0[2] * ktmp[1];
sum2 += r0[2] * ktmp[2];
sum3 += r0[2] * ktmp[3];
sum0 += r1[0] * ktmp[4];
sum1 += r1[0] * ktmp[5];
sum2 += r1[0] * ktmp[6];
sum3 += r1[0] * ktmp[7];
sum0n += r1[2] * ktmp[0];
sum1n += r1[2] * ktmp[1];
sum2n += r1[2] * ktmp[2];
sum3n += r1[2] * ktmp[3];
sum0n += r2[0] * ktmp[4];
sum1n += r2[0] * ktmp[5];
sum2n += r2[0] * ktmp[6];
sum3n += r2[0] * ktmp[7];
ktmp += 8;
sum0 += r1[1] * ktmp[0];
sum1 += r1[1] * ktmp[1];
sum2 += r1[1] * ktmp[2];
sum3 += r1[1] * ktmp[3];
sum0 += r1[2] * ktmp[4];
sum1 += r1[2] * ktmp[5];
sum2 += r1[2] * ktmp[6];
sum3 += r1[2] * ktmp[7];
sum0n += r2[1] * ktmp[0];
sum1n += r2[1] * ktmp[1];
sum2n += r2[1] * ktmp[2];
sum3n += r2[1] * ktmp[3];
sum0n += r2[2] * ktmp[4];
sum1n += r2[2] * ktmp[5];
sum2n += r2[2] * ktmp[6];
sum3n += r2[2] * ktmp[7];
ktmp += 8;
///
sum0 += r2[0] * ktmp[0];
sum1 += r2[0] * ktmp[1];
sum2 += r2[0] * ktmp[2];
sum3 += r2[0] * ktmp[3];
sum0 += r2[1] * ktmp[4];
sum1 += r2[1] * ktmp[5];
sum2 += r2[1] * ktmp[6];
sum3 += r2[1] * ktmp[7];
sum0n += r3[0] * ktmp[0];
sum1n += r3[0] * ktmp[1];
sum2n += r3[0] * ktmp[2];
sum3n += r3[0] * ktmp[3];
sum0n += r3[1] * ktmp[4];
sum1n += r3[1] * ktmp[5];
sum2n += r3[1] * ktmp[6];
sum3n += r3[1] * ktmp[7];
ktmp += 8;
sum0 += r2[2] * ktmp[0];
sum1 += r2[2] * ktmp[1];
sum2 += r2[2] * ktmp[2];
sum3 += r2[2] * ktmp[3];
sum0n += r3[2] * ktmp[0];
sum1n += r3[2] * ktmp[1];
sum2n += r3[2] * ktmp[2];
sum3n += r3[2] * ktmp[3];
ktmp += 4;
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
*(outptr0 + outw) += sum0n;
*(outptr1 + outw) += sum1n;
*(outptr2 + outw) += sum2n;
*(outptr3 + outw) += sum3n;
ktmp -= 12*3;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
#endif
r0++;
r1++;
r2++;
r3++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr1 += outw;
outptr2 += outw;
outptr3 += outw;
}
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 (nn > 0)
{
asm volatile(
"0: \n"
// "pld [%8, #256] \n"
"vld1.s8 {d0-d3}, [%8]! \n"// d0=k00 k01 d1=k02 k10 d2=k11 k12 d3=k20 k21
"pld [%5, #128] \n"
"vld1.s8 {d4-d5}, [%5] \n"// d4=r00 d5=r00n
"add %5, #8 \n"
"vdup.s8 d8, d0[0] \n"
"vdup.s8 d9, d0[1] \n"
"vdup.s8 d10, d0[2] \n"
"vdup.s8 d11, d0[3] \n"
"vmull.s8 q8, d4, d8 \n"
"vmull.s8 q9, d4, d9 \n"
"vext.s8 d24, d4, d5, #1 \n"// d24=r01
"vdup.s8 d12, d0[4] \n"
"vdup.s8 d13, d0[5] \n"
"vmull.s8 q10, d4, d10 \n"
"vmull.s8 q11, d4, d11 \n"
"vdup.s8 d14, d0[6] \n"
"vdup.s8 d15, d0[7] \n"
"vmlal.s8 q8, d24, d12 \n"
"vmlal.s8 q9, d24, d13 \n"
"vext.s8 d25, d4, d5, #2 \n"// d25=r02
"vdup.s8 d8, d1[0] \n"
"vdup.s8 d9, d1[1] \n"
"vmlal.s8 q10, d24, d14 \n"
"vmlal.s8 q11, d24, d15 \n"
"vdup.s8 d10, d1[2] \n"
"vdup.s8 d11, d1[3] \n"
"vmlal.s8 q8, d25, d8 \n"
"vmlal.s8 q9, d25, d9 \n"
"pld [%6, #128] \n"
"vld1.s8 {d6-d7}, [%6] \n"// d6=r10 d7=r10n
"add %6, #8 \n"
"vdup.s8 d12, d1[4] \n"
"vdup.s8 d13, d1[5] \n"
"vmlal.s8 q10, d25, d10 \n"
"vmlal.s8 q11, d25, d11 \n"
"vdup.s8 d14, d1[6] \n"
"vdup.s8 d15, d1[7] \n"
"vmlal.s8 q8, d6, d12 \n"
"vmlal.s8 q9, d6, d13 \n"
"vext.s8 d26, d6, d7, #1 \n"// d26=r11
"vdup.s8 d8, d2[0] \n"
"vdup.s8 d9, d2[1] \n"
"vmlal.s8 q10, d6, d14 \n"
"vmlal.s8 q11, d6, d15 \n"
"vdup.s8 d10, d2[2] \n"
"vdup.s8 d11, d2[3] \n"
"vmlal.s8 q8, d26, d8 \n"
"vmlal.s8 q9, d26, d9 \n"
"vext.s8 d27, d6, d7, #2 \n"// d27=r12
"vdup.s8 d12, d2[4] \n"
"vdup.s8 d13, d2[5] \n"
"vmlal.s8 q10, d26, d10 \n"
"vmlal.s8 q11, d26, d11 \n"
"vdup.s8 d14, d2[6] \n"
"vdup.s8 d15, d2[7] \n"
"vmlal.s8 q8, d27, d12 \n"
"vmlal.s8 q9, d27, d13 \n"
"pld [%7, #128] \n"
"vld1.s8 {d4-d5}, [%7] \n"// d4=r20 d5=r20n
"add %7, #8 \n"
"vdup.s8 d8, d3[0] \n"
"vdup.s8 d9, d3[1] \n"
"vmlal.s8 q10, d27, d14 \n"
"vmlal.s8 q11, d27, d15 \n"
"vdup.s8 d10, d3[2] \n"
"vdup.s8 d11, d3[3] \n"
"vmlal.s8 q8, d4, d8 \n"
"vmlal.s8 q9, d4, d9 \n"
"vext.s8 d24, d4, d5, #1 \n"// d24=r21
"vdup.s8 d12, d3[4] \n"
"vdup.s8 d13, d3[5] \n"
"vmlal.s8 q10, d4, d10 \n"
"vmlal.s8 q11, d4, d11 \n"
"vdup.s8 d14, d3[6] \n"
"vdup.s8 d15, d3[7] \n"
"vmlal.s8 q8, d24, d12 \n"
"vmlal.s8 q9, d24, d13 \n"
// "pld [%8, #128] \n"
"vld1.s8 {d0}, [%8] \n"
"add %8, #4 \n"
"vext.s8 d25, d4, d5, #2 \n"// d25=r22
"vdup.s8 d8, d0[0] \n"
"vdup.s8 d9, d0[1] \n"
"vmlal.s8 q10, d24, d14 \n"
"vmlal.s8 q11, d24, d15 \n"
"vdup.s8 d10, d0[2] \n"
"vdup.s8 d11, d0[3] \n"
"pld [%1, #256] \n"
"vld1.s32 {d12-d15}, [%1] \n"
"vmlal.s8 q8, d25, d8 \n"
"vmlal.s8 q9, d25, d9 \n"
"pld [%2, #256] \n"
"vld1.s32 {d0-d3}, [%2] \n"
"vaddw.s16 q6, q6, d16 \n"
"vaddw.s16 q7, q7, d17 \n"
"vmlal.s8 q10, d25, d10 \n"
"vmlal.s8 q11, d25, d11 \n"
"vaddw.s16 q0, q0, d18 \n"
"vaddw.s16 q1, q1, d19 \n"
"pld [%3, #256] \n"
"vld1.s32 {d16-d19}, [%3] \n"
"vst1.s32 {d12-d15}, [%1]! \n"
"pld [%4, #256] \n"
"vld1.s32 {d4-d7}, [%4] \n"
"vst1.s32 {d0-d3}, [%2]! \n"
"vaddw.s16 q8, q8, d20 \n"
"vaddw.s16 q9, q9, d21 \n"
"vaddw.s16 q2, q2, d22 \n"
"vaddw.s16 q3, q3, d23 \n"
"sub %8, #36 \n"
"vst1.s32 {d16-d19}, [%3]! \n"
"subs %0, #1 \n"
"vst1.s32 {d4-d7}, [%4]! \n"
"bne 0b \n"
: "=r"(nn),
"=r"(outptr0),
"=r"(outptr1),
"=r"(outptr2),
"=r"(outptr3),
"=r"(r0),
"=r"(r1),
"=r"(r2),
"=r"(ktmp)
: "0"(nn),
"1"(outptr0),
"2"(outptr1),
"3"(outptr2),
"4"(outptr3),
"5"(r0),
"6"(r1),
"7"(r2),
"8"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13"
);
}
#endif
#if __ARM_NEON
if (remain >= 4)
{
remain -= 4;
asm volatile(
"vld1.s8 {d0}, [%4] \n"// d0 = r00 r00n
"add %4, #4 \n"
"vld1.s8 {d3}, [%5] \n"// d3 = r10 r10n
"add %5, #4 \n"
"vld1.s8 {d6}, [%6] \n"// d6 = r20 r20n
"add %6, #4 \n"
"vld1.s8 {d12-d15}, [%7]! \n"// d12=k00 k01 d13=k02 k10 d14=k11 k12 d15=k20 k21
/// r00 r01 r02
"vext.s8 d1, d0, d0, #1 \n"
"vext.s8 d2, d0, d0, #2 \n"
"vdup.s8 d24, d12[0] \n"
"vdup.s8 d26, d12[1] \n"
"vdup.s8 d25, d12[2] \n"
"vdup.s8 d27, d12[3] \n"
"vsli.64 d0, d0, #32 \n"// d0 = r00 r00
"vsli.64 d1, d1, #32 \n"// d1 = r01 r01
"vsli.64 d2, d2, #32 \n"// d2 = r02 r02
"vsli.64 q12, q13, #32 \n"
"vdup.s8 d28, d12[4] \n"
"vdup.s8 d30, d12[5] \n"
"vdup.s8 d29, d12[6] \n"
"vdup.s8 d31, d12[7] \n"
"vsli.64 q14, q15, #32 \n"
"vmull.s8 q8, d0, d24 \n"
"vmull.s8 q9, d0, d25 \n"
"vdup.s8 d24, d13[0] \n"
"vdup.s8 d26, d13[1] \n"
"vdup.s8 d25, d13[2] \n"
"vdup.s8 d27, d13[3] \n"
"vsli.64 q12, q13, #32 \n"
"vmlal.s8 q8, d1, d28 \n"
"vmlal.s8 q9, d1, d29 \n"
/// r10 r11 r12
"vext.s8 d4, d3, d3, #1 \n"
"vext.s8 d5, d3, d3, #2 \n"
"vdup.s8 d28, d13[4] \n"
"vdup.s8 d30, d13[5] \n"
"vdup.s8 d29, d13[6] \n"
"vdup.s8 d31, d13[7] \n"
"vsli.64 d3, d3, #32 \n"// d3 = r10 r10
"vsli.64 d4, d4, #32 \n"// d4 = r11 r11
"vsli.64 d5, d5, #32 \n"// d5 = r12 r12
"vsli.64 q14, q15, #32 \n"
"vmlal.s8 q8, d2, d24 \n"
"vmlal.s8 q9, d2, d25 \n"
"vdup.s8 d24, d14[0] \n"
"vdup.s8 d26, d14[1] \n"
"vdup.s8 d25, d14[2] \n"
"vdup.s8 d27, d14[3] \n"
"vsli.64 q12, q13, #32 \n"
"vmlal.s8 q8, d3, d28 \n"
"vmlal.s8 q9, d3, d29 \n"
"vdup.s8 d28, d14[4] \n"
"vdup.s8 d30, d14[5] \n"
"vdup.s8 d29, d14[6] \n"
"vdup.s8 d31, d14[7] \n"
"vsli.64 q14, q15, #32 \n"
"vmlal.s8 q8, d4, d24 \n"
"vmlal.s8 q9, d4, d25 \n"
/// r20 r21 r22
"vext.s8 d7, d6, d6, #1 \n"
"vext.s8 d8, d6, d6, #2 \n"
"vdup.s8 d24, d15[0] \n"
"vdup.s8 d26, d15[1] \n"
"vdup.s8 d25, d15[2] \n"
"vdup.s8 d27, d15[3] \n"
"vsli.64 d6, d6, #32 \n"// d6 = r20 r20
"vsli.64 d7, d7, #32 \n"// d7 = r21 r21
"vsli.64 d8, d8, #32 \n"// d8 = r22 r22
"vsli.64 q12, q13, #32 \n"
"vmlal.s8 q8, d5, d28 \n"
"vmlal.s8 q9, d5, d29 \n"
"vdup.s8 d28, d15[4] \n"
"vdup.s8 d30, d15[5] \n"
"vdup.s8 d29, d15[6] \n"
"vdup.s8 d31, d15[7] \n"
"vsli.64 q14, q15, #32 \n"
"vld1.s8 {d12}, [%7] \n"// d12=k22
"add %7, #4 \n"
"vmlal.s8 q8, d6, d24 \n"
"vmlal.s8 q9, d6, d25 \n"
"vdup.s8 d24, d12[0] \n"
"vdup.s8 d26, d12[1] \n"
"vdup.s8 d25, d12[2] \n"
"vdup.s8 d27, d12[3] \n"
"vsli.64 q12, q13, #32 \n"
"vmlal.s8 q8, d7, d28 \n"
"vmlal.s8 q9, d7, d29 \n"
"vld1.s32 {d0-d1}, [%0] \n"
"vld1.s32 {d2-d3}, [%1] \n"
"vmlal.s8 q8, d8, d24 \n"
"vmlal.s8 q9, d8, d25 \n"
///
"vld1.s32 {d4-d5}, [%2] \n"
"vld1.s32 {d6-d7}, [%3] \n"
"vaddw.s16 q0, q0, d16 \n"
"vaddw.s16 q1, q1, d17 \n"
"vaddw.s16 q2, q2, d18 \n"
"vaddw.s16 q3, q3, d19 \n"
"vst1.s32 {d0-d1}, [%0]! \n"
"vst1.s32 {d2-d3}, [%1]! \n"
"sub %7, #36 \n"
"vst1.s32 {d4-d5}, [%2]! \n"
"vst1.s32 {d6-d7}, [%3]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(r0), // %4
"=r"(r1), // %5
"=r"(r2), // %6
"=r"(ktmp) // %7
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(r0),
"5"(r1),
"6"(r2),
"7"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q6", "q7", "q8", "q9", "q12", "q13", "q14", "q15"
);
}
#endif
for (; remain>0; remain--)
{
#if __ARM_NEON
asm volatile(
"vld1.s8 {d0[]}, [%4]! \n"
"vld1.s8 {d1[]}, [%4]! \n"
"vld1.s8 {d4-d7}, [%7]! \n"// d4 d5 d6 d7 = 0~7
"vsli.64 d0, d1, #32 \n"// d0 = 00 01
"vld1.s8 {d2[]}, [%4] \n"
"sub %4, %4, #2 \n"
"vld1.s8 {d3[]}, [%5]! \n"
"vsli.64 d2, d3, #32 \n"// d2 = 02 10
"vmull.s8 q8, d0, d4 \n"
"vld1.s8 {d0[]}, [%5]! \n"
"vld1.s8 {d1[]}, [%5] \n"
"sub %5, %5, #2 \n"
"vsli.64 d0, d1, #32 \n"// d0 = 11 12
"vmlal.s8 q8, d2, d5 \n"
"vld1.s8 {d2[]}, [%6]! \n"
"vld1.s8 {d3[]}, [%6]! \n"
"vsli.64 d2, d3, #32 \n"// d2 = 20 21
"vmlal.s8 q8, d0, d6 \n"
"vld1.s8 {d0[]}, [%6] \n"
"sub %6, %6, #2 \n"
"veor d1, d1, d1 \n"
"vld1.s8 {d4}, [%7] \n"// d4 = 0~4 xxxx
"sub %7, #32 \n"
"vsli.64 d0, d1, #32 \n"// d0 = 22 zero
"vmlal.s8 q8, d2, d7 \n"
"vld1.s32 {d20[0]}, [%0] \n"
"vmlal.s8 q8, d0, d4 \n"
"vld1.s32 {d20[1]}, [%1] \n"
"vadd.s16 d16, d16, d17 \n"
"vld1.s32 {d21[0]}, [%2] \n"
"vld1.s32 {d21[1]}, [%3] \n"
"vaddw.s16 q10, q10, d16 \n"
"vst1.s32 {d20[0]}, [%0]! \n"
"vst1.s32 {d20[1]}, [%1]! \n"
"vst1.s32 {d21[0]}, [%2]! \n"
"vst1.s32 {d21[1]}, [%3]! \n"
: "=r"(outptr0), // %0
"=r"(outptr1), // %1
"=r"(outptr2), // %2
"=r"(outptr3), // %3
"=r"(r0), // %4
"=r"(r1), // %5
"=r"(r2), // %6
"=r"(ktmp) // %7
: "0"(outptr0),
"1"(outptr1),
"2"(outptr2),
"3"(outptr3),
"4"(r0),
"5"(r1),
"6"(r2),
"7"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q10"
);
#else
int sum0 = 0;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum0 += r0[0] * ktmp[0];
sum1 += r0[0] * ktmp[1];
sum2 += r0[0] * ktmp[2];
sum3 += r0[0] * ktmp[3];
sum0 += r0[1] * ktmp[4];
sum1 += r0[1] * ktmp[5];
sum2 += r0[1] * ktmp[6];
sum3 += r0[1] * ktmp[7];
ktmp += 8;
sum0 += r0[2] * ktmp[0];
sum1 += r0[2] * ktmp[1];
sum2 += r0[2] * ktmp[2];
sum3 += r0[2] * ktmp[3];
sum0 += r1[0] * ktmp[4];
sum1 += r1[0] * ktmp[5];
sum2 += r1[0] * ktmp[6];
sum3 += r1[0] * ktmp[7];
ktmp += 8;
sum0 += r1[1] * ktmp[0];
sum1 += r1[1] * ktmp[1];
sum2 += r1[1] * ktmp[2];
sum3 += r1[1] * ktmp[3];
sum0 += r1[2] * ktmp[4];
sum1 += r1[2] * ktmp[5];
sum2 += r1[2] * ktmp[6];
sum3 += r1[2] * ktmp[7];
ktmp += 8;
sum0 += r2[0] * ktmp[0];
sum1 += r2[0] * ktmp[1];
sum2 += r2[0] * ktmp[2];
sum3 += r2[0] * ktmp[3];
sum0 += r2[1] * ktmp[4];
sum1 += r2[1] * ktmp[5];
sum2 += r2[1] * ktmp[6];
sum3 += r2[1] * ktmp[7];
ktmp += 8;
sum0 += r2[2] * ktmp[0];
sum1 += r2[2] * ktmp[1];
sum2 += r2[2] * ktmp[2];
sum3 += r2[2] * ktmp[3];
ktmp += 8;
*outptr0 += sum0;
*outptr1 += sum1;
*outptr2 += sum2;
*outptr3 += sum3;
ktmp -= 8*5;
outptr0++;
outptr1++;
outptr2++;
outptr3++;
#endif
r0++;
r1++;
r2++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
ktmp += 4*9;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0 = top_blob.channel(p);
out0.fill(0);
const signed char* ktmp = _kernel.channel(p/4 + p%4);
for (int q=0; q<inch; q++)
{
int* outptr0 = out0;
int* outptr0n = outptr0 + outw;
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;
const signed char* r3 = img0 + w * 3;
int8x8_t _k00 = vdup_n_s8(ktmp[0]);
int8x8_t _k01 = vdup_n_s8(ktmp[1]);
int8x8_t _k02 = vdup_n_s8(ktmp[2]);
int8x8_t _k10 = vdup_n_s8(ktmp[3]);
int8x8_t _k11 = vdup_n_s8(ktmp[4]);
int8x8_t _k12 = vdup_n_s8(ktmp[5]);
int8x8_t _k20 = vdup_n_s8(ktmp[6]);
int8x8_t _k21 = vdup_n_s8(ktmp[7]);
int8x8_t _k22 = vdup_n_s8(ktmp[8]);
int i = 0;
for (; i+1 < outh; i+=2)
{
#if __ARM_NEON
int nn = outw >> 3;
int remain = outw & 7;
#else
int remain = outw;
#endif // __ARM_NEON
#if __ARM_NEON
if (nn > 0)
{
asm volatile(
"0: \n"
"pld [%3, #128] \n"
"vld1.s8 {d4-d5}, [%3] \n"// d4=r00 d5=r00n
"add %3, #8 \n"
"pld [%6, #128] \n"
"vld1.s8 {d6-d7}, [%6] \n"// d6=r30 d7=r30n
"add %6, #8 \n"
"vext.s8 d8, d4, d5, #1 \n"// d8=r01
"vext.s8 d10, d6, d7, #1 \n"// d10=r31
"vmull.s8 q8, d4, %P14 \n"
"vmull.s8 q9, d6, %P20 \n"
"vext.s8 d9, d4, d5, #2 \n"// d9=r02
"vext.s8 d11, d6, d7, #2 \n"// d11=r32
"vmlal.s8 q8, d8, %P15 \n"
"vmlal.s8 q9, d10, %P21 \n"
"pld [%4, #128] \n"
"vld1.s8 {d4-d5}, [%4] \n"// d4=r10 d5=r10n
"add %4, #8 \n"
"vmlal.s8 q8, d9, %P16 \n"
"vmlal.s8 q9, d11, %P22 \n"
"vext.s8 d8, d4, d5, #1 \n"// d8=r11
"vmlal.s8 q8, d4, %P17 \n"
"vmlal.s8 q9, d4, %P14 \n"
"vext.s8 d9, d4, d5, #2 \n"// d9=r12
"vmlal.s8 q8, d8, %P18 \n"
"vmlal.s8 q9, d8, %P15 \n"
"pld [%5, #128] \n"
"vld1.s8 {d6-d7}, [%5] \n"// d6=r20 d7=r20n
"add %5, #8 \n"
"vmlal.s8 q8, d9, %P19 \n"
"vmlal.s8 q9, d9, %P16 \n"
"vext.s8 d10, d6, d7, #1 \n"// d10=r21
"vmlal.s8 q8, d6, %P20 \n"
"vmlal.s8 q9, d6, %P17 \n"
"vext.s8 d11, d6, d7, #2 \n"// d11=r22
"vmlal.s8 q8, d10, %P21 \n"
"vmlal.s8 q9, d10, %P18 \n"
"pld [%1, #256] \n"
"vld1.s32 {d0-d3}, [%1] \n"
"vmlal.s8 q8, d11, %P22 \n"
"vmlal.s8 q9, d11, %P19 \n"
"pld [%2, #256] \n"
"vld1.s32 {d12-d15}, [%2] \n"
"vaddw.s16 q0, q0, d16 \n"
"vaddw.s16 q1, q1, d17 \n"
"vaddw.s16 q6, q6, d18 \n"
"vaddw.s16 q7, q7, d19 \n"
"vst1.s32 {d0-d3}, [%1]! \n"
"subs %0, #1 \n"
"vst1.s32 {d12-d15}, [%2]! \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(outptr0n), // %2
"=r"(r0), // %3
"=r"(r1), // %4
"=r"(r2), // %5
"=r"(r3) // %6
: "0"(nn),
"1"(outptr0),
"2"(outptr0n),
"3"(r0),
"4"(r1),
"5"(r2),
"6"(r3),
"w"(_k00), // %14
"w"(_k01), // %15
"w"(_k02), // %16
"w"(_k10), // %17
"w"(_k11), // %18
"w"(_k12), // %19
"w"(_k20), // %20
"w"(_k21), // %21
"w"(_k22) // %22
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9"
);
}
#endif
#if __ARM_NEON
if (remain >= 4)
{
remain -= 4;
asm volatile(
"vld1.s8 {d12}, [%6]! \n"// d12=0~7
/// r00 r01 r02
"vld1.s8 {d0}, [%2] \n"// d0 = r00 r00n
"add %2, #4 \n"
"vdup.s8 d24, d12[0] \n"
"vext.s8 d1, d0, d0, #1 \n"
"vext.s8 d2, d0, d0, #2 \n"
/// r10 r11 r12
"vld1.s8 {d3}, [%3] \n"// d3 = r10 r10n
"add %3, #4 \n"
"vdup.s8 d25, d12[1] \n"
"vext.s8 d4, d3, d3, #1 \n"
"vext.s8 d5, d3, d3, #2 \n"
"vdup.s8 d26, d12[2] \n"
"vsli.64 d0, d3, #32 \n"// d0 = r00 r10
"vsli.64 d1, d4, #32 \n"// d1 = r01 r11
"vsli.64 d2, d5, #32 \n"// d2 = r02 r12
"vmull.s8 q8, d0, d24 \n"
"vmull.s8 q9, d1, d25 \n"
/// r20 r21 r22
"vld1.s8 {d6}, [%4] \n"// d6 = r20 r20n
"add %4, #4 \n"
"vdup.s8 d27, d12[3] \n"
"vdup.s8 d28, d12[4] \n"
"vext.s8 d7, d6, d6, #1 \n"
"vext.s8 d8, d6, d6, #2 \n"
"vsli.64 d3, d6, #32 \n"// d3 = r10 r20
"vdup.s8 d29, d12[5] \n"
"vmlal.s8 q8, d2, d26 \n"
"vmlal.s8 q9, d3, d27 \n"
"vsli.64 d4, d7, #32 \n"// d4 = r11 r21
"vsli.64 d5, d8, #32 \n"// d5 = r12 r22
/// r30 r31 r32
"vld1.s8 {d9}, [%5] \n"// d9 = r30 r30n
"add %5, #4 \n"
"vdup.s8 d30, d12[6] \n"
"vdup.s8 d31, d12[7] \n"
"vmlal.s8 q8, d4, d28 \n"
"vmlal.s8 q9, d5, d29 \n"
"vext.s8 d10, d9, d9, #1 \n"
"vext.s8 d11, d9, d9, #2 \n"
"vsli.64 d6, d9, #32 \n"// d6 = r20 r30
"vsli.64 d7, d10, #32 \n"// d7 = r21 r31
"vmlal.s8 q8, d6, d30 \n"
"vmlal.s8 q9, d7, d31 \n"
"vld1.s8 {d13[]}, [%6]! \n"
"vsli.64 d8, d11, #32 \n"// d8 = r22 r32
"vmlal.s8 q8, d8, d13 \n"
///
"vld1.s32 {d0-d1}, [%0] \n"
"vadd.s16 q8, q8, q9 \n"
"vld1.s32 {d2-d3}, [%1] \n"
"vaddw.s16 q0, q0, d16 \n"
"vaddw.s16 q1, q1, d17 \n"
"sub %6, #9 \n"
"vst1.s32 {d0-d1}, [%0]! \n"
"vst1.s32 {d2-d3}, [%1]! \n"
: "=r"(outptr0), // %0
"=r"(outptr0n), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(r3), // %5
"=r"(ktmp) // %6
: "0"(outptr0),
"1"(outptr0n),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(r3),
"6"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
);
}
#endif
for (; remain>0; remain--)
{
#if __ARM_NEON
asm volatile(
"vld1.s8 {d0[0]}, [%2]! \n"
"vld1.s8 {d0[1]}, [%2]! \n"
"vld1.s8 {d0[2]}, [%2] \n"
"sub %2, #2 \n"
"vld1.s8 {d0[3]}, [%3]! \n"
"vld1.s8 {d0[4]}, [%3]! \n"
"vld1.s8 {d0[5]}, [%3] \n"
"sub %3, #2 \n"
"vld1.s8 {d0[6]}, [%4]! \n"
"vld1.s8 {d0[7]}, [%4]! \n"// d0=r
"vld1.s8 {d4[]}, [%4] \n"// d4=r22
"sub %4, #2 \n"
"vext.s8 d1, d0, d4, #3 \n"
"vld1.s8 {d1[6]}, [%5]! \n"
"vld1.s8 {d1[7]}, [%5]! \n"// d1=rn
"vld1.s8 {d2}, [%6]! \n"// d2=k01234567
"vld1.s8 {d5[]}, [%5] \n"// d5=r32
"sub %5, #2 \n"
"veor d3, d3 \n"
"vmull.s8 q8, d0, d2 \n"
"vmull.s8 q9, d1, d2 \n"
"vld1.s8 {d3[0]}, [%6] \n"// d3=k8 ... zeros
"sub %6, #8 \n"
"vmlal.s8 q8, d4, d3 \n"
"vmlal.s8 q9, d5, d3 \n"
"vld1.s32 {d6[0]}, [%0] \n"
"vadd.s16 d16, d16, d17 \n"
"vadd.s16 d18, d18, d19 \n"
"vld1.s32 {d6[1]}, [%1] \n"
"vpadd.s16 d16, d16, d18 \n"
"vpadal.s16 d6, d16 \n"
"vst1.s32 {d6[0]}, [%0]! \n"
"vst1.s32 {d6[1]}, [%1]! \n"
: "=r"(outptr0), // %0
"=r"(outptr0n), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2), // %4
"=r"(r3), // %5
"=r"(ktmp) // %6
: "0"(outptr0),
"1"(outptr0n),
"2"(r0),
"3"(r1),
"4"(r2),
"5"(r3),
"6"(ktmp)
: "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9"
);
#else
int sum0 = 0;
int sum0n = 0;
sum0 += r0[0] * ktmp[0];
sum0 += r0[1] * ktmp[1];
sum0 += r0[2] * ktmp[2];
sum0 += r1[0] * ktmp[3];
sum0 += r1[1] * ktmp[4];
sum0 += r1[2] * ktmp[5];
sum0 += r2[0] * ktmp[6];
sum0 += r2[1] * ktmp[7];
sum0 += r2[2] * ktmp[8];
sum0n += r1[0] * ktmp[0];
sum0n += r1[1] * ktmp[1];
sum0n += r1[2] * ktmp[2];
sum0n += r2[0] * ktmp[3];
sum0n += r2[1] * ktmp[4];
sum0n += r2[2] * ktmp[5];
sum0n += r3[0] * ktmp[6];
sum0n += r3[1] * ktmp[7];
sum0n += r3[2] * ktmp[8];
*outptr0 += sum0;
*outptr0n += sum0n;
outptr0++;
outptr0n++;
#endif
r0++;
r1++;
r2++;
r3++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr0 += outw;
outptr0n += outw;
}
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 (nn > 0)
{
asm volatile(
"0: \n"
"pld [%2, #128] \n"
"vld1.s8 {d4-d5}, [%2] \n"// d4=r00 d5=r00n
"add %2, #8 \n"
"vext.s8 d8, d4, d5, #1 \n"// d8=r01
"vmull.s8 q8, d4, %P10 \n"
"vext.s8 d9, d4, d5, #2 \n"// d9=r02
"vmull.s8 q9, d8, %P11 \n"
"pld [%3, #128] \n"
"vld1.s8 {d6-d7}, [%3] \n"// d6=r10 d7=r10n
"add %3, #8 \n"
"vmlal.s8 q8, d9, %P12 \n"
"vext.s8 d10, d6, d7, #1 \n"// d10=r11
"vmlal.s8 q9, d6, %P13 \n"
"vext.s8 d11, d6, d7, #2 \n"// d11=r12
"vmlal.s8 q8, d10, %P14 \n"
"pld [%4, #128] \n"
"vld1.s8 {d4-d5}, [%4] \n"// d4=r20 d5=r20n
"add %4, #8 \n"
"vmlal.s8 q9, d11, %P15 \n"
"vext.s8 d8, d4, d5, #1 \n"// d8=r21
"vmlal.s8 q8, d4, %P16 \n"
"vext.s8 d9, d4, d5, #2 \n"// d9=r22
"vmlal.s8 q9, d8, %P17 \n"
"vmlal.s8 q8, d9, %P18 \n"
"pld [%1, #256] \n"
"vld1.s32 {d0-d3}, [%1] \n"
"vadd.s16 q8, q8, q9 \n"
"vaddw.s16 q0, q0, d16 \n"
"vaddw.s16 q1, q1, d17 \n"
"subs %0, #1 \n"
"vst1.s32 {d0-d3}, [%1]! \n"
"bne 0b \n"
: "=r"(nn), // %0
"=r"(outptr0), // %1
"=r"(r0), // %2
"=r"(r1), // %3
"=r"(r2) // %4
: "0"(nn),
"1"(outptr0),
"2"(r0),
"3"(r1),
"4"(r2),
"w"(_k00), // %10
"w"(_k01), // %11
"w"(_k02), // %12
"w"(_k10), // %13
"w"(_k11), // %14
"w"(_k12), // %15
"w"(_k20), // %16
"w"(_k21), // %17
"w"(_k22) // %18
: "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q8", "q9"
);
}
#endif
for (; remain>0; remain--)
{
int sum0 = 0;
sum0 += r0[0] * ktmp[0];
sum0 += r0[1] * ktmp[1];
sum0 += r0[2] * ktmp[2];
sum0 += r1[0] * ktmp[3];
sum0 += r1[1] * ktmp[4];
sum0 += r1[2] * ktmp[5];
sum0 += r2[0] * ktmp[6];
sum0 += r2[1] * ktmp[7];
sum0 += r2[2] * ktmp[8];
*outptr0 += sum0;
r0++;
r1++;
r2++;
outptr0++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
ktmp += 9;
}
}
}
static void conv3x3s2_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt)
{
int outw = top_blob.w;
int remain = outw & 7;
typedef void (*conv_func_int8)(const Mat&, Mat&, const Mat&, const Option&);
conv_func_int8 conv_func_table[8] =
{
conv3x3s2_neon_s8, //0
conv3x3s2_neon_s8, //1
conv3x3s2_neon_s8, //2
conv3x3s2_neon_s8, //3
conv3x3s2_neon_s8, //4
conv3x3s2_neon_s8, //5
conv3x3s2_neon_s8, //6
conv3x3s2_neon_s8, //7
};
conv_func_int8 conv = conv_func_table[remain];
conv(bottom_blob, top_blob, _kernel, opt);
return;
}
#endif
|
estimator.h | // Copyright (C) 2013 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#ifndef THEIA_SOLVERS_ESTIMATOR_H_
#define THEIA_SOLVERS_ESTIMATOR_H_
#include <glog/logging.h>
#ifdef THEIA_USE_OPENMP
#include <omp.h>
#endif
#include <vector>
namespace theia {
// Templated class for estimating a model for RANSAC. This class is purely a
// virtual class and should be implemented for the specific task that RANSAC is
// being used for. Two methods must be implemented: EstimateModel and Error. All
// other methods are optional, but will likely enhance the quality of the RANSAC
// output.
//
// NOTE: RANSAC, ARRSAC, and other solvers work best if Datum and Model are
// lightweight classes or structs.
template <class Datum, class Model> class Estimator {
public:
Estimator() {}
virtual ~Estimator() {}
// Given a set of data points, estimate the model. Users should implement this
// function appropriately for the task being solved. Returns true for
// successful model estimation (and outputs model), false for failed
// estimation. Typically, this is a minimal set, but it is not required to be.
virtual bool EstimateModel(const std::vector<Datum>& data,
std::vector<Model>* model) const = 0;
// Estimate a model from a non-minimal sampling of the data. E.g. for a line,
// use SVD on a set of points instead of constructing a line from two points.
// By default, this simply implements the minimal case.
virtual bool EstimateModelNonminimal(const std::vector<Datum>& data,
std::vector<Model>* model) const {
return EstimateModel(data, model);
}
// Refine the model based on an updated subset of data, and a pre-computed
// model. Can be optionally implemented.
virtual bool RefineModel(const std::vector<Datum>& data, Model* model) const {
return true;
}
// Given a model and a data point, calculate the error. Users should implement
// this function appropriately for the task being solved.
virtual double Error(const Datum& data, const Model& model) const = 0;
// Compute the residuals of many data points. By default this is just a loop
// that calls Error() on each data point, but this function can be useful if
// the errors of multiple points may be estimated simultanesously (e.g.,
// matrix multiplication to compute the reprojection error of many points at
// once).
virtual std::vector<double> Residuals(const std::vector<Datum>& data,
const Model& model) const {
std::vector<double> residuals(data.size());
#pragma omp parallel for
for (int i = 0; i < data.size(); i++) {
residuals[i] = Error(data[i], model);
}
return residuals;
}
// Returns the set inliers of the data set based on the error threshold
// provided.
std::vector<bool> GetInliers(const std::vector<Datum>& data,
const Model& model,
double error_threshold) const {
std::vector<bool> inliers;
for (const Datum& data_point : data)
inliers.push_back(Error(data_point, model) < error_threshold);
return inliers;
}
// Returns the number inliers of the data set based on the error threshold
// provided.
int GetNumInliers(const std::vector<Datum>& data, const Model& model,
double error_threshold) const {
int num_inliers = 0;
for (const Datum& data_point : data)
if (Error(data_point, model) < error_threshold) num_inliers++;
return num_inliers;
}
// Enable a quick check to see if the model is valid. This can be a geometric
// check or some other verification of the model structure.
virtual bool ValidModel(const Model& model) const { return true; }
};
} // namespace theia
#endif // THEIA_SOLVERS_ESTIMATOR_H_
|
prepress.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP RRRR EEEEE PPPP RRRR EEEEE SSSSS SSSSS %
% P P R R E P P R R E SS SS %
% PPPP RRRR EEE PPPP RRRR EEE SSS SSS %
% P R R E P R R E SS SS %
% P R R EEEEE P R R EEEEE SSSSS SSSSS %
% %
% %
% MagickCore Prepress Methods %
% %
% Software Design %
% John Cristy %
% October 2001 %
% %
% %
% Copyright 1999-2013 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/cache-view.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/hashmap.h"
#include "magick/image.h"
#include "magick/list.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/prepress.h"
#include "magick/registry.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/splay-tree.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e T o t a l I n k D e n s i t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageTotalInkDensity() returns the total ink density for a CMYK image.
% Total Ink Density (TID) is determined by adding the CMYK values in the
% darkest shadow area in an image.
%
% The format of the GetImageTotalInkDensity method is:
%
% double GetImageTotalInkDensity(const Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport double GetImageTotalInkDensity(Image *image)
{
CacheView
*image_view;
double
total_ink_density;
ExceptionInfo
*exception;
MagickBooleanType
status;
ssize_t
y;
assert(image != (Image *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(image->signature == MagickSignature);
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
ImageError,"ColorSeparatedImageRequired","`%s'",image->filename);
return(0.0);
}
status=MagickTrue;
total_ink_density=0.0;
exception=(&image->exception);
image_view=AcquireVirtualCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
density;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
density=(double) GetPixelRed(p)+GetPixelGreen(p)+
GetPixelBlue(p)+GetPixelIndex(indexes+x);
if (density > total_ink_density)
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_GetImageTotalInkDensity)
#endif
{
if (density > total_ink_density)
total_ink_density=density;
}
p++;
}
}
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
total_ink_density=0.0;
return(total_ink_density);
}
|
parallel.h | #pragma once
//***************************************
// All the pbbs library uses only four functions for
// accessing parallelism.
// These can be implemented on top of any scheduler.
//***************************************
// number of threads available from OS
// template <>
int num_workers();
// id of running thread, should be numbered from [0...num-workers)
int worker_id();
void set_num_workers(int n);
// the granularity of a simple loop (e.g. adding one to each element
// of an array) to reasonably hide cost of scheduler
// #define PAR_GRANULARITY 2000
// parallel loop from start (inclusive) to end (exclusive) running
// function f.
// f should map long to void.
// granularity is the number of iterations to run sequentially
// if 0 (default) then the scheduler will decide
// conservative uses a safer scheduler
template <typename F>
static void parallel_for(long start, long end, F f, long granularity = 0,
bool conservative = false);
// runs the thunks left and right in parallel.
// both left and write should map void to void
// conservative uses a safer scheduler
template <typename Lf, typename Rf>
static void par_do(Lf left, Rf right, bool conservative = false);
template <typename A, typename Af, typename Df, typename F>
static void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity = 0,
bool conservative = false);
//***************************************
// cilkplus
#if defined(CILK)
#include <cilk/cilk.h>
#include <cilk/cilk_api.h>
#include <cilk/reducer.h>
#include <iostream>
#include <sstream>
#define PAR_GRANULARITY 2000
template <typename F>
inline void parallel_for(long start, long end, F f, long granularity,
bool conservative) {
if (granularity == 0)
cilk_for(long i = start; i < end; i++) f(i);
else if ((end - start) <= granularity)
for (long i = start; i < end; i++) f(i);
else {
long n = end - start;
long mid = (start + (9 * (n + 1)) / 16);
cilk_spawn parallel_for(start, mid, f, granularity);
parallel_for(mid, end, f, granularity);
cilk_sync;
}
}
template <typename F>
inline void parallel_for_1(long start, long end, F f, long granularity,
bool conservative) {
_Pragma("cilk grainsize = 1") cilk_for(long i = start; i < end; i++) f(i);
}
template <typename Lf, typename Rf>
inline void par_do(Lf left, Rf right, bool conservative) {
cilk_spawn right();
left();
cilk_sync;
}
template <typename A>
class alloc_holder {
struct Monoid : cilk::monoid_base<A> {
static void reduce(A *left, A *right) {}
};
public:
cilk::reducer<Monoid> imp_;
alloc_holder() : imp_() {}
};
// TODO try parallel_for_1
template <typename A, typename Af, typename Df, typename F>
inline void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity,
bool conservative) {
alloc_holder<A> alloc;
parallel_for_1(start, end,
[&](size_t i) {
init_alloc(&alloc.imp_.view());
f(i, &(alloc.imp_.view()));
// finish_alloc(&(alloc.imp_.view()));
},
granularity, conservative);
}
// openmp
#elif defined(OPENMP)
#include <omp.h>
#define PAR_GRANULARITY 200000
template <class F>
inline void parallel_for(long start, long end, F f, long granularity,
bool conservative) {
_Pragma("omp parallel for") for (long i = start; i < end; i++) f(i);
}
template <typename F>
inline void parallel_for_1(long start, long end, F f, long granularity,
bool conservative) {
#pragma omp for schedule(dynamic, 1) nowait
for (long i = start; i < end; i++) f(i);
}
bool in_par_do = false;
template <typename Lf, typename Rf>
inline void par_do(Lf left, Rf right, bool conservative) {
if (!in_par_do) {
in_par_do = true; // at top level start up tasking
#pragma omp parallel
#pragma omp single
#pragma omp task
left();
#pragma omp task
right();
#pragma omp taskwait
in_par_do = false;
} else { // already started
#pragma omp task
left();
#pragma omp task
right();
}
}
template <typename Job>
inline void parallel_run(Job job, int num_threads = 0) {
job();
}
template <typename A, typename Af, typename Df, typename F>
inline void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity,
bool conservative) {
A* alloc = nullptr;
#pragma omp parallel private(alloc)
{
alloc = new A();
init_alloc(alloc);
parallel_for_1(start, end, [&](size_t i) { f(i, alloc); }, granularity,
conservative);
//#pragma omp for schedule(dynamic, 1) nowait
// for(long i=start; i<end; i++) f(i, alloc);
finish_alloc(alloc);
}
}
// Guy's scheduler (ABP)
#elif defined(HOMEGROWN)
#include "scheduler.h"
#define PAR_GRANULARITY 512
template <class F>
inline void parallel_for(long start, long end, F f, long granularity,
bool conservative) {
global_scheduler.parfor(start, end, f, granularity, conservative);
}
template <typename Lf, typename Rf>
inline void par_do(Lf left, Rf right, bool conservative) {
return global_scheduler.pardo(left, right, conservative);
}
template <typename Job>
inline void parallel_run(Job job, int num_threads = 0) {
job();
}
template <typename A, typename Af, typename Df, typename F>
inline void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity,
bool conservative) {
parallel_for(start, end,
[&](long i) {
static thread_local A* alloc = new A();
init_alloc(alloc);
f(i, alloc);
},
granularity, conservative);
// finish_alloc(alloc);
}
// c++
#else
#define PAR_GRANULARITY 1000
template <class F>
inline void parallel_for(long start, long end, F f, long granularity,
bool conservative) {
for (long i = start; i < end; i++) {
f(i);
}
}
template <typename Lf, typename Rf>
inline void par_do(Lf left, Rf right, bool conservative) {
left();
right();
}
template <typename Job>
inline void parallel_run(Job job, int num_threads = 0) {
job();
}
template <typename A, typename Af, typename Df, typename F>
inline void parallel_for_alloc(Af init_alloc, Df finish_alloc, long start,
long end, F f, long granularity,
bool conservative) {
A* alloc = new A();
init_alloc(alloc);
for (long i = start; i < end; i++) {
f(i, alloc);
}
finish_alloc(alloc);
}
#endif
|
nndes.h | /*
Copyright (C) 2010,2011 Wei Dong <wdong@wdong.org>
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WDONG_NNDESCENT
#define WDONG_NNDESCENT
#include "nndes-common.h"
#include "ported_boost_progress.h"
namespace similarity {
using std::cout;
using std::unique_ptr;
using std::vector;
using std::swap;
#ifndef NNDES_SHOW_PROGRESS
#define NNDES_SHOW_PROGRESS 1
#endif
// Normally one would use GRAPH_BOTH,
// GRAPH_KNN & GRAPH_RNN are for experiments only.
static const int GRAPH_NONE = 0, GRAPH_KNN = 1, GRAPH_RNN = 2, GRAPH_BOTH = 4;
typedef int GraphOption;
// The main NN-Descent class.
// Instead of the actual dataset, the class takes a distance oracle
// as input. Given two data item ids, the oracle returns the distance
// between the two.
template <typename ORACLE>
class NNDescent {
private:
const ORACLE &oracle;
int N; // # points
int K; // K-NN to find
int S; // # of NNs to use for exploration
GraphOption option;
vector<KNN> nn; // K-NN approximation
// We maintain old and newly added KNN/RNN items
// separately for incremental processing:
// we need to compare two new ones
// and a new one to an old one, but not two old ones as they
// must have been compared already.
vector<vector<int> > nn_old;
vector<vector<int> > nn_new;
vector<vector<int> > rnn_old;
vector<vector<int> > rnn_new;
// total number of comparisons done.
long long int cost;
// This function decides of it's necessary to compare two
// points. Obviously a point should not compare against itself.
// Another potential usage of this function is to record all
// pairs that have already be compared, so that when seen in the future,
// then same pair doesn't have be compared again.
bool mark (int p1, int p2) {
return p1 == p2;
}
// Compare two points and update their KNN list of necessary.
// Return the number of comparisons done (0 or 1).
int update (int p1, int p2) {
if (mark(p1, p2)) return 0;
// KNN::update is synchronized by a lock
// keep an order is necessary to avoid deadlock.
if (p1 > p2) swap(p1, p2);
float dist = oracle(p1, p2);
nn[p1].update(KNN::Element(p2, dist, true));
nn[p2].update(KNN::Element(p1, dist, true));
return 1;
}
public:
const vector<KNN> &getNN() const {
return nn;
}
long long int getCost () const {
return cost;
}
NNDescent (int N_, int K_, float S_, const ORACLE &oracle_,
GraphOption opt = GRAPH_BOTH)
: oracle(oracle_), N(N_), K(K_), S(K * S_), option(opt), nn(N_),
nn_old(N_), nn_new(N_), rnn_old(N_), rnn_new(N_), cost(0)
{
for (int i = 0; i < N; ++i) {
nn[i].init(K);
// random initial edges
if ((option & GRAPH_KNN) || (option & GRAPH_BOTH)) {
nn_new[i].resize(S);
BOOST_FOREACH(int &u, nn_new[i]) {
u = RandomInt() % N;
}
}
if ((option & GRAPH_RNN) || (option & GRAPH_BOTH)) {
rnn_new[i].resize(S);
BOOST_FOREACH(int &u, rnn_new[i]) {
u = RandomInt() % N;
}
}
}
}
// An iteration contains two parts:
// local join
// identify the newly detected NNs.
int iterate (bool PrintProgress) {
#if NNDES_SHOW_PROGRESS
unique_ptr<ProgressDisplay> progress(
PrintProgress? new ProgressDisplay(N, cerr): NULL);
#endif
long long int cc = 0;
// local joins
#pragma omp parallel for default(shared) reduction(+:cc)
for (int i = 0; i < N; ++i) {
// The following loops are bloated to deal with all
// the experimental setups. Otherwise they should
// be really simple.
if (option & (GRAPH_KNN | GRAPH_BOTH)) {
BOOST_FOREACH(int j, nn_new[i]) {
BOOST_FOREACH(int k, nn_new[i]) {
if (j >= k) continue;
cc += update(j, k);
}
BOOST_FOREACH(int k, nn_old[i]) {
cc += update(j, k);
}
}
}
if (option & (GRAPH_RNN | GRAPH_BOTH)) {
BOOST_FOREACH(int j, rnn_new[i]) {
BOOST_FOREACH(int k, rnn_new[i]) {
if (j >= k) continue;
cc += update(j, k);
}
BOOST_FOREACH(int k, rnn_old[i]) {
cc += update(j, k);
}
}
}
if (option & GRAPH_BOTH) {
BOOST_FOREACH(int j, nn_new[i]) {
BOOST_FOREACH(int k, rnn_old[i]) {
cc += update(j, k);
}
BOOST_FOREACH(int k, rnn_new[i]) {
cc += update(j, k);
}
}
BOOST_FOREACH(int j, nn_old[i]) {
BOOST_FOREACH(int k, rnn_new[i]) {
cc += update(j, k);
}
}
}
#if NNDES_SHOW_PROGRESS
#pragma omp critical
if (progress) ++(*progress);
#endif
}
cost += cc;
int t = 0;
//#pragma omp parallel for default(shared) reduction(+:t)
for (int i = 0; i < N; ++i) {
nn_old[i].clear();
nn_new[i].clear();
rnn_old[i].clear();
rnn_new[i].clear();
// find the new ones
for (int j = 0; j < K; ++j) {
KNN::Element &e = nn[i][j];
if (e.key == KNN::Element::BAD) continue;
if (e.flag){
nn_new[i].push_back(j);
}
else {
nn_old[i].push_back(e.key);
}
}
t += nn_new[i].size();
// sample
if (nn_new[i].size() > unsigned(S)) {
random_shuffle(nn_new[i].begin(), nn_new[i].end());
nn_new[i].resize(S);
}
BOOST_FOREACH(int &v, nn_new[i]) {
nn[i][v].flag = false;
v = nn[i][v].key;
}
}
// symmetrize
if ((option & GRAPH_RNN) || (option & GRAPH_BOTH)) {
for (int i = 0; i < N; ++i) {
BOOST_FOREACH(int e, nn_old[i]) {
rnn_old[e].push_back(i);
}
BOOST_FOREACH(int e, nn_new[i]) {
rnn_new[e].push_back(i);
}
}
}
//#pragma omp parallel for default(shared) reduction(+:t)
for (int i = 0; i < N; ++i) {
if (rnn_old[i].size() > unsigned(S)) {
random_shuffle(rnn_old[i].begin(), rnn_old[i].end());
rnn_old[i].resize(S);
}
if (rnn_new[i].size() > unsigned(S)) {
random_shuffle(rnn_new[i].begin(), rnn_new[i].end());
rnn_new[i].resize(S);
}
}
return t;
}
};
}
#endif
|
3d7pt_var.c | /*
* Order-1, 3D 7 point stencil with variable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*7);
for(m=0; m<7;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 4;
tile_size[1] = 4;
tile_size[2] = 32;
tile_size[3] = 1024;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<7; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt-1; t++) {
for (i = 1; i < Nz-1; i++) {
for (j = 1; j < Ny-1; j++) {
for (k = 1; k < Nx-1; k++) {
A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] +
coef[1][i][j][k] * A[t%2][i-1][j ][k ] +
coef[2][i][j][k] * A[t%2][i ][j-1][k ] +
coef[3][i][j][k] * A[t%2][i ][j ][k-1] +
coef[4][i][j][k] * A[t%2][i+1][j ][k ] +
coef[5][i][j][k] * A[t%2][i ][j+1][k ] +
coef[6][i][j][k] * A[t%2][i ][j ][k+1];
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "variable no-symmetry")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<7;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
3d25pt.c | /*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 8;
tile_size[1] = 8;
tile_size[2] = 8;
tile_size[3] = 512;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#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] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*(
coef0* A[t%2][i ][j ][k ] +
coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] +
A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] +
A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) +
coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] +
A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] +
A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) +
coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] +
A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] +
A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) +
coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] +
A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][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, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
taskgroup.c | //===-- taskgroup.c - Example for the "taskgroup" construct -------*- C -*-===//
//
// Part of the LOMP Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <stdio.h>
#include <unistd.h>
#include <omp.h>
#define NTASKS 32
void produce(double d) {
for (int i = 0; i < NTASKS; i++) {
// create a new task to for another thread to steal
printf("%d: creating task\n", omp_get_thread_num());
#pragma omp task firstprivate(i) firstprivate(d)
{
double answer = i * d;
printf("%d: Hello from task %d and the answer is %lf\n",
omp_get_thread_num(), i, answer);
}
}
}
int main(void) {
double d = 42.0;
#pragma omp parallel
{
#pragma omp master
{
#pragma omp taskgroup
{ produce(d); }
printf("After the taskgroup\n");
}
}
return 0;
}
|
nco_s1d.c | /* $Header$ */
/* Purpose: NCO utilities for Sparse-1D (S1D) datasets */
/* Copyright (C) 2015--present Charlie Zender
This file is part of NCO, the netCDF Operators. NCO is free software.
You may redistribute and/or modify NCO under the terms of the
3-Clause BSD License with exceptions described in the LICENSE file */
#include "nco_s1d.h" /* Sparse-1D datasets */
const char * /* O [sng] String describing sparse-type */
nco_s1d_sng /* [fnc] Convert sparse-1D type enum to string */
(const nco_s1d_typ_enm nco_s1d_typ) /* I [enm] Sparse-1D type enum */
{
/* Purpose: Convert sparse-type enum to string */
switch(nco_s1d_typ){
case nco_s1d_clm: return "Sparse Column (cols1d) format";
case nco_s1d_grd: return "Sparse Gridcell (grid1d) format";
case nco_s1d_lnd: return "Sparse Landunit (land1d) format";
case nco_s1d_pft: return "Sparse PFT (pfts1d) format" ;
default: nco_dfl_case_generic_err(); break;
} /* !nco_s1d_typ_enm */
/* Some compilers: e.g., SGI cc, need return statement to end non-void functions */
return (char *)NULL;
} /* !nco_s1d_sng() */
int /* O [rcd] Return code */
nco_s1d_unpack /* [fnc] Unpack sparse-1D CLM/ELM variables into full file */
(rgr_sct * const rgr, /* I/O [sct] Regridding structure */
trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal Table */
{
/* Purpose: Read sparse CLM/ELM input file, inflate and write into output file */
/* Usage:
ncks -O -C --s1d -v cols1d_topoglc ~/data/bm/elm_mali_rst.nc ~/foo.nc
ncks -O -C --s1d -v cols1d_topoglc --hrz=${DATA}/bm/elm_mali_ig_hst.nc ${DATA}/bm/elm_mali_rst.nc ~/foo.nc */
const char fnc_nm[]="nco_s1d_unpack()"; /* [sng] Function name */
char var_nm[NC_MAX_NAME+1L];
char *fl_in;
char *fl_out;
char *fl_tpl; /* [sng] Template file (contains horizontal grid) */
char dmn_nm[NC_MAX_NAME]; /* [sng] Dimension name */
char *grd_nm_in=(char *)strdup("gridcell");
char *lnd_nm_in=(char *)strdup("landunit");
char *clm_nm_in=(char *)strdup("column");
char *pft_nm_in=(char *)strdup("pft");
int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */
int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */
int fll_md_old; /* [enm] Old fill mode */
int in_id; /* I [id] Input netCDF file ID */
int md_open; /* [enm] Mode flag for nc_open() call */
int out_id; /* I [id] Output netCDF file ID */
int rcd=NC_NOERR;
int tpl_id; /* [id] Input netCDF file ID (for horizontal grid template) */
int dmn_idx; /* [idx] Dimension index */
/* Initialize local copies of command-line values */
dfl_lvl=rgr->dfl_lvl;
fl_in=rgr->fl_in;
fl_out=rgr->fl_out;
in_id=rgr->in_id;
out_id=rgr->out_id;
/* Search for horizontal grid */
char *col_nm_in=rgr->col_nm_in; /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */
char *lat_nm_in=rgr->lat_nm_in; /* [sng] Name of input dimension to recognize as latitude */
char *lon_nm_in=rgr->lon_nm_in; /* [sng] Name of input dimension to recognize as longitude */
int dmn_id_col_in=NC_MIN_INT; /* [id] Dimension ID */
int dmn_id_lat_in=NC_MIN_INT; /* [id] Dimension ID */
int dmn_id_lon_in=NC_MIN_INT; /* [id] Dimension ID */
nco_bool FL_RTR_RMT_LCN;
nco_bool flg_grd_1D=False; /* [flg] Unpacked data are on unstructured (1D) grid */
nco_bool flg_grd_rct=False; /* [flg] Unpacked data are on rectangular (2D) grid */
nco_bool flg_grd_dat=False; /* [flg] Use horizontal grid from required input data file */
nco_bool flg_grd_tpl=False; /* [flg] Use horizontal grid from optional horizontal grid template file */
/* Does data file have unstructured grid?
MB: Routine must handle two semantically distinct meanings of "column":
1. The horizontal dimension in an unstructured grid
2. A fraction of a landunit, which is a fraction of a CTSM/ELM gridcell
In particular, a column is a fraction of a vegetated, urban, glacier, or crop landunit
This routine distinguishes these meanings by abbreviating (1) as "col" and (2) as "clm"
This usage maintains the precedent that "col" is the horizontal unstructured dimension in nco_rgr.c
It is necessary though unintuitive that "cols1d" variable metadata will use the "clm" abbreviation */
if(col_nm_in && (rcd=nco_inq_dimid_flg(in_id,col_nm_in,&dmn_id_col_in)) == NC_NOERR) /* do nothing */;
else if((rcd=nco_inq_dimid_flg(in_id,"lndgrid",&dmn_id_col_in)) == NC_NOERR) col_nm_in=strdup("lndgrid"); /* CLM */
if(dmn_id_col_in != NC_MIN_INT) flg_grd_1D=True;
/* Does data file have RLL grid? */
if(!flg_grd_1D){
if(lat_nm_in && (rcd=nco_inq_dimid_flg(in_id,lat_nm_in,&dmn_id_lat_in)) == NC_NOERR) /* do nothing */;
else if((rcd=nco_inq_dimid_flg(in_id,"latitude",&dmn_id_lat_in)) == NC_NOERR) lat_nm_in=strdup("lndgrid"); /* CF */
if(lon_nm_in && (rcd=nco_inq_dimid_flg(in_id,lon_nm_in,&dmn_id_lon_in)) == NC_NOERR) /* do nothing */;
else if((rcd=nco_inq_dimid_flg(in_id,"longitude",&dmn_id_lon_in)) == NC_NOERR) lon_nm_in=strdup("lndgrid"); /* CF */
} /* !flg_grd_1D */
if(dmn_id_lat_in != NC_MIN_INT && dmn_id_lon_in != NC_MIN_INT) flg_grd_rct=True;
/* Set where to obtain horizontal grid */
if(flg_grd_1D || flg_grd_rct) flg_grd_dat=True; else flg_grd_tpl=True;
if(flg_grd_tpl && !rgr->fl_hrz){
(void)fprintf(stderr,"%s: ERROR %s did not locate horizontal grid in input data file and no optional horizontal gridfile was provided.\nHINT: Use option --hrz to specify file with horizontal grid used by input data.\n",nco_prg_nm_get(),fnc_nm);
nco_exit(EXIT_FAILURE);
} /* !flg_grd_tpl */
/* Open grid template file iff necessary */
if(flg_grd_tpl && rgr->fl_hrz){
char *fl_pth_lcl=NULL;
nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */
nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */
nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */
size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */
/* Duplicate (because nco_fl_mk_lcl() free()'s its fl_in) */
fl_tpl=(char *)strdup(rgr->fl_hrz);
/* Make sure file is on local system and is readable or die trying */
fl_tpl=nco_fl_mk_lcl(fl_tpl,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN);
/* Open file using appropriate buffer size hints and verbosity */
if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE;
if(SHARE_OPEN) md_open=md_open|NC_SHARE;
rcd+=nco_fl_open(fl_tpl,md_open,&bfr_sz_hnt,&tpl_id);
/* Same logic used to search for grid in data file and to search for grid in template file...
Does template file have unstructured grid? */
if(col_nm_in && (rcd=nco_inq_dimid_flg(tpl_id,col_nm_in,&dmn_id_col_in)) == NC_NOERR) /* do nothing */;
else if((rcd=nco_inq_dimid_flg(tpl_id,"lndgrid",&dmn_id_col_in)) == NC_NOERR) col_nm_in=strdup("lndgrid"); /* CLM */
if(dmn_id_col_in != NC_MIN_INT) flg_grd_1D=True;
/* Does template file have RLL grid? */
if(!flg_grd_1D){
if(lat_nm_in && (rcd=nco_inq_dimid_flg(tpl_id,lat_nm_in,&dmn_id_lat_in)) == NC_NOERR) /* do nothing */;
else if((rcd=nco_inq_dimid_flg(tpl_id,"latitude",&dmn_id_lat_in)) == NC_NOERR) lat_nm_in=strdup("lndgrid"); /* CF */
if(lon_nm_in && (rcd=nco_inq_dimid_flg(tpl_id,lon_nm_in,&dmn_id_lon_in)) == NC_NOERR) /* do nothing */;
else if((rcd=nco_inq_dimid_flg(tpl_id,"longitude",&dmn_id_lon_in)) == NC_NOERR) lon_nm_in=strdup("lndgrid"); /* CF */
} /* !flg_grd_1D */
if(dmn_id_lat_in != NC_MIN_INT && dmn_id_lon_in != NC_MIN_INT) flg_grd_rct=True;
/* Set where to obtain horizontal grid */
if(!flg_grd_1D && !flg_grd_rct){
(void)fprintf(stderr,"%s: ERROR %s did not locate horizontal grid in input data file %s or in template file %s.\nHINT: One of those files must contain the grid dimensions and coordinates used by the packed data in the input data file.\n",nco_prg_nm_get(),fnc_nm,fl_in,fl_tpl);
nco_exit(EXIT_FAILURE);
} /* !flg_grd_1D */
} /* !flg_grd_tpl */
int cols1d_gridcell_index_id=NC_MIN_INT; /* [id] Gridcell index of column */
int cols1d_ixy_id=NC_MIN_INT; /* [id] Column 2D longitude index */
int cols1d_jxy_id=NC_MIN_INT; /* [id] Column 2D latitude index */
int cols1d_lat_id=NC_MIN_INT; /* [id] Column latitude */
int cols1d_lon_id=NC_MIN_INT; /* [id] Column longitude */
int grid1d_ixy_id=NC_MIN_INT; /* [id] Gridcell 2D longitude index */
int grid1d_jxy_id=NC_MIN_INT; /* [id] Gridcell 2D latitude index */
int grid1d_lat_id=NC_MIN_INT; /* [id] Gridcell latitude */
int grid1d_lon_id=NC_MIN_INT; /* [id] Gridcell longitude */
int land1d_gridcell_index_id=NC_MIN_INT; /* [id] Gridcell index of landunit */
int land1d_ixy_id=NC_MIN_INT; /* [id] Landunit 2D longitude index */
int land1d_jxy_id=NC_MIN_INT; /* [id] Landunit 2D latitude index */
int land1d_lat_id=NC_MIN_INT; /* [id] Landunit latitude */
int land1d_lon_id=NC_MIN_INT; /* [id] Landunit longitude */
int pfts1d_gridcell_index_id=NC_MIN_INT; /* [id] Gridcell index of PFT */
int pfts1d_column_index_id=NC_MIN_INT; /* [id] Column index of PFT */
int pfts1d_ixy_id=NC_MIN_INT; /* [id] PFT 2D longitude index */
int pfts1d_jxy_id=NC_MIN_INT; /* [id] PFT 2D latitude index */
int pfts1d_lat_id=NC_MIN_INT; /* [id] PFT latitude */
int pfts1d_lon_id=NC_MIN_INT; /* [id] PFT longitude */
int dmn_id_grd=NC_MIN_INT; /* [id] Dimension ID */
int dmn_id_lnd=NC_MIN_INT; /* [id] Dimension ID */
int dmn_id_clm=NC_MIN_INT; /* [id] Dimension ID */
int dmn_id_pft=NC_MIN_INT; /* [id] Dimension ID */
nco_bool flg_s1d_clm=False; /* [flg] Dataset contains sparse variables for columns */
nco_bool flg_s1d_grd=False; /* [flg] Dataset contains sparse variables for gridcells */
nco_bool flg_s1d_lnd=False; /* [flg] Dataset contains sparse variables for landunits */
nco_bool flg_s1d_pft=False; /* [flg] Dataset contains sparse variables for PFTs */
rcd=nco_inq_varid_flg(in_id,"cols1d_gridcell_index",&cols1d_gridcell_index_id);
if(cols1d_gridcell_index_id != NC_MIN_INT) flg_s1d_clm=True;
if(flg_s1d_clm){
rcd=nco_inq_varid(in_id,"cols1d_ixy",&cols1d_ixy_id);
rcd=nco_inq_varid(in_id,"cols1d_jxy",&cols1d_jxy_id);
rcd=nco_inq_varid(in_id,"cols1d_lat",&cols1d_lat_id);
rcd=nco_inq_varid(in_id,"cols1d_lon",&cols1d_lon_id);
} /* !flg_s1d_clm */
rcd=nco_inq_varid_flg(in_id,"grid1d_lat",&grid1d_lat_id);
if(grid1d_lat_id != NC_MIN_INT) flg_s1d_grd=True;
if(flg_s1d_grd){
rcd=nco_inq_varid(in_id,"grid1d_ixy",&grid1d_ixy_id);
rcd=nco_inq_varid(in_id,"grid1d_jxy",&grid1d_jxy_id);
rcd=nco_inq_varid(in_id,"grid1d_lon",&grid1d_lon_id);
} /* !flg_s1d_grd */
rcd=nco_inq_varid_flg(in_id,"land1d_gridcell_index",&land1d_gridcell_index_id);
if(land1d_gridcell_index_id != NC_MIN_INT) flg_s1d_lnd=True;
if(flg_s1d_lnd){
rcd=nco_inq_varid(in_id,"land1d_ixy",&land1d_ixy_id);
rcd=nco_inq_varid(in_id,"land1d_jxy",&land1d_jxy_id);
rcd=nco_inq_varid(in_id,"land1d_lat",&land1d_lat_id);
rcd=nco_inq_varid(in_id,"land1d_lon",&land1d_lon_id);
} /* !flg_s1d_lnd */
rcd=nco_inq_varid_flg(in_id,"pfts1d_gridcell_index",&pfts1d_gridcell_index_id);
if(pfts1d_gridcell_index_id != NC_MIN_INT) flg_s1d_pft=True;
if(flg_s1d_pft){
rcd=nco_inq_varid(in_id,"pfts1d_column_index",&pfts1d_column_index_id);
rcd=nco_inq_varid(in_id,"pfts1d_ixy",&pfts1d_ixy_id);
rcd=nco_inq_varid(in_id,"pfts1d_jxy",&pfts1d_jxy_id);
rcd=nco_inq_varid(in_id,"pfts1d_lat",&pfts1d_lat_id);
rcd=nco_inq_varid(in_id,"pfts1d_lon",&pfts1d_lon_id);
} /* !flg_s1d_pft */
assert(flg_s1d_clm || flg_s1d_lnd || flg_s1d_pft);
if(flg_s1d_clm) rcd=nco_inq_dimid(in_id,clm_nm_in,&dmn_id_clm);
if(flg_s1d_grd) rcd=nco_inq_dimid(in_id,grd_nm_in,&dmn_id_grd);
if(flg_s1d_lnd) rcd=nco_inq_dimid(in_id,lnd_nm_in,&dmn_id_lnd);
if(flg_s1d_pft) rcd=nco_inq_dimid(in_id,pft_nm_in,&dmn_id_pft);
if(nco_dbg_lvl_get() >= nco_dbg_std){
(void)fprintf(stderr,"%s: INFO %s necessary information to unpack cols1d variables\n",nco_prg_nm_get(),flg_s1d_clm ? "Found all" : "Could not find");
(void)fprintf(stderr,"%s: INFO %s necessary information to unpack lnds1d variables\n",nco_prg_nm_get(),flg_s1d_lnd ? "Found all" : "Could not find");
(void)fprintf(stderr,"%s: INFO %s necessary information to unpack pfts1d variables\n",nco_prg_nm_get(),flg_s1d_pft ? "Found all" : "Could not find");
} /* !dbg */
/* Collect other information from data and template files */
int dmn_nbr_in; /* [nbr] Number of dimensions in input file */
int dmn_nbr_out; /* [nbr] Number of dimensions in output file */
int var_nbr; /* [nbr] Number of variables in file */
rcd=nco_inq(in_id,&dmn_nbr_in,&var_nbr,(int *)NULL,(int *)NULL);
const unsigned int trv_nbr=trv_tbl->nbr; /* [idx] Number of traversal table entries */
int var_cpy_nbr=0; /* [nbr] Number of copied variables */
int var_rgr_nbr=0; /* [nbr] Number of unpacked variables */
int var_xcl_nbr=0; /* [nbr] Number of deleted variables */
int var_crt_nbr=0; /* [nbr] Number of created variables */
long idx; /* [idx] Generic index */
unsigned int idx_tbl; /* [idx] Counter for traversal table */
char *dmn_nm_cp; /* [sng] Dimension name as char * to reduce indirection */
nco_bool has_clm; /* [flg] Contains column dimension */
nco_bool has_grd; /* [flg] Contains gridcell dimension */
nco_bool has_lnd; /* [flg] Contains landunit dimension */
nco_bool has_pft; /* [flg] Contains PFT dimension */
nco_bool need_clm=False; /* [flg] At least one variable to unpack needs column dimension */
nco_bool need_grd=False; /* [flg] At least one variable to unpack needs gridcell dimension */
nco_bool need_lnd=False; /* [flg] At least one variable to unpack needs landunit dimension */
nco_bool need_pft=False; /* [flg] At least one variable to unpack needs PFT dimension */
trv_sct trv; /* [sct] Traversal table object structure to reduce indirection */
/* Define unpacking flag for each variable */
for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){
trv=trv_tbl->lst[idx_tbl];
if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){
dmn_nbr_in=trv_tbl->lst[idx_tbl].nbr_dmn;
has_clm=False;
has_grd=False;
has_lnd=False;
has_pft=False;
for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){
/* Pre-determine flags necessary during next loop */
dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm;
if(!has_clm && clm_nm_in) has_clm=!strcmp(dmn_nm_cp,clm_nm_in);
if(!has_grd && grd_nm_in) has_grd=!strcmp(dmn_nm_cp,grd_nm_in);
if(!has_lnd && lnd_nm_in) has_lnd=!strcmp(dmn_nm_cp,lnd_nm_in);
if(!has_pft && pft_nm_in) has_pft=!strcmp(dmn_nm_cp,pft_nm_in);
} /* !dmn_idx */
/* Unpack variables that contain a sparse-1D dimension */
if(has_clm || has_lnd || has_pft){
trv_tbl->lst[idx_tbl].flg_rgr=True;
var_rgr_nbr++;
if(has_clm) need_clm=True;
if(has_grd) need_grd=True;
if(has_lnd) need_lnd=True;
if(has_pft) need_pft=True;
} /* endif */
assert(!(has_clm && has_lnd));
assert(!(has_clm && has_pft));
assert(!(has_lnd && has_pft));
/* Copy all variables that are not regridded or omitted */
if(!trv_tbl->lst[idx_tbl].flg_rgr) var_cpy_nbr++;
} /* end nco_obj_typ_var */
} /* end idx_tbl */
if(!var_rgr_nbr) (void)fprintf(stdout,"%s: WARNING %s reports no variables fit unpacking criteria. The sparse data unpacker expects at least one variable to unpack, and variables not unpacked are copied straight to output. HINT: If the name(s) of the input sparse-1D dimensions (e.g., \"column\", \"landunit\", and \"pft\") do not match NCO's preset defaults (case-insensitive unambiguous forms and abbreviations of \"column\", \"landunit\", and/or \"pft\", respectively) then change the dimension names that NCO looks for. Instructions are at http://nco.sf.net/nco.html#sparse. For CTSM/ELM sparse-1D coordinate grids, ensure that the \"column\" and \"landunit\" variable names are known with, e.g., \"ncks --rgr column_nm=clm --rgr landunit_nm=lnd\" or \"ncremap -R '--rgr clm=clm --rgr lnd=lnd'\".\n",nco_prg_nm_get(),fnc_nm);
if(nco_dbg_lvl_get() >= nco_dbg_fl){
for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){
trv=trv_tbl->lst[idx_tbl];
if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr) (void)fprintf(stderr,"Unpack %s? %s\n",trv.nm,trv.flg_rgr ? "Yes" : "No");
} /* end idx_tbl */
} /* end dbg */
int hrz_id; /* [id] Horizontal grid netCDF file ID */
long col_nbr; /* [nbr] Number of columns */
long lon_nbr; /* [nbr] Number of longitudes */
long lat_nbr; /* [nbr] Number of latitudes */
if(flg_grd_dat) hrz_id=in_id; else hrz_id=tpl_id;
if(flg_grd_1D) rcd=nco_inq_dimlen(hrz_id,dmn_id_col_in,&col_nbr);
if(flg_grd_rct){
rcd=nco_inq_dimlen(hrz_id,dmn_id_lat_in,&lat_nbr);
rcd=nco_inq_dimlen(hrz_id,dmn_id_lon_in,&lon_nbr);
} /* !flg_grd_rct */
if(flg_grd_tpl){
nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */
/* No further access to template file, close it */
nco_close(tpl_id);
/* Remove local copy of file */
if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_tpl);
} /* !flg_grd_tpl */
/* Lay-out unpacked file */
char *col_nm_out=NULL;
char *lat_nm_out=NULL;
char *lon_nm_out=NULL;
char *lat_dmn_nm_out;
char *lon_dmn_nm_out;
int dmn_id_col_out=NC_MIN_INT; /* [id] Dimension ID */
int dmn_id_lat_out=NC_MIN_INT; /* [id] Dimension ID */
int dmn_id_lon_out=NC_MIN_INT; /* [id] Dimension ID */
int col_out_id; /* [id] Variable ID for column */
int lon_out_id; /* [id] Variable ID for longitude */
int lat_out_id; /* [id] Variable ID for latitude */
if(rgr->col_nm_out) col_nm_out=rgr->col_nm_out; else col_nm_out=col_nm_in;
if(rgr->lat_dmn_nm) lat_dmn_nm_out=rgr->lat_dmn_nm; else lat_dmn_nm_out=lat_nm_in;
if(rgr->lon_dmn_nm) lon_dmn_nm_out=rgr->lon_dmn_nm; else lon_dmn_nm_out=lon_nm_in;
if(rgr->lat_nm_out) lat_nm_out=rgr->lat_nm_out; else lat_nm_out=lat_nm_in;
if(rgr->lon_nm_out) lon_nm_out=rgr->lon_nm_out; else lon_nm_out=lon_nm_in;
/* Define horizontal dimensions before all else */
if(flg_grd_1D){
rcd=nco_def_dim(out_id,col_nm_out,col_nbr,&dmn_id_col_out);
} /* !flg_grd_1D */
if(flg_grd_rct){
rcd=nco_def_dim(out_id,lat_nm_out,lat_nbr,&dmn_id_lat_out);
rcd=nco_def_dim(out_id,lon_nm_out,lon_nbr,&dmn_id_lon_out);
} /* !flg_grd_rct */
/* Pre-allocate dimension ID and cnt/srt space */
int *dmn_id_in=NULL; /* [id] Dimension IDs */
int *dmn_id_out=NULL; /* [id] Dimension IDs */
int dmn_nbr_max; /* [nbr] Maximum number of dimensions variable can have in input or output */
long *dmn_cnt_in=NULL;
long *dmn_cnt_out=NULL;
long *dmn_srt=NULL;
rcd+=nco_inq_ndims(in_id,&dmn_nbr_max);
dmn_id_in=(int *)nco_malloc(dmn_nbr_max*sizeof(int));
dmn_id_out=(int *)nco_malloc(dmn_nbr_max*sizeof(int));
if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt);
dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long));
if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in);
if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out);
dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long));
dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long));
//(void)fprintf(stdout,"%s: DEBUG quark1 dmn_nbr_out = %d, dmn_nbr_ps = %d\n",nco_prg_nm_get(),dmn_nbr_out,dmn_nbr_ps);
int shuffle; /* [flg] Turn-on shuffle filter */
int deflate; /* [flg] Turn-on deflate filter */
deflate=(int)True;
shuffle=NC_SHUFFLE;
dfl_lvl=rgr->dfl_lvl;
fl_out_fmt=rgr->fl_out_fmt;
const int dmn_nbr_0D=0; /* [nbr] Rank of 0-D grid variables (scalars) */
const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */
const nc_type crd_typ_out=NC_DOUBLE;
nc_type var_typ_rgr; /* [enm] Variable type used during regridding */
var_typ_rgr=NC_DOUBLE; /* NB: Perform interpolation in double precision */
if(flg_grd_1D){
rcd+=nco_def_var(out_id,col_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col_out,&col_out_id);
if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,col_out_id,shuffle,deflate,dfl_lvl);
var_crt_nbr++;
} /* !flg_grd_1D */
if(flg_grd_rct){
rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lat_out,&lat_out_id);
if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl);
var_crt_nbr++;
rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lon_out,&lon_out_id);
if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl);
var_crt_nbr++;
} /* !flg_grd_rct */
/* Free pre-allocated array space */
if(dmn_id_in) dmn_id_in=(int *)nco_free(dmn_id_in);
if(dmn_id_out) dmn_id_out=(int *)nco_free(dmn_id_out);
if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt);
if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in);
if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out);
/* Unpack and copy data from input file */
int dmn_idx_col=int_CEWI; /* [idx] Index of column dimension */
int dmn_idx_lat=int_CEWI; /* [idx] Index of latitude dimension */
int dmn_idx_lon=int_CEWI; /* [idx] Index of longitude dimension */
int var_id; /* [id] Current variable ID */
long var_sz; /* [nbr] Size of variable */
nc_type var_typ_in; /* [enm] NetCDF type of input data */
nc_type var_typ_out; /* [enm] NetCDF type of data in output file */
nco_s1d_typ_enm nco_s1d_typ; /* [enm] Sparse-1D type of input variable */
ptr_unn var_val_in;
ptr_unn var_val_out;
#ifdef ENABLE_S1D
#ifdef __GNUG__
# pragma omp parallel for firstprivate(has_clm,has_grd,has_lnd,has_pft,var_val_in,var_val_out) private(dmn_cnt_in,dmn_cnt_out,dmn_id_in,dmn_id_out,dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dmn_nm,dmn_srt,grd_idx,has_mss_val,idx_in,idx_out,idx_tbl,in_id,lvl_idx_in,lvl_idx_out,lvl_nbr_in,lvl_nbr_out,mss_val_dbl,rcd,thr_idx,trv,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ_out,var_typ_rgr) shared(dmn_id_col_in,dmn_id_col_out,dmn_id_pft_in,dmn_id_pft_out,dmn_id_tm_in,flg_s1d_clm,flg_s1d_pft,grd_nbr,idx_dbg,col_nbr_in,col_nbr_out,pft_nbr_in,pft_nbr_out,out_id,xtr_mth)
#endif /* !__GNUG__ */
for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){
trv=trv_tbl->lst[idx_tbl];
thr_idx=omp_get_thread_num();
in_id=trv_tbl->in_id_arr[thr_idx];
#ifdef _OPENMP
if(nco_dbg_lvl_get() >= nco_dbg_grp && !thr_idx && !idx_tbl) (void)fprintf(fp_stdout,"%s: INFO %s reports regrid loop uses %d thread%s\n",nco_prg_nm_get(),fnc_nm,omp_get_num_threads(),(omp_get_num_threads() > 1) ? "s" : "");
if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s: INFO thread = %d, idx_tbl = %d, nm = %s\n",nco_prg_nm_get(),thr_idx,idx_tbl,trv.nm);
#endif /* !_OPENMP */
if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){
if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s%s ",trv.flg_rgr ? "#" : "~",trv.nm);
if(trv.flg_rgr){
/* Interpolate variable */
if(strstr("cols1d",var_nm)){
nco_s1d_typ=nco_s1d_clm;
}else if(strstr("pfts1d",var_nm)){
nco_s1d_typ=nco_s1d_pft;
}else{
(void)fprintf(stderr,"%s: ERROR %s reports variable %s does not appear to be sparse\n",nco_prg_nm_get(),fnc_nm,var_nm);
nco_exit(EXIT_FAILURE);
} /* !strstr() */
if(nco_dbg_lvl_get() >= nco_dbg_std){
(void)fprintf(stderr,"%s: INFO %s reports variable %s is sparse type %s",nco_prg_nm_get(),fnc_nm,var_nm,nco_s1d_sng(nco_s1d_typ));
} /* !dbg */
}else{ /* !trv.flg_rgr */
/* Use standard NCO copy routine for variables that are not regridded
20190511: Copy them only once */
#pragma omp critical
{ /* begin OpenMP critical */
(void)nco_cpy_var_val(in_id,out_id,(FILE *)NULL,(md5_sct *)NULL,trv.nm,trv_tbl);
} /* end OpenMP critical */
} /* !flg_rgr */
} /* !xtr */
} /* end (OpenMP parallel for) loop over idx_tbl */
if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"\n");
if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s completion report: Variables interpolated = %d, copied unmodified = %d, omitted = %d, created = %d\n",nco_prg_nm_get(),fnc_nm,var_rgr_nbr,var_cpy_nbr,var_xcl_nbr,var_crt_nbr);
/* Free output data memory */
#endif /* !ENABLE_S1D */
// if(col_nm_in) col_nm_in=(char *)nco_free(col_nm_in);
if(clm_nm_in) clm_nm_in=(char *)nco_free(clm_nm_in);
if(grd_nm_in) grd_nm_in=(char *)nco_free(grd_nm_in);
if(lnd_nm_in) lnd_nm_in=(char *)nco_free(lnd_nm_in);
if(pft_nm_in) pft_nm_in=(char *)nco_free(pft_nm_in);
return rcd;
} /* !nco_s1d_unpack() */
|
GB_binop__bget_int64.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCUDA_DEV
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__bget_int64)
// A.*B function (eWiseMult): GB (_AemultB_08__bget_int64)
// A.*B function (eWiseMult): GB (_AemultB_02__bget_int64)
// A.*B function (eWiseMult): GB (_AemultB_04__bget_int64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_int64)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__bget_int64)
// C+=b function (dense accum): GB (_Cdense_accumb__bget_int64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_int64)
// C=scalar+B GB (_bind1st__bget_int64)
// C=scalar+B' GB (_bind1st_tran__bget_int64)
// C=A+scalar GB (_bind2nd__bget_int64)
// C=A'+scalar GB (_bind2nd_tran__bget_int64)
// C type: int64_t
// A type: int64_t
// A pattern? 0
// B type: int64_t
// B pattern? 0
// BinaryOp: cij = GB_BITGET (aij, bij, int64_t, 64)
#define GB_ATYPE \
int64_t
#define GB_BTYPE \
int64_t
#define GB_CTYPE \
int64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int64_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int64_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_BITGET (x, y, int64_t, 64) ;
// 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_BGET || GxB_NO_INT64 || GxB_NO_BGET_INT64)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
void GB (_Cdense_ewise3_noaccum__bget_int64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__bget_int64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bget_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
//------------------------------------------------------------------------------
#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
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *restrict Cx = (int64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bget_int64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
int64_t alpha_scalar ;
int64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int64_t *) alpha_scalar_in)) ;
beta_scalar = (*((int64_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__bget_int64)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__bget_int64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__bget_int64)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__bget_int64)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bget_int64)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t *Cx = (int64_t *) Cx_output ;
int64_t x = (*((int64_t *) x_input)) ;
int64_t *Bx = (int64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int64_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_BITGET (x, bij, int64_t, 64) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bget_int64)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int64_t *Cx = (int64_t *) Cx_output ;
int64_t *Ax = (int64_t *) Ax_input ;
int64_t y = (*((int64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int64_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_BITGET (aij, y, int64_t, 64) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_BITGET (x, aij, int64_t, 64) ; \
}
GrB_Info GB (_bind1st_tran__bget_int64)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t x = (*((const int64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int64_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int64_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_BITGET (aij, y, int64_t, 64) ; \
}
GrB_Info GB (_bind2nd_tran__bget_int64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t y = (*((const int64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
array_init_2.c | // Test the handling of two loops under omp for
// watch the loop index replacement (private by default)
// and tje array outlining
#include <stdlib.h>
int main(void)
{
int i, j;
float** u = (float**) malloc( 500 * sizeof( float*) );
for( i=0; i<500; i++)
u[i] = (float*) malloc( 500 * sizeof(float) );
#pragma omp parallel for
for (i=0; i<500; i++)
for (j=0; j<500; j++)
{
u[i][j] = 0.0;
}
return 0;
}
// This code has data races since j is shared
|
serialized.c | // RUN: %libomp-compile-and-run | %sort-threads | FileCheck %s
// REQUIRES: ompt
// UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7
#define TEST_NEED_PRINT_FRAME_FROM_OUTLINED_FN
#include "callback.h"
#include <omp.h>
#include <math.h>
int main() {
omp_set_nested(0);
print_frame(0);
#pragma omp parallel num_threads(2)
{
print_frame_from_outlined_fn(1);
print_ids(0);
print_ids(1);
print_frame(0);
#pragma omp master
{
print_ids(0);
void *creator_frame = get_frame_address(0);
int t = (int)sin(0.1);
#pragma omp task if (t)
{
void *task_frame = get_frame_address(0);
if (creator_frame == task_frame) {
// Assume this code was inlined which the compiler is allowed to do.
print_frame(0);
} else {
// The exit frame must be our parent!
print_frame_from_outlined_fn(1);
}
print_ids(0);
print_ids(1);
print_ids(2);
}
print_fuzzy_address(1);
print_ids(0);
}
print_ids(0);
}
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback
// CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]]
// make sure initial data pointers are null
// CHECK-NOT: 0: new_task_data initially not null
// CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_task_create
// CHECK-SAME: parent_task_id={{[0-9]+}}, parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=[[NULL]]
// CHECK-SAME: new_task_id={{[0-9]+}}, codeptr_ra=[[NULL]]
// CHECK-SAME: task_type=ompt_task_initial=1, has_dependences=no
// CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address(0)
// CHECK-SAME: =[[MAIN_REENTER:0x[0-f]+]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID:[0-9]+]]
// CHECK-SAME: parent_task_frame.exit=[[NULL]]
// CHECK-SAME: parent_task_frame.reenter=0x{{[0-f]+}}
// CHECK-SAME: parallel_id=[[PARALLEL_ID:[0-9]+]], requested_team_size=2
// CHECK-SAME: codeptr_ra=0x{{[0-f]+}}, invoker={{[0-9]+}}
// nested parallel masters
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin
// CHECK-SAME: parallel_id=[[PARALLEL_ID]]
// CHECK-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]]
// CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address
// CHECK-SAME: =[[EXIT:0x[0-f]+]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK-SAME: exit_frame=[[EXIT]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[MASTER_ID]]: task level 1
// CHECK-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID:[0-9]+]]
// CHECK-SAME: task_id=[[PARENT_TASK_ID]],
// CHECK-SAME: exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address(0)=[[REENTER:0x[0-f]+]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_create
// CHECK-SAME: parent_task_id=[[IMPLICIT_TASK_ID]]
// CHECK-SAME: parent_task_frame.exit=[[EXIT]]
// CHECK-SAME: parent_task_frame.reenter=0x{{[0-f]+}}
// CHECK-SAME: new_task_id=[[TASK_ID:[0-9]+]]
// CHECK-SAME: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}}
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_schedule:
// CHECK-SAME: first_task_id=[[IMPLICIT_TASK_ID]], second_task_id=[[TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: __builtin_frame_address
// CHECK-SAME: =[[TASK_EXIT:0x[0-f]+]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[TASK_ID]]
// CHECK-SAME: exit_frame=[[TASK_EXIT]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[MASTER_ID]]: task level 1
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK-SAME: exit_frame=[[EXIT]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: task level 2
// CHECK-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]]
// CHECK-SAME: task_id=[[PARENT_TASK_ID]]
// CHECK-SAME: exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_schedule
// CHECK-SAME: first_task_id=[[TASK_ID]], second_task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_task_end: task_id=[[TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK-SAME: exit_frame=[[EXIT]], reenter_frame=[[NULL]]
// implicit barrier parallel
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: task level 0
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK-SAME: exit_frame=[[NULL]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_barrier_end
// parallel_id is 0 because the region ended in the barrier!
// CHECK-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end
// CHECK-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin
// CHECK-SAME: parallel_id=[[PARALLEL_ID]]
// CHECK-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]]
// CHECK: {{^}}[[THREAD_ID]]: __builtin_frame_address
// CHECK-SAME: =[[EXIT:0x[0-f]+]]
// CHECK: {{^}}[[THREAD_ID]]: task level 0
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK-SAME: exit_frame=[[EXIT]], reenter_frame=[[NULL]]
// CHECK: {{^}}[[THREAD_ID]]: task level 1
// CHECK-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]]
// CHECK-SAME: task_id=[[PARENT_TASK_ID]]
// CHECK-SAME: exit_frame=[[NULL]], reenter_frame=0x{{[0-f]+}}
// CHECK: {{^}}[[THREAD_ID]]: __builtin_frame_address(0)={{0x[0-f]+}}
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: task level 0
// CHECK-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// CHECK-SAME: exit_frame=[[NULL]], reenter_frame=[[NULL]]
// parallel_id is 0 because the region ended in the barrier!
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_barrier_end
// CHECK-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]]
// CHECK: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end
// CHECK-SAME: parallel_id=0, task_id=[[IMPLICIT_TASK_ID]]
return 0;
}
|
feature_group.h | /*!
* Copyright (c) 2017 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_FEATURE_GROUP_H_
#define LIGHTGBM_FEATURE_GROUP_H_
#include <LightGBM/bin.h>
#include <LightGBM/meta.h>
#include <LightGBM/utils/random.h>
#include <cstdio>
#include <memory>
#include <vector>
namespace LightGBM
{
class Dataset;
class DatasetLoader;
/*! \brief Using to store data and providing some operations on one feature group*/
class FeatureGroup
{
public:
friend Dataset;
friend DatasetLoader;
/*!
* \brief Constructor
* \param num_feature number of features of this group
* \param bin_mappers Bin mapper for features
* \param num_data Total number of data
* \param is_enable_sparse True if enable sparse feature
*/
FeatureGroup(int num_feature, bool is_multi_val,
std::vector<std::unique_ptr<BinMapper>, mi_stl_allocator<std::unique_ptr<BinMapper>>> *bin_mappers,
data_size_t num_data) : num_feature_(num_feature), is_multi_val_(is_multi_val), is_sparse_(false)
{
CHECK_EQ(static_cast<int>(bin_mappers->size()), num_feature);
// use bin at zero to store most_freq_bin
num_total_bin_ = 1;
bin_offsets_.emplace_back(num_total_bin_);
auto &ref_bin_mappers = *bin_mappers;
for (int i = 0; i < num_feature_; ++i)
{
bin_mappers_.emplace_back(ref_bin_mappers[i].release());
auto num_bin = bin_mappers_[i]->num_bin();
if (bin_mappers_[i]->GetMostFreqBin() == 0)
{
num_bin -= 1;
}
num_total_bin_ += num_bin;
bin_offsets_.emplace_back(num_total_bin_);
}
CreateBinData(num_data, is_multi_val_, true, false);
}
FeatureGroup(const FeatureGroup &other, int num_data)
{
num_feature_ = other.num_feature_;
is_multi_val_ = other.is_multi_val_;
is_sparse_ = other.is_sparse_;
num_total_bin_ = other.num_total_bin_;
bin_offsets_ = other.bin_offsets_;
bin_mappers_.reserve(other.bin_mappers_.size());
for (auto &bin_mapper : other.bin_mappers_)
{
bin_mappers_.emplace_back(new BinMapper(*bin_mapper));
}
CreateBinData(num_data, is_multi_val_, !is_sparse_, is_sparse_);
}
FeatureGroup(std::vector<std::unique_ptr<BinMapper>, mi_stl_allocator<std::unique_ptr<BinMapper>>> *bin_mappers,
data_size_t num_data) : num_feature_(1), is_multi_val_(false)
{
CHECK_EQ(static_cast<int>(bin_mappers->size()), 1);
// use bin at zero to store default_bin
num_total_bin_ = 1;
bin_offsets_.emplace_back(num_total_bin_);
auto &ref_bin_mappers = *bin_mappers;
for (int i = 0; i < num_feature_; ++i)
{
bin_mappers_.emplace_back(ref_bin_mappers[i].release());
auto num_bin = bin_mappers_[i]->num_bin();
if (bin_mappers_[i]->GetMostFreqBin() == 0)
{
num_bin -= 1;
}
num_total_bin_ += num_bin;
bin_offsets_.emplace_back(num_total_bin_);
}
CreateBinData(num_data, false, false, false);
}
/*!
* \brief Constructor from memory
* \param memory Pointer of memory
* \param num_all_data Number of global data
* \param local_used_indices Local used indices, empty means using all data
*/
FeatureGroup(const void *memory, data_size_t num_all_data,
const std::vector<data_size_t, mi_stl_allocator<data_size_t>> &local_used_indices)
{
const char *memory_ptr = reinterpret_cast<const char *>(memory);
// get is_sparse
is_multi_val_ = *(reinterpret_cast<const bool *>(memory_ptr));
memory_ptr += sizeof(is_multi_val_);
is_sparse_ = *(reinterpret_cast<const bool *>(memory_ptr));
memory_ptr += sizeof(is_sparse_);
num_feature_ = *(reinterpret_cast<const int *>(memory_ptr));
memory_ptr += sizeof(num_feature_);
// get bin mapper
bin_mappers_.clear();
bin_offsets_.clear();
// start from 1, due to need to store zero bin in this slot
num_total_bin_ = 1;
bin_offsets_.emplace_back(num_total_bin_);
for (int i = 0; i < num_feature_; ++i)
{
bin_mappers_.emplace_back(new BinMapper(memory_ptr));
auto num_bin = bin_mappers_[i]->num_bin();
if (bin_mappers_[i]->GetMostFreqBin() == 0)
{
num_bin -= 1;
}
num_total_bin_ += num_bin;
bin_offsets_.emplace_back(num_total_bin_);
memory_ptr += bin_mappers_[i]->SizesInByte();
}
data_size_t num_data = num_all_data;
if (!local_used_indices.empty())
{
num_data = static_cast<data_size_t>(local_used_indices.size());
}
if (is_multi_val_)
{
for (int i = 0; i < num_feature_; ++i)
{
int addi = bin_mappers_[i]->GetMostFreqBin() == 0 ? 0 : 1;
if (bin_mappers_[i]->sparse_rate() >= kSparseThreshold)
{
multi_bin_data_.emplace_back(Bin::CreateSparseBin(num_data, bin_mappers_[i]->num_bin() + addi));
}
else
{
multi_bin_data_.emplace_back(Bin::CreateDenseBin(num_data, bin_mappers_[i]->num_bin() + addi));
}
multi_bin_data_.back()->LoadFromMemory(memory_ptr, local_used_indices);
memory_ptr += multi_bin_data_.back()->SizesInByte();
}
}
else
{
if (is_sparse_)
{
bin_data_.reset(Bin::CreateSparseBin(num_data, num_total_bin_));
}
else
{
bin_data_.reset(Bin::CreateDenseBin(num_data, num_total_bin_));
}
// get bin data
bin_data_->LoadFromMemory(memory_ptr, local_used_indices);
}
}
/*! \brief Destructor */
~FeatureGroup()
{
}
/*!
* \brief Push one record, will auto convert to bin and push to bin data
* \param tid Thread id
* \param idx Index of record
* \param value feature value of record
*/
inline void PushData(int tid, int sub_feature_idx, data_size_t line_idx, double value)
{
uint32_t bin = bin_mappers_[sub_feature_idx]->ValueToBin(value);
if (bin == bin_mappers_[sub_feature_idx]->GetMostFreqBin())
{
return;
}
if (bin_mappers_[sub_feature_idx]->GetMostFreqBin() == 0)
{
bin -= 1;
}
if (is_multi_val_)
{
multi_bin_data_[sub_feature_idx]->Push(tid, line_idx, bin + 1);
}
else
{
bin += bin_offsets_[sub_feature_idx];
bin_data_->Push(tid, line_idx, bin);
}
}
void ReSize(int num_data)
{
if (!is_multi_val_)
{
bin_data_->ReSize(num_data);
}
else
{
for (int i = 0; i < num_feature_; ++i)
{
multi_bin_data_[i]->ReSize(num_data);
}
}
}
inline void CopySubrow(const FeatureGroup *full_feature, const data_size_t *used_indices, data_size_t num_used_indices)
{
if (!is_multi_val_)
{
bin_data_->CopySubrow(full_feature->bin_data_.get(), used_indices, num_used_indices);
}
else
{
for (int i = 0; i < num_feature_; ++i)
{
multi_bin_data_[i]->CopySubrow(full_feature->multi_bin_data_[i].get(), used_indices, num_used_indices);
}
}
}
inline BinIterator *SubFeatureIterator(int sub_feature)
{
uint32_t most_freq_bin = bin_mappers_[sub_feature]->GetMostFreqBin();
if (!is_multi_val_)
{
uint32_t min_bin = bin_offsets_[sub_feature];
uint32_t max_bin = bin_offsets_[sub_feature + 1] - 1;
return bin_data_->GetIterator(min_bin, max_bin, most_freq_bin);
}
else
{
int addi = bin_mappers_[sub_feature]->GetMostFreqBin() == 0 ? 0 : 1;
uint32_t min_bin = 1;
uint32_t max_bin = bin_mappers_[sub_feature]->num_bin() - 1 + addi;
return multi_bin_data_[sub_feature]->GetIterator(min_bin, max_bin, most_freq_bin);
}
}
inline void FinishLoad()
{
if (is_multi_val_)
{
OMP_INIT_EX();
#pragma omp parallel for schedule(guided)
for (int i = 0; i < num_feature_; ++i)
{
OMP_LOOP_EX_BEGIN();
multi_bin_data_[i]->FinishLoad();
OMP_LOOP_EX_END();
}
OMP_THROW_EX();
}
else
{
bin_data_->FinishLoad();
}
}
/*!
* \brief Returns a BinIterator that can access the entire feature group's raw data.
* The RawGet() function of the iterator should be called for best efficiency.
* \return A pointer to the BinIterator object
*/
inline BinIterator *FeatureGroupIterator()
{
if (is_multi_val_)
{
return nullptr;
}
uint32_t min_bin = bin_offsets_[0];
uint32_t max_bin = bin_offsets_.back() - 1;
uint32_t most_freq_bin = 0;
return bin_data_->GetIterator(min_bin, max_bin, most_freq_bin);
}
inline data_size_t Split(int sub_feature, const uint32_t *threshold,
int num_threshold, bool default_left,
const data_size_t *data_indices, data_size_t cnt,
data_size_t *lte_indices,
data_size_t *gt_indices) const
{
uint32_t default_bin = bin_mappers_[sub_feature]->GetDefaultBin();
uint32_t most_freq_bin = bin_mappers_[sub_feature]->GetMostFreqBin();
if (!is_multi_val_)
{
uint32_t min_bin = bin_offsets_[sub_feature];
uint32_t max_bin = bin_offsets_[sub_feature + 1] - 1;
if (bin_mappers_[sub_feature]->bin_type() == BinType::NumericalBin)
{
auto missing_type = bin_mappers_[sub_feature]->missing_type();
if (num_feature_ == 1)
{
return bin_data_->Split(max_bin, default_bin, most_freq_bin,
missing_type, default_left, *threshold,
data_indices, cnt, lte_indices, gt_indices);
}
else
{
return bin_data_->Split(min_bin, max_bin, default_bin, most_freq_bin,
missing_type, default_left, *threshold,
data_indices, cnt, lte_indices, gt_indices);
}
}
else
{
if (num_feature_ == 1)
{
return bin_data_->SplitCategorical(max_bin, most_freq_bin, threshold,
num_threshold, data_indices, cnt,
lte_indices, gt_indices);
}
else
{
return bin_data_->SplitCategorical(
min_bin, max_bin, most_freq_bin, threshold, num_threshold,
data_indices, cnt, lte_indices, gt_indices);
}
}
}
else
{
int addi = bin_mappers_[sub_feature]->GetMostFreqBin() == 0 ? 0 : 1;
uint32_t max_bin = bin_mappers_[sub_feature]->num_bin() - 1 + addi;
if (bin_mappers_[sub_feature]->bin_type() == BinType::NumericalBin)
{
auto missing_type = bin_mappers_[sub_feature]->missing_type();
return multi_bin_data_[sub_feature]->Split(
max_bin, default_bin, most_freq_bin, missing_type, default_left,
*threshold, data_indices, cnt, lte_indices, gt_indices);
}
else
{
return multi_bin_data_[sub_feature]->SplitCategorical(
max_bin, most_freq_bin, threshold, num_threshold, data_indices, cnt,
lte_indices, gt_indices);
}
}
}
/*!
* \brief From bin to feature value
* \param bin
* \return FeatureGroup value of this bin
*/
inline double BinToValue(int sub_feature_idx, uint32_t bin) const
{
return bin_mappers_[sub_feature_idx]->BinToValue(bin);
}
/*!
* \brief Save binary data to file
* \param file File want to write
*/
void SaveBinaryToFile(const VirtualFileWriter *writer) const
{
writer->Write(&is_multi_val_, sizeof(is_multi_val_));
writer->Write(&is_sparse_, sizeof(is_sparse_));
writer->Write(&num_feature_, sizeof(num_feature_));
for (int i = 0; i < num_feature_; ++i)
{
bin_mappers_[i]->SaveBinaryToFile(writer);
}
if (is_multi_val_)
{
for (int i = 0; i < num_feature_; ++i)
{
multi_bin_data_[i]->SaveBinaryToFile(writer);
}
}
else
{
bin_data_->SaveBinaryToFile(writer);
}
}
/*!
* \brief Get sizes in byte of this object
*/
size_t SizesInByte() const
{
size_t ret = sizeof(is_multi_val_) + sizeof(is_sparse_) + sizeof(num_feature_);
for (int i = 0; i < num_feature_; ++i)
{
ret += bin_mappers_[i]->SizesInByte();
}
if (!is_multi_val_)
{
ret += bin_data_->SizesInByte();
}
else
{
for (int i = 0; i < num_feature_; ++i)
{
ret += multi_bin_data_[i]->SizesInByte();
}
}
return ret;
}
/*! \brief Disable copy */
FeatureGroup &operator=(const FeatureGroup &) = delete;
/*! \brief Deep copy */
FeatureGroup(const FeatureGroup &other)
{
num_feature_ = other.num_feature_;
is_multi_val_ = other.is_multi_val_;
is_sparse_ = other.is_sparse_;
num_total_bin_ = other.num_total_bin_;
bin_offsets_ = other.bin_offsets_;
bin_mappers_.reserve(other.bin_mappers_.size());
for (auto &bin_mapper : other.bin_mappers_)
{
bin_mappers_.emplace_back(new BinMapper(*bin_mapper));
}
if (!is_multi_val_)
{
bin_data_.reset(other.bin_data_->Clone());
}
else
{
multi_bin_data_.clear();
for (int i = 0; i < num_feature_; ++i)
{
multi_bin_data_.emplace_back(other.multi_bin_data_[i]->Clone());
}
}
}
private:
void CreateBinData(int num_data, bool is_multi_val, bool force_dense, bool force_sparse)
{
if (is_multi_val)
{
multi_bin_data_.clear();
for (int i = 0; i < num_feature_; ++i)
{
int addi = bin_mappers_[i]->GetMostFreqBin() == 0 ? 0 : 1;
if (bin_mappers_[i]->sparse_rate() >= kSparseThreshold)
{
multi_bin_data_.emplace_back(Bin::CreateSparseBin(
num_data, bin_mappers_[i]->num_bin() + addi));
}
else
{
multi_bin_data_.emplace_back(
Bin::CreateDenseBin(num_data, bin_mappers_[i]->num_bin() + addi));
}
}
is_multi_val_ = true;
}
else
{
if (force_sparse || (!force_dense && num_feature_ == 1 &&
bin_mappers_[0]->sparse_rate() >= kSparseThreshold))
{
is_sparse_ = true;
bin_data_.reset(Bin::CreateSparseBin(num_data, num_total_bin_));
}
else
{
is_sparse_ = false;
bin_data_.reset(Bin::CreateDenseBin(num_data, num_total_bin_));
}
is_multi_val_ = false;
}
}
/*! \brief Number of features */
int num_feature_;
/*! \brief Bin mapper for sub features */
std::vector<std::unique_ptr<BinMapper>, mi_stl_allocator<std::unique_ptr<BinMapper>>> bin_mappers_;
/*! \brief Bin offsets for sub features */
std::vector<uint32_t, mi_stl_allocator<uint32_t>> bin_offsets_;
/*! \brief Bin data of this feature */
std::unique_ptr<Bin> bin_data_;
std::vector<std::unique_ptr<Bin>, mi_stl_allocator<std::unique_ptr<Bin>>> multi_bin_data_;
/*! \brief True if this feature is sparse */
bool is_multi_val_;
bool is_sparse_;
int num_total_bin_;
};
} // namespace LightGBM
#endif // LIGHTGBM_FEATURE_GROUP_H_
|
num_secretos.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
int main()
{
srand(time(NULL));
#pragma omp parallel
{
int id = omp_get_thread_num();
int numero_secreto = rand() % 20;
// #pragma omp single // apenas uma thread executa barrando as outras até o fim
// #pragma omp single nowait // mesma ideia porem sem a barreira
// #pragma omp master // mesma ideia da acima mas apenas a thread 0 executa
printf("Vamos revelar os números secretos!\n");
// #pragma omp barrier // a execução só continua quando todas as threads chegarem na barreira
printf("Thread %d escolheu o número %d\n",id,numero_secreto);
}
}
|
GB_unop__identity_uint8_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 Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_uint8_fp64)
// op(A') function: GB (_unop_tran__identity_uint8_fp64)
// C type: uint8_t
// A type: double
// cast: uint8_t cij = GB_cast_to_uint8_t ((double) (aij))
// unaryop: cij = aij
#define GB_ATYPE \
double
#define GB_CTYPE \
uint8_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 = x ;
// casting
#define GB_CAST(z, aij) \
uint8_t z = GB_cast_to_uint8_t ((double) (aij)) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
double aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint8_t z = GB_cast_to_uint8_t ((double) (aij)) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_FP64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint8_fp64)
(
uint8_t *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 ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
double aij = Ax [p] ;
uint8_t z = GB_cast_to_uint8_t ((double) (aij)) ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
double aij = Ax [p] ;
uint8_t z = GB_cast_to_uint8_t ((double) (aij)) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_uint8_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
|
convolution_7x7_pack1to4.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 conv7x7s2_pack1to4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2 * outw + w;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
Mat out0 = top_blob.channel(p);
v4f32 _bias0 = bias ? (v4f32)__msa_ld_w(bias + p * 4, 0) : (v4f32)__msa_fill_w(0);
out0.fill(_bias0);
for (int q = 0; q < inch; q++)
{
float* outptr0 = out0;
const Mat img0 = bottom_blob.channel(q);
const float* r0 = img0.row(0);
const float* r1 = img0.row(1);
const float* r2 = img0.row(2);
const float* r3 = img0.row(3);
const float* r4 = img0.row(4);
const float* r5 = img0.row(5);
const float* r6 = img0.row(6);
const float* kptr = kernel.channel(p).row(q);
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0);
v4f32 _sum1 = (v4f32)__msa_ld_w(outptr0 + 4, 0);
v4f32 _sum2 = (v4f32)__msa_ld_w(outptr0 + 4 * 2, 0);
v4f32 _sum3 = (v4f32)__msa_ld_w(outptr0 + 4 * 3, 0);
v4f32 _k00 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k01 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k02 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k03 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k04 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k05 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k06 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r0 = __msa_ld_w(r0, 0);
v4i32 _r0n = __msa_ld_w(r0 + 4, 0);
v4i32 _r0nn = __msa_ld_w(r0 + 8, 0);
v4f32 _r00 = (v4f32)__msa_splati_w(_r0, 0);
v4f32 _r01 = (v4f32)__msa_splati_w(_r0, 1);
v4f32 _r02 = (v4f32)__msa_splati_w(_r0, 2);
v4f32 _r03 = (v4f32)__msa_splati_w(_r0, 3);
v4f32 _r04 = (v4f32)__msa_splati_w(_r0n, 0);
v4f32 _r05 = (v4f32)__msa_splati_w(_r0n, 1);
v4f32 _r06 = (v4f32)__msa_splati_w(_r0n, 2);
v4f32 _r07 = (v4f32)__msa_splati_w(_r0n, 3);
v4f32 _r08 = (v4f32)__msa_splati_w(_r0nn, 0);
v4f32 _r09 = (v4f32)__msa_splati_w(_r0nn, 1);
v4f32 _r0a = (v4f32)__msa_splati_w(_r0nn, 2);
v4f32 _r0b = (v4f32)__msa_splati_w(_r0nn, 3);
v4f32 _r0c = __msa_fill_w_f32(r0[12]);
_sum0 = __msa_fmadd_w(_sum0, _r00, _k00);
_sum1 = __msa_fmadd_w(_sum1, _r02, _k00);
_sum2 = __msa_fmadd_w(_sum2, _r04, _k00);
_sum3 = __msa_fmadd_w(_sum3, _r06, _k00);
_sum0 = __msa_fmadd_w(_sum0, _r01, _k01);
_sum1 = __msa_fmadd_w(_sum1, _r03, _k01);
_sum2 = __msa_fmadd_w(_sum2, _r05, _k01);
_sum3 = __msa_fmadd_w(_sum3, _r07, _k01);
_sum0 = __msa_fmadd_w(_sum0, _r02, _k02);
_sum1 = __msa_fmadd_w(_sum1, _r04, _k02);
_sum2 = __msa_fmadd_w(_sum2, _r06, _k02);
_sum3 = __msa_fmadd_w(_sum3, _r08, _k02);
_sum0 = __msa_fmadd_w(_sum0, _r03, _k03);
_sum1 = __msa_fmadd_w(_sum1, _r05, _k03);
_sum2 = __msa_fmadd_w(_sum2, _r07, _k03);
_sum3 = __msa_fmadd_w(_sum3, _r09, _k03);
_sum0 = __msa_fmadd_w(_sum0, _r04, _k04);
_sum1 = __msa_fmadd_w(_sum1, _r06, _k04);
_sum2 = __msa_fmadd_w(_sum2, _r08, _k04);
_sum3 = __msa_fmadd_w(_sum3, _r0a, _k04);
_sum0 = __msa_fmadd_w(_sum0, _r05, _k05);
_sum1 = __msa_fmadd_w(_sum1, _r07, _k05);
_sum2 = __msa_fmadd_w(_sum2, _r09, _k05);
_sum3 = __msa_fmadd_w(_sum3, _r0b, _k05);
_sum0 = __msa_fmadd_w(_sum0, _r06, _k06);
_sum1 = __msa_fmadd_w(_sum1, _r08, _k06);
_sum2 = __msa_fmadd_w(_sum2, _r0a, _k06);
_sum3 = __msa_fmadd_w(_sum3, _r0c, _k06);
v4f32 _k10 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k11 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k12 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k13 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k14 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k15 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k16 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r1 = __msa_ld_w(r1, 0);
v4i32 _r1n = __msa_ld_w(r1 + 4, 0);
v4i32 _r1nn = __msa_ld_w(r1 + 8, 0);
v4f32 _r10 = (v4f32)__msa_splati_w(_r1, 0);
v4f32 _r11 = (v4f32)__msa_splati_w(_r1, 1);
v4f32 _r12 = (v4f32)__msa_splati_w(_r1, 2);
v4f32 _r13 = (v4f32)__msa_splati_w(_r1, 3);
v4f32 _r14 = (v4f32)__msa_splati_w(_r1n, 0);
v4f32 _r15 = (v4f32)__msa_splati_w(_r1n, 1);
v4f32 _r16 = (v4f32)__msa_splati_w(_r1n, 2);
v4f32 _r17 = (v4f32)__msa_splati_w(_r1n, 3);
v4f32 _r18 = (v4f32)__msa_splati_w(_r1nn, 0);
v4f32 _r19 = (v4f32)__msa_splati_w(_r1nn, 1);
v4f32 _r1a = (v4f32)__msa_splati_w(_r1nn, 2);
v4f32 _r1b = (v4f32)__msa_splati_w(_r1nn, 3);
v4f32 _r1c = __msa_fill_w_f32(r1[12]);
_sum0 = __msa_fmadd_w(_sum0, _r10, _k10);
_sum1 = __msa_fmadd_w(_sum1, _r12, _k10);
_sum2 = __msa_fmadd_w(_sum2, _r14, _k10);
_sum3 = __msa_fmadd_w(_sum3, _r16, _k10);
_sum0 = __msa_fmadd_w(_sum0, _r11, _k11);
_sum1 = __msa_fmadd_w(_sum1, _r13, _k11);
_sum2 = __msa_fmadd_w(_sum2, _r15, _k11);
_sum3 = __msa_fmadd_w(_sum3, _r17, _k11);
_sum0 = __msa_fmadd_w(_sum0, _r12, _k12);
_sum1 = __msa_fmadd_w(_sum1, _r14, _k12);
_sum2 = __msa_fmadd_w(_sum2, _r16, _k12);
_sum3 = __msa_fmadd_w(_sum3, _r18, _k12);
_sum0 = __msa_fmadd_w(_sum0, _r13, _k13);
_sum1 = __msa_fmadd_w(_sum1, _r15, _k13);
_sum2 = __msa_fmadd_w(_sum2, _r17, _k13);
_sum3 = __msa_fmadd_w(_sum3, _r19, _k13);
_sum0 = __msa_fmadd_w(_sum0, _r14, _k14);
_sum1 = __msa_fmadd_w(_sum1, _r16, _k14);
_sum2 = __msa_fmadd_w(_sum2, _r18, _k14);
_sum3 = __msa_fmadd_w(_sum3, _r1a, _k14);
_sum0 = __msa_fmadd_w(_sum0, _r15, _k15);
_sum1 = __msa_fmadd_w(_sum1, _r17, _k15);
_sum2 = __msa_fmadd_w(_sum2, _r19, _k15);
_sum3 = __msa_fmadd_w(_sum3, _r1b, _k15);
_sum0 = __msa_fmadd_w(_sum0, _r16, _k16);
_sum1 = __msa_fmadd_w(_sum1, _r18, _k16);
_sum2 = __msa_fmadd_w(_sum2, _r1a, _k16);
_sum3 = __msa_fmadd_w(_sum3, _r1c, _k16);
v4f32 _k20 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k21 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k22 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k23 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k24 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k25 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k26 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r2 = __msa_ld_w(r2, 0);
v4i32 _r2n = __msa_ld_w(r2 + 4, 0);
v4i32 _r2nn = __msa_ld_w(r2 + 8, 0);
v4f32 _r20 = (v4f32)__msa_splati_w(_r2, 0);
v4f32 _r21 = (v4f32)__msa_splati_w(_r2, 1);
v4f32 _r22 = (v4f32)__msa_splati_w(_r2, 2);
v4f32 _r23 = (v4f32)__msa_splati_w(_r2, 3);
v4f32 _r24 = (v4f32)__msa_splati_w(_r2n, 0);
v4f32 _r25 = (v4f32)__msa_splati_w(_r2n, 1);
v4f32 _r26 = (v4f32)__msa_splati_w(_r2n, 2);
v4f32 _r27 = (v4f32)__msa_splati_w(_r2n, 3);
v4f32 _r28 = (v4f32)__msa_splati_w(_r2nn, 0);
v4f32 _r29 = (v4f32)__msa_splati_w(_r2nn, 1);
v4f32 _r2a = (v4f32)__msa_splati_w(_r2nn, 2);
v4f32 _r2b = (v4f32)__msa_splati_w(_r2nn, 3);
v4f32 _r2c = __msa_fill_w_f32(r2[12]);
_sum0 = __msa_fmadd_w(_sum0, _r20, _k20);
_sum1 = __msa_fmadd_w(_sum1, _r22, _k20);
_sum2 = __msa_fmadd_w(_sum2, _r24, _k20);
_sum3 = __msa_fmadd_w(_sum3, _r26, _k20);
_sum0 = __msa_fmadd_w(_sum0, _r21, _k21);
_sum1 = __msa_fmadd_w(_sum1, _r23, _k21);
_sum2 = __msa_fmadd_w(_sum2, _r25, _k21);
_sum3 = __msa_fmadd_w(_sum3, _r27, _k21);
_sum0 = __msa_fmadd_w(_sum0, _r22, _k22);
_sum1 = __msa_fmadd_w(_sum1, _r24, _k22);
_sum2 = __msa_fmadd_w(_sum2, _r26, _k22);
_sum3 = __msa_fmadd_w(_sum3, _r28, _k22);
_sum0 = __msa_fmadd_w(_sum0, _r23, _k23);
_sum1 = __msa_fmadd_w(_sum1, _r25, _k23);
_sum2 = __msa_fmadd_w(_sum2, _r27, _k23);
_sum3 = __msa_fmadd_w(_sum3, _r29, _k23);
_sum0 = __msa_fmadd_w(_sum0, _r24, _k24);
_sum1 = __msa_fmadd_w(_sum1, _r26, _k24);
_sum2 = __msa_fmadd_w(_sum2, _r28, _k24);
_sum3 = __msa_fmadd_w(_sum3, _r2a, _k24);
_sum0 = __msa_fmadd_w(_sum0, _r25, _k25);
_sum1 = __msa_fmadd_w(_sum1, _r27, _k25);
_sum2 = __msa_fmadd_w(_sum2, _r29, _k25);
_sum3 = __msa_fmadd_w(_sum3, _r2b, _k25);
_sum0 = __msa_fmadd_w(_sum0, _r26, _k26);
_sum1 = __msa_fmadd_w(_sum1, _r28, _k26);
_sum2 = __msa_fmadd_w(_sum2, _r2a, _k26);
_sum3 = __msa_fmadd_w(_sum3, _r2c, _k26);
v4f32 _k30 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k31 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k32 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k33 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k34 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k35 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k36 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r3 = __msa_ld_w(r3, 0);
v4i32 _r3n = __msa_ld_w(r3 + 4, 0);
v4i32 _r3nn = __msa_ld_w(r3 + 8, 0);
v4f32 _r30 = (v4f32)__msa_splati_w(_r3, 0);
v4f32 _r31 = (v4f32)__msa_splati_w(_r3, 1);
v4f32 _r32 = (v4f32)__msa_splati_w(_r3, 2);
v4f32 _r33 = (v4f32)__msa_splati_w(_r3, 3);
v4f32 _r34 = (v4f32)__msa_splati_w(_r3n, 0);
v4f32 _r35 = (v4f32)__msa_splati_w(_r3n, 1);
v4f32 _r36 = (v4f32)__msa_splati_w(_r3n, 2);
v4f32 _r37 = (v4f32)__msa_splati_w(_r3n, 3);
v4f32 _r38 = (v4f32)__msa_splati_w(_r3nn, 0);
v4f32 _r39 = (v4f32)__msa_splati_w(_r3nn, 1);
v4f32 _r3a = (v4f32)__msa_splati_w(_r3nn, 2);
v4f32 _r3b = (v4f32)__msa_splati_w(_r3nn, 3);
v4f32 _r3c = __msa_fill_w_f32(r3[12]);
_sum0 = __msa_fmadd_w(_sum0, _r30, _k30);
_sum1 = __msa_fmadd_w(_sum1, _r32, _k30);
_sum2 = __msa_fmadd_w(_sum2, _r34, _k30);
_sum3 = __msa_fmadd_w(_sum3, _r36, _k30);
_sum0 = __msa_fmadd_w(_sum0, _r31, _k31);
_sum1 = __msa_fmadd_w(_sum1, _r33, _k31);
_sum2 = __msa_fmadd_w(_sum2, _r35, _k31);
_sum3 = __msa_fmadd_w(_sum3, _r37, _k31);
_sum0 = __msa_fmadd_w(_sum0, _r32, _k32);
_sum1 = __msa_fmadd_w(_sum1, _r34, _k32);
_sum2 = __msa_fmadd_w(_sum2, _r36, _k32);
_sum3 = __msa_fmadd_w(_sum3, _r38, _k32);
_sum0 = __msa_fmadd_w(_sum0, _r33, _k33);
_sum1 = __msa_fmadd_w(_sum1, _r35, _k33);
_sum2 = __msa_fmadd_w(_sum2, _r37, _k33);
_sum3 = __msa_fmadd_w(_sum3, _r39, _k33);
_sum0 = __msa_fmadd_w(_sum0, _r34, _k34);
_sum1 = __msa_fmadd_w(_sum1, _r36, _k34);
_sum2 = __msa_fmadd_w(_sum2, _r38, _k34);
_sum3 = __msa_fmadd_w(_sum3, _r3a, _k34);
_sum0 = __msa_fmadd_w(_sum0, _r35, _k35);
_sum1 = __msa_fmadd_w(_sum1, _r37, _k35);
_sum2 = __msa_fmadd_w(_sum2, _r39, _k35);
_sum3 = __msa_fmadd_w(_sum3, _r3b, _k35);
_sum0 = __msa_fmadd_w(_sum0, _r36, _k36);
_sum1 = __msa_fmadd_w(_sum1, _r38, _k36);
_sum2 = __msa_fmadd_w(_sum2, _r3a, _k36);
_sum3 = __msa_fmadd_w(_sum3, _r3c, _k36);
v4f32 _k40 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k41 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k42 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k43 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k44 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k45 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k46 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r4 = __msa_ld_w(r4, 0);
v4i32 _r4n = __msa_ld_w(r4 + 4, 0);
v4i32 _r4nn = __msa_ld_w(r4 + 8, 0);
v4f32 _r40 = (v4f32)__msa_splati_w(_r4, 0);
v4f32 _r41 = (v4f32)__msa_splati_w(_r4, 1);
v4f32 _r42 = (v4f32)__msa_splati_w(_r4, 2);
v4f32 _r43 = (v4f32)__msa_splati_w(_r4, 3);
v4f32 _r44 = (v4f32)__msa_splati_w(_r4n, 0);
v4f32 _r45 = (v4f32)__msa_splati_w(_r4n, 1);
v4f32 _r46 = (v4f32)__msa_splati_w(_r4n, 2);
v4f32 _r47 = (v4f32)__msa_splati_w(_r4n, 3);
v4f32 _r48 = (v4f32)__msa_splati_w(_r4nn, 0);
v4f32 _r49 = (v4f32)__msa_splati_w(_r4nn, 1);
v4f32 _r4a = (v4f32)__msa_splati_w(_r4nn, 2);
v4f32 _r4b = (v4f32)__msa_splati_w(_r4nn, 3);
v4f32 _r4c = __msa_fill_w_f32(r4[12]);
_sum0 = __msa_fmadd_w(_sum0, _r40, _k40);
_sum1 = __msa_fmadd_w(_sum1, _r42, _k40);
_sum2 = __msa_fmadd_w(_sum2, _r44, _k40);
_sum3 = __msa_fmadd_w(_sum3, _r46, _k40);
_sum0 = __msa_fmadd_w(_sum0, _r41, _k41);
_sum1 = __msa_fmadd_w(_sum1, _r43, _k41);
_sum2 = __msa_fmadd_w(_sum2, _r45, _k41);
_sum3 = __msa_fmadd_w(_sum3, _r47, _k41);
_sum0 = __msa_fmadd_w(_sum0, _r42, _k42);
_sum1 = __msa_fmadd_w(_sum1, _r44, _k42);
_sum2 = __msa_fmadd_w(_sum2, _r46, _k42);
_sum3 = __msa_fmadd_w(_sum3, _r48, _k42);
_sum0 = __msa_fmadd_w(_sum0, _r43, _k43);
_sum1 = __msa_fmadd_w(_sum1, _r45, _k43);
_sum2 = __msa_fmadd_w(_sum2, _r47, _k43);
_sum3 = __msa_fmadd_w(_sum3, _r49, _k43);
_sum0 = __msa_fmadd_w(_sum0, _r44, _k44);
_sum1 = __msa_fmadd_w(_sum1, _r46, _k44);
_sum2 = __msa_fmadd_w(_sum2, _r48, _k44);
_sum3 = __msa_fmadd_w(_sum3, _r4a, _k44);
_sum0 = __msa_fmadd_w(_sum0, _r45, _k45);
_sum1 = __msa_fmadd_w(_sum1, _r47, _k45);
_sum2 = __msa_fmadd_w(_sum2, _r49, _k45);
_sum3 = __msa_fmadd_w(_sum3, _r4b, _k45);
_sum0 = __msa_fmadd_w(_sum0, _r46, _k46);
_sum1 = __msa_fmadd_w(_sum1, _r48, _k46);
_sum2 = __msa_fmadd_w(_sum2, _r4a, _k46);
_sum3 = __msa_fmadd_w(_sum3, _r4c, _k46);
v4f32 _k50 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k51 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k52 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k53 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k54 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k55 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k56 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r5 = __msa_ld_w(r5, 0);
v4i32 _r5n = __msa_ld_w(r5 + 4, 0);
v4i32 _r5nn = __msa_ld_w(r5 + 8, 0);
v4f32 _r50 = (v4f32)__msa_splati_w(_r5, 0);
v4f32 _r51 = (v4f32)__msa_splati_w(_r5, 1);
v4f32 _r52 = (v4f32)__msa_splati_w(_r5, 2);
v4f32 _r53 = (v4f32)__msa_splati_w(_r5, 3);
v4f32 _r54 = (v4f32)__msa_splati_w(_r5n, 0);
v4f32 _r55 = (v4f32)__msa_splati_w(_r5n, 1);
v4f32 _r56 = (v4f32)__msa_splati_w(_r5n, 2);
v4f32 _r57 = (v4f32)__msa_splati_w(_r5n, 3);
v4f32 _r58 = (v4f32)__msa_splati_w(_r5nn, 0);
v4f32 _r59 = (v4f32)__msa_splati_w(_r5nn, 1);
v4f32 _r5a = (v4f32)__msa_splati_w(_r5nn, 2);
v4f32 _r5b = (v4f32)__msa_splati_w(_r5nn, 3);
v4f32 _r5c = __msa_fill_w_f32(r5[12]);
_sum0 = __msa_fmadd_w(_sum0, _r50, _k50);
_sum1 = __msa_fmadd_w(_sum1, _r52, _k50);
_sum2 = __msa_fmadd_w(_sum2, _r54, _k50);
_sum3 = __msa_fmadd_w(_sum3, _r56, _k50);
_sum0 = __msa_fmadd_w(_sum0, _r51, _k51);
_sum1 = __msa_fmadd_w(_sum1, _r53, _k51);
_sum2 = __msa_fmadd_w(_sum2, _r55, _k51);
_sum3 = __msa_fmadd_w(_sum3, _r57, _k51);
_sum0 = __msa_fmadd_w(_sum0, _r52, _k52);
_sum1 = __msa_fmadd_w(_sum1, _r54, _k52);
_sum2 = __msa_fmadd_w(_sum2, _r56, _k52);
_sum3 = __msa_fmadd_w(_sum3, _r58, _k52);
_sum0 = __msa_fmadd_w(_sum0, _r53, _k53);
_sum1 = __msa_fmadd_w(_sum1, _r55, _k53);
_sum2 = __msa_fmadd_w(_sum2, _r57, _k53);
_sum3 = __msa_fmadd_w(_sum3, _r59, _k53);
_sum0 = __msa_fmadd_w(_sum0, _r54, _k54);
_sum1 = __msa_fmadd_w(_sum1, _r56, _k54);
_sum2 = __msa_fmadd_w(_sum2, _r58, _k54);
_sum3 = __msa_fmadd_w(_sum3, _r5a, _k54);
_sum0 = __msa_fmadd_w(_sum0, _r55, _k55);
_sum1 = __msa_fmadd_w(_sum1, _r57, _k55);
_sum2 = __msa_fmadd_w(_sum2, _r59, _k55);
_sum3 = __msa_fmadd_w(_sum3, _r5b, _k55);
_sum0 = __msa_fmadd_w(_sum0, _r56, _k56);
_sum1 = __msa_fmadd_w(_sum1, _r58, _k56);
_sum2 = __msa_fmadd_w(_sum2, _r5a, _k56);
_sum3 = __msa_fmadd_w(_sum3, _r5c, _k56);
v4f32 _k60 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k61 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k62 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k63 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k64 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k65 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k66 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr -= 4 * 42;
v4i32 _r6 = __msa_ld_w(r6, 0);
v4i32 _r6n = __msa_ld_w(r6 + 4, 0);
v4i32 _r6nn = __msa_ld_w(r6 + 8, 0);
v4f32 _r60 = (v4f32)__msa_splati_w(_r6, 0);
v4f32 _r61 = (v4f32)__msa_splati_w(_r6, 1);
v4f32 _r62 = (v4f32)__msa_splati_w(_r6, 2);
v4f32 _r63 = (v4f32)__msa_splati_w(_r6, 3);
v4f32 _r64 = (v4f32)__msa_splati_w(_r6n, 0);
v4f32 _r65 = (v4f32)__msa_splati_w(_r6n, 1);
v4f32 _r66 = (v4f32)__msa_splati_w(_r6n, 2);
v4f32 _r67 = (v4f32)__msa_splati_w(_r6n, 3);
v4f32 _r68 = (v4f32)__msa_splati_w(_r6nn, 0);
v4f32 _r69 = (v4f32)__msa_splati_w(_r6nn, 1);
v4f32 _r6a = (v4f32)__msa_splati_w(_r6nn, 2);
v4f32 _r6b = (v4f32)__msa_splati_w(_r6nn, 3);
v4f32 _r6c = __msa_fill_w_f32(r6[12]);
_sum0 = __msa_fmadd_w(_sum0, _r60, _k60);
_sum1 = __msa_fmadd_w(_sum1, _r62, _k60);
_sum2 = __msa_fmadd_w(_sum2, _r64, _k60);
_sum3 = __msa_fmadd_w(_sum3, _r66, _k60);
_sum0 = __msa_fmadd_w(_sum0, _r61, _k61);
_sum1 = __msa_fmadd_w(_sum1, _r63, _k61);
_sum2 = __msa_fmadd_w(_sum2, _r65, _k61);
_sum3 = __msa_fmadd_w(_sum3, _r67, _k61);
_sum0 = __msa_fmadd_w(_sum0, _r62, _k62);
_sum1 = __msa_fmadd_w(_sum1, _r64, _k62);
_sum2 = __msa_fmadd_w(_sum2, _r66, _k62);
_sum3 = __msa_fmadd_w(_sum3, _r68, _k62);
_sum0 = __msa_fmadd_w(_sum0, _r63, _k63);
_sum1 = __msa_fmadd_w(_sum1, _r65, _k63);
_sum2 = __msa_fmadd_w(_sum2, _r67, _k63);
_sum3 = __msa_fmadd_w(_sum3, _r69, _k63);
_sum0 = __msa_fmadd_w(_sum0, _r64, _k64);
_sum1 = __msa_fmadd_w(_sum1, _r66, _k64);
_sum2 = __msa_fmadd_w(_sum2, _r68, _k64);
_sum3 = __msa_fmadd_w(_sum3, _r6a, _k64);
_sum0 = __msa_fmadd_w(_sum0, _r65, _k65);
_sum1 = __msa_fmadd_w(_sum1, _r67, _k65);
_sum2 = __msa_fmadd_w(_sum2, _r69, _k65);
_sum3 = __msa_fmadd_w(_sum3, _r6b, _k65);
_sum0 = __msa_fmadd_w(_sum0, _r66, _k66);
_sum1 = __msa_fmadd_w(_sum1, _r68, _k66);
_sum2 = __msa_fmadd_w(_sum2, _r6a, _k66);
_sum3 = __msa_fmadd_w(_sum3, _r6c, _k66);
__msa_st_w((v4i32)_sum0, outptr0, 0);
__msa_st_w((v4i32)_sum1, outptr0 + 4, 0);
__msa_st_w((v4i32)_sum2, outptr0 + 4 * 2, 0);
__msa_st_w((v4i32)_sum3, outptr0 + 4 * 3, 0);
outptr0 += 4 * 4;
r0 += 8;
r1 += 8;
r2 += 8;
r3 += 8;
r4 += 8;
r5 += 8;
r6 += 8;
}
for (; j < outw; j++)
{
v4f32 _sum0 = (v4f32)__msa_ld_w(outptr0, 0);
v4f32 _k00 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k01 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k02 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k03 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k04 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k05 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k06 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r0 = __msa_ld_w(r0, 0);
v4i32 _r0n = __msa_ld_w(r0 + 4, 0);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r0, 0), _k00);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r0, 1), _k01);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r0, 2), _k02);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r0, 3), _k03);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r0n, 0), _k04);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r0n, 1), _k05);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r0n, 2), _k06);
v4f32 _k10 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k11 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k12 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k13 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k14 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k15 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k16 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r1 = __msa_ld_w(r1, 0);
v4i32 _r1n = __msa_ld_w(r1 + 4, 0);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r1, 0), _k10);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r1, 1), _k11);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r1, 2), _k12);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r1, 3), _k13);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r1n, 0), _k14);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r1n, 1), _k15);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r1n, 2), _k16);
v4f32 _k20 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k21 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k22 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k23 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k24 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k25 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k26 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r2 = __msa_ld_w(r2, 0);
v4i32 _r2n = __msa_ld_w(r2 + 4, 0);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r2, 0), _k20);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r2, 1), _k21);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r2, 2), _k22);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r2, 3), _k23);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r2n, 0), _k24);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r2n, 1), _k25);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r2n, 2), _k26);
v4f32 _k30 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k31 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k32 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k33 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k34 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k35 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k36 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r3 = __msa_ld_w(r3, 0);
v4i32 _r3n = __msa_ld_w(r3 + 4, 0);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r3, 0), _k30);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r3, 1), _k31);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r3, 2), _k32);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r3, 3), _k33);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r3n, 0), _k34);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r3n, 1), _k35);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r3n, 2), _k36);
v4f32 _k40 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k41 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k42 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k43 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k44 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k45 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k46 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r4 = __msa_ld_w(r4, 0);
v4i32 _r4n = __msa_ld_w(r4 + 4, 0);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r4, 0), _k40);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r4, 1), _k41);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r4, 2), _k42);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r4, 3), _k43);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r4n, 0), _k44);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r4n, 1), _k45);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r4n, 2), _k46);
v4f32 _k50 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k51 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k52 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k53 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k54 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k55 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k56 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr += 4 * 7;
v4i32 _r5 = __msa_ld_w(r5, 0);
v4i32 _r5n = __msa_ld_w(r5 + 4, 0);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r5, 0), _k50);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r5, 1), _k51);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r5, 2), _k52);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r5, 3), _k53);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r5n, 0), _k54);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r5n, 1), _k55);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r5n, 2), _k56);
v4f32 _k60 = (v4f32)__msa_ld_w(kptr, 0);
v4f32 _k61 = (v4f32)__msa_ld_w(kptr + 4, 0);
v4f32 _k62 = (v4f32)__msa_ld_w(kptr + 4 * 2, 0);
v4f32 _k63 = (v4f32)__msa_ld_w(kptr + 4 * 3, 0);
v4f32 _k64 = (v4f32)__msa_ld_w(kptr + 4 * 4, 0);
v4f32 _k65 = (v4f32)__msa_ld_w(kptr + 4 * 5, 0);
v4f32 _k66 = (v4f32)__msa_ld_w(kptr + 4 * 6, 0);
kptr -= 4 * 42;
v4i32 _r6 = __msa_ld_w(r6, 0);
v4i32 _r6n = __msa_ld_w(r6 + 4, 0);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r6, 0), _k60);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r6, 1), _k61);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r6, 2), _k62);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r6, 3), _k63);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r6n, 0), _k64);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r6n, 1), _k65);
_sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_r6n, 2), _k66);
__msa_st_w((v4i32)_sum0, outptr0, 0);
outptr0 += 4;
r0 += 2;
r1 += 2;
r2 += 2;
r3 += 2;
r4 += 2;
r5 += 2;
r6 += 2;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
r3 += tailstep;
r4 += tailstep;
r5 += tailstep;
r6 += tailstep;
}
}
}
}
|
wand-view.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W W AAA N N DDDD %
% W W A A NN N D D %
% W W W AAAAA N N N D D %
% WW WW A A N NN D D %
% W W A A N N DDDD %
% %
% V V IIIII EEEEE W W %
% V V I E W W %
% V V I EEE W W W %
% V V I E WW WW %
% V IIIII EEEEE W W %
% %
% %
% MagickWand Wand View Methods %
% %
% Software Design %
% Cristy %
% March 2003 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "MagickWand/studio.h"
#include "MagickWand/MagickWand.h"
#include "MagickWand/magick-wand-private.h"
#include "MagickWand/wand.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/thread-private.h"
/*
Define declarations.
*/
#define WandViewId "WandView"
/*
Typedef declarations.
*/
struct _WandView
{
size_t
id;
char
name[MagickPathExtent],
*description;
RectangleInfo
extent;
MagickWand
*wand;
Image
*image;
CacheView
*view;
PixelWand
***pixel_wands;
ExceptionInfo
*exception;
MagickBooleanType
debug;
size_t
signature;
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e W a n d V i e w %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneWandView() makes a copy of the specified wand view.
%
% The format of the CloneWandView method is:
%
% WandView *CloneWandView(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport WandView *CloneWandView(const WandView *wand_view)
{
WandView
*clone_view;
register ssize_t
i;
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == MagickWandSignature);
if (wand_view->debug != MagickFalse)
(void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand_view->name);
clone_view=(WandView *) AcquireMagickMemory(sizeof(*clone_view));
if (clone_view == (WandView *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
wand_view->name);
(void) ResetMagickMemory(clone_view,0,sizeof(*clone_view));
clone_view->id=AcquireWandId();
(void) FormatLocaleString(clone_view->name,MagickPathExtent,"%s-%.20g",
WandViewId,(double) clone_view->id);
clone_view->description=ConstantString(wand_view->description);
clone_view->image=CloneImage(wand_view->image,0,0,MagickTrue,
wand_view->exception);
clone_view->view=CloneCacheView(wand_view->view);
clone_view->extent=wand_view->extent;
clone_view->exception=AcquireExceptionInfo();
InheritException(clone_view->exception,wand_view->exception);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
clone_view->pixel_wands[i]=ClonePixelWands((const PixelWand **)
wand_view->pixel_wands[i],wand_view->extent.width);
clone_view->debug=wand_view->debug;
if (clone_view->debug != MagickFalse)
(void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",clone_view->name);
clone_view->signature=MagickWandSignature;
return(clone_view);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y W a n d V i e w %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyWandView() deallocates memory associated with a wand view.
%
% The format of the DestroyWandView method is:
%
% WandView *DestroyWandView(WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
static PixelWand ***DestroyPixelsThreadSet(PixelWand ***pixel_wands,
const size_t number_wands)
{
register ssize_t
i;
assert(pixel_wands != (PixelWand ***) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixel_wands[i] != (PixelWand **) NULL)
pixel_wands[i]=DestroyPixelWands(pixel_wands[i],number_wands);
pixel_wands=(PixelWand ***) RelinquishMagickMemory(pixel_wands);
return(pixel_wands);
}
WandExport WandView *DestroyWandView(WandView *wand_view)
{
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == MagickWandSignature);
wand_view->pixel_wands=DestroyPixelsThreadSet(wand_view->pixel_wands,
wand_view->extent.width);
wand_view->image=DestroyImage(wand_view->image);
wand_view->view=DestroyCacheView(wand_view->view);
wand_view->exception=DestroyExceptionInfo(wand_view->exception);
wand_view->signature=(~MagickWandSignature);
RelinquishWandId(wand_view->id);
wand_view=(WandView *) RelinquishMagickMemory(wand_view);
return(wand_view);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D u p l e x T r a n s f e r W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DuplexTransferWandViewIterator() iterates over three wand views in
% parallel and calls your transfer method for each scanline of the view. The
% source and duplex pixel extent is not confined to the image canvas-- that is
% you can include negative offsets or widths or heights that exceed the image
% dimension. However, the destination wand view is confined to the image
% canvas-- that is no negative offsets or widths or heights that exceed the
% image dimension are permitted.
%
% The callback signature is:
%
% MagickBooleanType DuplexTransferImageViewMethod(const WandView *source,
% const WandView *duplex,WandView *destination,const ssize_t y,
% const int thread_id,void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback transfer method that must be
% executed by a single thread at a time.
%
% The format of the DuplexTransferWandViewIterator method is:
%
% MagickBooleanType DuplexTransferWandViewIterator(WandView *source,
% WandView *duplex,WandView *destination,
% DuplexTransferWandViewMethod transfer,void *context)
%
% A description of each parameter follows:
%
% o source: the source wand view.
%
% o duplex: the duplex wand view.
%
% o destination: the destination wand view.
%
% o transfer: the transfer callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType DuplexTransferWandViewIterator(WandView *source,
WandView *duplex,WandView *destination,DuplexTransferWandViewMethod transfer,
void *context)
{
Image
*destination_image,
*source_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(source != (WandView *) NULL);
assert(source->signature == MagickWandSignature);
if (transfer == (DuplexTransferWandViewMethod) NULL)
return(MagickFalse);
source_image=source->wand->images;
destination_image=destination->wand->images;
status=SetImageStorageClass(destination_image,DirectClass,
destination->exception);
if (status == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=source->extent.height-source->extent.y;
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(source_image,destination_image,height,1)
#endif
for (y=source->extent.y; y < (ssize_t) source->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const Quantum
*magick_restrict duplex_pixels,
*magick_restrict pixels;
register ssize_t
x;
register Quantum
*magick_restrict destination_pixels;
if (status == MagickFalse)
continue;
pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y,
source->extent.width,1,source->exception);
if (pixels == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) source->extent.width; x++)
{
PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]);
pixels+=GetPixelChannels(source->image);
}
duplex_pixels=GetCacheViewVirtualPixels(duplex->view,duplex->extent.x,y,
duplex->extent.width,1,duplex->exception);
if (duplex_pixels == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) duplex->extent.width; x++)
{
PixelSetQuantumPixel(duplex->image,duplex_pixels,
duplex->pixel_wands[id][x]);
duplex_pixels+=GetPixelChannels(duplex->image);
}
destination_pixels=GetCacheViewAuthenticPixels(destination->view,
destination->extent.x,y,destination->extent.width,1,
destination->exception);
if (destination_pixels == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) destination->extent.width; x++)
{
PixelSetQuantumPixel(destination->image,destination_pixels,
destination->pixel_wands[id][x]);
destination_pixels+=GetPixelChannels(destination->image);
}
if (transfer(source,duplex,destination,y,id,context) == MagickFalse)
status=MagickFalse;
destination_pixels=GetCacheViewAuthenticPixels(destination->view,
destination->extent.x,y,destination->extent.width,1,
destination->exception);
for (x=0; x < (ssize_t) destination->extent.width; x++)
{
PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x],
destination_pixels);
destination_pixels+=GetPixelChannels(destination->image);
}
sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception);
if (sync == MagickFalse)
status=MagickFalse;
if (source_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_DuplexTransferWandViewIterator)
#endif
proceed=SetImageProgress(source_image,source->description,progress++,
source->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w E x c e p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewException() returns the severity, reason, and description of any
% error that occurs when utilizing a wand view.
%
% The format of the GetWandViewException method is:
%
% char *GetWandViewException(const WandView *wand_view,
% ExceptionType *severity)
%
% A description of each parameter follows:
%
% o wand_view: the pixel wand_view.
%
% o severity: the severity of the error is returned here.
%
*/
WandExport char *GetWandViewException(const WandView *wand_view,
ExceptionType *severity)
{
char
*description;
assert(wand_view != (const WandView *) NULL);
assert(wand_view->signature == MagickWandSignature);
if (wand_view->debug != MagickFalse)
(void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand_view->name);
assert(severity != (ExceptionType *) NULL);
*severity=wand_view->exception->severity;
description=(char *) AcquireQuantumMemory(2UL*MagickPathExtent,
sizeof(*description));
if (description == (char *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
wand_view->name);
*description='\0';
if (wand_view->exception->reason != (char *) NULL)
(void) CopyMagickString(description,GetLocaleExceptionMessage(
wand_view->exception->severity,wand_view->exception->reason),
MagickPathExtent);
if (wand_view->exception->description != (char *) NULL)
{
(void) ConcatenateMagickString(description," (",MagickPathExtent);
(void) ConcatenateMagickString(description,GetLocaleExceptionMessage(
wand_view->exception->severity,wand_view->exception->description),
MagickPathExtent);
(void) ConcatenateMagickString(description,")",MagickPathExtent);
}
return(description);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewExtent() returns the wand view extent.
%
% The format of the GetWandViewExtent method is:
%
% RectangleInfo GetWandViewExtent(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport RectangleInfo GetWandViewExtent(const WandView *wand_view)
{
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == MagickWandSignature);
return(wand_view->extent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewIterator() iterates over the wand view in parallel and calls
% your get method for each scanline of the view. The pixel extent is
% not confined to the image canvas-- that is you can include negative offsets
% or widths or heights that exceed the image dimension. Any updates to
% the pixels in your callback are ignored.
%
% The callback signature is:
%
% MagickBooleanType GetImageViewMethod(const WandView *source,
% const ssize_t y,const int thread_id,void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback get method that must be
% executed by a single thread at a time.
%
% The format of the GetWandViewIterator method is:
%
% MagickBooleanType GetWandViewIterator(WandView *source,
% GetWandViewMethod get,void *context)
%
% A description of each parameter follows:
%
% o source: the source wand view.
%
% o get: the get callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType GetWandViewIterator(WandView *source,
GetWandViewMethod get,void *context)
{
Image
*source_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(source != (WandView *) NULL);
assert(source->signature == MagickWandSignature);
if (get == (GetWandViewMethod) NULL)
return(MagickFalse);
source_image=source->wand->images;
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=source->extent.height-source->extent.y;
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(source_image,source_image,height,1)
#endif
for (y=source->extent.y; y < (ssize_t) source->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
register const Quantum
*pixels;
register ssize_t
x;
if (status == MagickFalse)
continue;
pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y,
source->extent.width,1,source->exception);
if (pixels == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) source->extent.width; x++)
{
PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]);
pixels+=GetPixelChannels(source->image);
}
if (get(source,y,id,context) == MagickFalse)
status=MagickFalse;
if (source_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_GetWandViewIterator)
#endif
proceed=SetImageProgress(source_image,source->description,progress++,
source->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewPixels() returns the wand view pixel_wands.
%
% The format of the GetWandViewPixels method is:
%
% PixelWand *GetWandViewPixels(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport PixelWand **GetWandViewPixels(const WandView *wand_view)
{
const int
id = GetOpenMPThreadId();
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == MagickWandSignature);
return(wand_view->pixel_wands[id]);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t W a n d V i e w W a n d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetWandViewWand() returns the magick wand associated with the wand view.
%
% The format of the GetWandViewWand method is:
%
% MagickWand *GetWandViewWand(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport MagickWand *GetWandViewWand(const WandView *wand_view)
{
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == MagickWandSignature);
return(wand_view->wand);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s W a n d V i e w %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsWandView() returns MagickTrue if the the parameter is verified as a wand
% view object.
%
% The format of the IsWandView method is:
%
% MagickBooleanType IsWandView(const WandView *wand_view)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
*/
WandExport MagickBooleanType IsWandView(const WandView *wand_view)
{
size_t
length;
if (wand_view == (const WandView *) NULL)
return(MagickFalse);
if (wand_view->signature != MagickWandSignature)
return(MagickFalse);
length=strlen(WandViewId);
if (LocaleNCompare(wand_view->name,WandViewId,length) != 0)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e w W a n d V i e w %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NewWandView() returns a wand view required for all other methods in the
% Wand View API.
%
% The format of the NewWandView method is:
%
% WandView *NewWandView(MagickWand *wand)
%
% A description of each parameter follows:
%
% o wand: the wand.
%
*/
static PixelWand ***AcquirePixelsThreadSet(const size_t number_wands)
{
PixelWand
***pixel_wands;
register ssize_t
i;
size_t
number_threads;
number_threads=GetOpenMPMaximumThreads();
pixel_wands=(PixelWand ***) AcquireQuantumMemory(number_threads,
sizeof(*pixel_wands));
if (pixel_wands == (PixelWand ***) NULL)
return((PixelWand ***) NULL);
(void) ResetMagickMemory(pixel_wands,0,number_threads*sizeof(*pixel_wands));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixel_wands[i]=NewPixelWands(number_wands);
if (pixel_wands[i] == (PixelWand **) NULL)
return(DestroyPixelsThreadSet(pixel_wands,number_wands));
}
return(pixel_wands);
}
WandExport WandView *NewWandView(MagickWand *wand)
{
ExceptionInfo
*exception;
WandView
*wand_view;
assert(wand != (MagickWand *) NULL);
assert(wand->signature == MagickWandSignature);
wand_view=(WandView *) AcquireMagickMemory(sizeof(*wand_view));
if (wand_view == (WandView *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
(void) ResetMagickMemory(wand_view,0,sizeof(*wand_view));
wand_view->id=AcquireWandId();
(void) FormatLocaleString(wand_view->name,MagickPathExtent,"%s-%.20g",
WandViewId,(double) wand_view->id);
wand_view->description=ConstantString("WandView");
wand_view->wand=wand;
exception=AcquireExceptionInfo();
wand_view->view=AcquireVirtualCacheView(wand_view->wand->images,exception);
wand_view->extent.width=wand->images->columns;
wand_view->extent.height=wand->images->rows;
wand_view->pixel_wands=AcquirePixelsThreadSet(wand_view->extent.width);
wand_view->exception=exception;
if (wand_view->pixel_wands == (PixelWand ***) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
wand_view->debug=IsEventLogging();
wand_view->signature=MagickWandSignature;
return(wand_view);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% N e w W a n d V i e w E x t e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% NewWandViewExtent() returns a wand view required for all other methods
% in the Wand View API.
%
% The format of the NewWandViewExtent method is:
%
% WandView *NewWandViewExtent(MagickWand *wand,const ssize_t x,
% const ssize_t y,const size_t width,const size_t height)
%
% A description of each parameter follows:
%
% o wand: the magick wand.
%
% o x,y,columns,rows: These values define the perimeter of a extent of
% pixel_wands view.
%
*/
WandExport WandView *NewWandViewExtent(MagickWand *wand,const ssize_t x,
const ssize_t y,const size_t width,const size_t height)
{
ExceptionInfo
*exception;
WandView
*wand_view;
assert(wand != (MagickWand *) NULL);
assert(wand->signature == MagickWandSignature);
wand_view=(WandView *) AcquireMagickMemory(sizeof(*wand_view));
if (wand_view == (WandView *) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
(void) ResetMagickMemory(wand_view,0,sizeof(*wand_view));
wand_view->id=AcquireWandId();
(void) FormatLocaleString(wand_view->name,MagickPathExtent,"%s-%.20g",
WandViewId,(double) wand_view->id);
wand_view->description=ConstantString("WandView");
exception=AcquireExceptionInfo();
wand_view->view=AcquireVirtualCacheView(wand_view->wand->images,exception);
wand_view->wand=wand;
wand_view->extent.width=width;
wand_view->extent.height=height;
wand_view->extent.x=x;
wand_view->extent.y=y;
wand_view->exception=exception;
wand_view->pixel_wands=AcquirePixelsThreadSet(wand_view->extent.width);
if (wand_view->pixel_wands == (PixelWand ***) NULL)
ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
wand_view->debug=IsEventLogging();
wand_view->signature=MagickWandSignature;
return(wand_view);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t W a n d V i e w D e s c r i p t i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetWandViewDescription() associates a description with an image view.
%
% The format of the SetWandViewDescription method is:
%
% void SetWandViewDescription(WandView *image_view,const char *description)
%
% A description of each parameter follows:
%
% o wand_view: the wand view.
%
% o description: the wand view description.
%
*/
MagickExport void SetWandViewDescription(WandView *wand_view,
const char *description)
{
assert(wand_view != (WandView *) NULL);
assert(wand_view->signature == MagickWandSignature);
wand_view->description=ConstantString(description);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetWandViewIterator() iterates over the wand view in parallel and calls
% your set method for each scanline of the view. The pixel extent is
% confined to the image canvas-- that is no negative offsets or widths or
% heights that exceed the image dimension. The pixels are initiallly
% undefined and any settings you make in the callback method are automagically
% synced back to your image.
%
% The callback signature is:
%
% MagickBooleanType SetImageViewMethod(ImageView *destination,
% const ssize_t y,const int thread_id,void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback set method that must be
% executed by a single thread at a time.
%
% The format of the SetWandViewIterator method is:
%
% MagickBooleanType SetWandViewIterator(WandView *destination,
% SetWandViewMethod set,void *context)
%
% A description of each parameter follows:
%
% o destination: the wand view.
%
% o set: the set callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType SetWandViewIterator(WandView *destination,
SetWandViewMethod set,void *context)
{
Image
*destination_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(destination != (WandView *) NULL);
assert(destination->signature == MagickWandSignature);
if (set == (SetWandViewMethod) NULL)
return(MagickFalse);
destination_image=destination->wand->images;
status=SetImageStorageClass(destination_image,DirectClass,
destination->exception);
if (status == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=destination->extent.height-destination->extent.y;
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(destination_image,destination_image,height,1)
#endif
for (y=destination->extent.y; y < (ssize_t) destination->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register ssize_t
x;
register Quantum
*magick_restrict pixels;
if (status == MagickFalse)
continue;
pixels=GetCacheViewAuthenticPixels(destination->view,destination->extent.x,
y,destination->extent.width,1,destination->exception);
if (pixels == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
if (set(destination,y,id,context) == MagickFalse)
status=MagickFalse;
for (x=0; x < (ssize_t) destination->extent.width; x++)
{
PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x],
pixels);
pixels+=GetPixelChannels(destination->image);
}
sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception);
if (sync == MagickFalse)
status=MagickFalse;
if (destination_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_SetWandViewIterator)
#endif
proceed=SetImageProgress(destination_image,destination->description,
progress++,destination->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f e r W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransferWandViewIterator() iterates over two wand views in parallel and
% calls your transfer method for each scanline of the view. The source pixel
% extent is not confined to the image canvas-- that is you can include
% negative offsets or widths or heights that exceed the image dimension.
% However, the destination wand view is confined to the image canvas-- that
% is no negative offsets or widths or heights that exceed the image dimension
% are permitted.
%
% The callback signature is:
%
% MagickBooleanType TransferImageViewMethod(const WandView *source,
% WandView *destination,const ssize_t y,const int thread_id,
% void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback transfer method that must be
% executed by a single thread at a time.
%
% The format of the TransferWandViewIterator method is:
%
% MagickBooleanType TransferWandViewIterator(WandView *source,
% WandView *destination,TransferWandViewMethod transfer,void *context)
%
% A description of each parameter follows:
%
% o source: the source wand view.
%
% o destination: the destination wand view.
%
% o transfer: the transfer callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType TransferWandViewIterator(WandView *source,
WandView *destination,TransferWandViewMethod transfer,void *context)
{
Image
*destination_image,
*source_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(source != (WandView *) NULL);
assert(source->signature == MagickWandSignature);
if (transfer == (TransferWandViewMethod) NULL)
return(MagickFalse);
source_image=source->wand->images;
destination_image=destination->wand->images;
status=SetImageStorageClass(destination_image,DirectClass,
destination->exception);
if (status == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=source->extent.height-source->extent.y;
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(source_image,destination_image,height,1)
#endif
for (y=source->extent.y; y < (ssize_t) source->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register const Quantum
*magick_restrict pixels;
register ssize_t
x;
register Quantum
*magick_restrict destination_pixels;
if (status == MagickFalse)
continue;
pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y,
source->extent.width,1,source->exception);
if (pixels == (const Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) source->extent.width; x++)
{
PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]);
pixels+=GetPixelChannels(source->image);
}
destination_pixels=GetCacheViewAuthenticPixels(destination->view,
destination->extent.x,y,destination->extent.width,1,
destination->exception);
if (destination_pixels == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) destination->extent.width; x++)
{
PixelSetQuantumPixel(destination->image,destination_pixels,
destination->pixel_wands[id][x]);
destination_pixels+=GetPixelChannels(destination->image);
}
if (transfer(source,destination,y,id,context) == MagickFalse)
status=MagickFalse;
destination_pixels=GetCacheViewAuthenticPixels(destination->view,
destination->extent.x,y,destination->extent.width,1,
destination->exception);
for (x=0; x < (ssize_t) destination->extent.width; x++)
{
PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x],
destination_pixels);
destination_pixels+=GetPixelChannels(destination->image);
}
sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception);
if (sync == MagickFalse)
status=MagickFalse;
if (source_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_TransferWandViewIterator)
#endif
proceed=SetImageProgress(source_image,source->description,progress++,
source->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U p d a t e W a n d V i e w I t e r a t o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UpdateWandViewIterator() iterates over the wand view in parallel and calls
% your update method for each scanline of the view. The pixel extent is
% confined to the image canvas-- that is no negative offsets or widths or
% heights that exceed the image dimension are permitted. Updates to pixels
% in your callback are automagically synced back to the image.
%
% The callback signature is:
%
% MagickBooleanType UpdateImageViewMethod(WandView *source,const ssize_t y,
% const int thread_id,void *context)
%
% Use this pragma if the view is not single threaded:
%
% #pragma omp critical
%
% to define a section of code in your callback update method that must be
% executed by a single thread at a time.
%
% The format of the UpdateWandViewIterator method is:
%
% MagickBooleanType UpdateWandViewIterator(WandView *source,
% UpdateWandViewMethod update,void *context)
%
% A description of each parameter follows:
%
% o source: the source wand view.
%
% o update: the update callback method.
%
% o context: the user defined context.
%
*/
WandExport MagickBooleanType UpdateWandViewIterator(WandView *source,
UpdateWandViewMethod update,void *context)
{
Image
*source_image;
MagickBooleanType
status;
MagickOffsetType
progress;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
size_t
height;
#endif
ssize_t
y;
assert(source != (WandView *) NULL);
assert(source->signature == MagickWandSignature);
if (update == (UpdateWandViewMethod) NULL)
return(MagickFalse);
source_image=source->wand->images;
status=SetImageStorageClass(source_image,DirectClass,source->exception);
if (status == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
height=source->extent.height-source->extent.y;
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(source_image,source_image,height,1)
#endif
for (y=source->extent.y; y < (ssize_t) source->extent.height; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register ssize_t
x;
register Quantum
*magick_restrict pixels;
if (status == MagickFalse)
continue;
pixels=GetCacheViewAuthenticPixels(source->view,source->extent.x,y,
source->extent.width,1,source->exception);
if (pixels == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) source->extent.width; x++)
{
PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]);
pixels+=GetPixelChannels(source->image);
}
if (update(source,y,id,context) == MagickFalse)
status=MagickFalse;
for (x=0; x < (ssize_t) source->extent.width; x++)
{
PixelGetQuantumPixel(source->image,source->pixel_wands[id][x],pixels);
pixels+=GetPixelChannels(source->image);
}
sync=SyncCacheViewAuthenticPixels(source->view,source->exception);
if (sync == MagickFalse)
status=MagickFalse;
if (source_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickWand_UpdateWandViewIterator)
#endif
proceed=SetImageProgress(source_image,source->description,progress++,
source->extent.height);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
return(status);
}
|
GxB_BinaryOp_xtype_name.c | //------------------------------------------------------------------------------
// GxB_BinaryOp_xtype_name: return the type_name of x for z=f(x,y)
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
#include "GB.h"
GrB_Info GxB_BinaryOp_xtype_name // return the name of the type of x
(
char *type_name, // name of the type (char array of size at least
// GxB_MAX_NAME_LEN, owned by the user application).
const GrB_BinaryOp binaryop
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GB_WHERE1 ("GxB_BinaryOp_xtype_name (type_name, op)") ;
GB_RETURN_IF_NULL (type_name) ;
GB_RETURN_IF_NULL_OR_FAULTY (binaryop) ;
ASSERT_BINARYOP_OK (binaryop, "binaryop for xtype_name", GB0) ;
//--------------------------------------------------------------------------
// get the type_name
//--------------------------------------------------------------------------
memcpy (type_name, binaryop->xtype->name, GxB_MAX_NAME_LEN) ;
#pragma omp flush
return (GrB_SUCCESS) ;
}
|
GB_unop__identity_bool_int8.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_bool_int8
// op(A') function: GB_unop_tran__identity_bool_int8
// C type: bool
// A type: int8_t
// cast: bool cij = (bool) aij
// unaryop: cij = aij
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int8_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
bool z = (bool) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
int8_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
bool z = (bool) aij ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_bool_int8
(
bool *Cx, // Cx and Ax may be aliased
const int8_t *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (int8_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
int8_t aij = Ax [p] ;
bool z = (bool) 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 ;
int8_t aij = Ax [p] ;
bool z = (bool) 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_bool_int8
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
sumavectores_openmp.c | #include <omp.h>
#include <stdio.h>
#include <stdlib.h>
FILE *archivo;
int main(int argc, char **argv)
{
int i, j, k;
int tam_vector = atoi(argv[1]);
long long int tam_matriz = tam_vector * tam_vector;
float *a = (float *) malloc (tam_vector * sizeof(float));
float *b = (float *) malloc (tam_vector * sizeof(float));
float *c = (float *) malloc (tam_vector * sizeof(float));
/* Asignamos el numero de hilos deseados */
omp_set_num_threads(atoi(argv[2]));
//printf("Hilos: %d\nTamano: %d\n", atoi(argv[2]), tam_vector);
/* Se llenan los vectores con valores iniciales aleatorios */
#pragma omp parallel
{
#pragma omp for
for (i = 0; i < tam_vector; ++i)
{
a[i] = rand() / (float) RAND_MAX;
b[i] = rand() / (float) RAND_MAX;
c[i] = a[i] + b[i];
}
}
// Guarda el vector suma en un archivo de salida
// for (i = 0; i < tam_vector; ++i)
// {
// fprintf(archivo, "%2.4f \n", c[i]);
// }
// fclose(archivo);
return 0;
}
|
RCCE_minimum.c |
/*
* Copyright 2010 Carsten Clauss, Chair for Operating Systems,
* RWTH Aachen University
*
* 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 <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "RCCE.h"
#undef _SCCPRAM_PUT_REMOTE_
extern t_vcharp RCCE_malloc(size_t);
extern int RCCE_put(t_vcharp, t_vcharp, int, int);
extern int RCCE_get(t_vcharp, t_vcharp, int, int);
extern int RCCE_acquire_lock(int);
extern int RCCE_release_lock(int);
#define MAX_STEPS 1000*10120
#define OCCURRENCE 100
#undef _TOKEN_PASSING_
#undef _MASTER_CORE_
#undef _MASTER_TREE_
#pragma omp thread_private(stamp_t, nuM_ranks, my_arnk, steps)
#pragma omp thread_private(my_token, global_tokens, remote_token)
#pragma omp thread_private(distance, neighbor, val_array)
typedef long long int stamp_t;
typedef struct _token_t
{
stamp_t steps;
int rank;
int exit;
} token_t;
int num_ranks;
int my_rank;
stamp_t steps;
token_t my_token;
token_t *global_tokens;
int distance = 1;
int neighbor;
volatile unsigned char val_array[RCCE_LINE_SIZE];
token_t* remote_token;
#ifdef _TOKEN_PASSING_
void stop_and_check()
{
#ifndef _SCCPRAM_PUT_REMOTE_
neighbor = RCCE_ue() - distance;
if(neighbor < 0) neighbor = neighbor + RCCE_num_ues();
#else
neighbor = RCCE_ue() + distance;
if( neighbor > RCCE_num_ues() - 1 ) neighbor = neighbor - RCCE_num_ues();
#endif
if(neighbor != RCCE_ue())
{
// do the token-passing:
while(1)
{
#ifndef _SCCPRAM_PUT_REMOTE_
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, neighbor);
#else
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, RCCE_ue() );
#endif
remote_token = (token_t*)val_array;
//printf("(%d|%lld) neighbor: %d|%lld / my_token: %d|%lld\n", RCCE_ue(), steps, remote_token->rank, remote_token->steps, my_token.rank, my_token.steps);
if(remote_token->exit)
{
int current = neighbor;
// my current neighbor is atually finished --> determine a new neighbor:
distance++;
#ifndef _SCCPRAM_PUT_REMOTE_
neighbor = RCCE_ue() - distance;
if(neighbor < 0) neighbor = neighbor + RCCE_num_ues();
#else
neighbor = RCCE_ue() + distance;
if( neighbor > RCCE_num_ues() - 1 ) neighbor = neighbor - RCCE_num_ues();
#endif
if(neighbor == RCCE_ue())
{
// there is no other neighbor still running --> go on!
break;
}
else
{
// restart token-passing with new neighbor...
continue;
}
}
if(remote_token->rank == RCCE_ue())
{
// my own rank has rounded:
if(remote_token->steps == steps)
{
// go on!
break;
}
else
{
// update my token:
my_token.steps = steps;
my_token.rank = RCCE_ue();
#ifndef _SCCPRAM_PUT_REMOTE_
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
#else
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, neighbor);
#endif
}
}
else
{
if( (steps < remote_token->steps) || ((steps == remote_token->steps) && (RCCE_ue() < remote_token->rank)) )
{
// update my token:
my_token.steps = steps;
my_token.rank = RCCE_ue();
#ifndef _SCCPRAM_PUT_REMOTE_
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
#else
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, neighbor);
#endif
}
else
{
if( (remote_token->rank != my_token.rank) || (remote_token->steps != my_token.steps) )
{
// forward remote token:
memcpy(&my_token, remote_token, sizeof(token_t));
#ifndef _SCCPRAM_PUT_REMOTE_
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
#else
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, neighbor);
#endif
}
}
}
}
}
}
#else
#if defined(_MASTER_CORE_) || defined(_MASTER_TREE_)
void stop_and_check()
{
while(1)
{
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, RCCE_ue());
remote_token = (token_t*)val_array;
// printf("RANK %d: %lld\n", my_rank, steps); fflush(stdout); sleep(1);
if(remote_token->exit) break;
}
}
#else
void stop_and_check()
{
int i;
int winner_rank = my_rank;
stamp_t winner_steps = steps;
while(1)
{
winner_rank = my_rank;
winner_steps = steps;
for(i=0; i<num_ranks; i++)
{
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, i);
remote_token = (token_t*)val_array;
if(remote_token->steps < winner_steps)
{
winner_steps = remote_token->steps;
winner_rank = remote_token->rank;
}
}
if(winner_rank == my_rank) break;
}
}
#endif
#endif
#ifdef _MASTER_CORE_
void one_single_master()
{
int i, j;
int winner_rank;
int winner_flag;
stamp_t winner_steps;
int count;
count = 0;
while(1)
{
winner_flag = 0;
for(i=0,j=0; i<num_ranks - 1; i++)
{
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, i);
remote_token = (token_t*)val_array;
if( (!j) || (remote_token->steps < winner_steps) )
{
if(remote_token->exit == 0)
{
j=1;
winner_steps = remote_token->steps;
winner_rank = remote_token->rank;
winner_flag = 1;
}
}
}
if(winner_flag)
{
my_token.steps = winner_steps;
my_token.rank = winner_rank;
my_token.exit = 1;
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, winner_rank);
}
count++;
if(count == 1000)
{
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, num_ranks-1);
remote_token = (token_t*)val_array;
if(remote_token->exit == num_ranks - 1) break;
count = 0;
}
}
}
#endif
#ifdef _MASTER_TREE_
void multiple_masters(int flag)
{
int i;
int winner_rank;
int winner_flag;
stamp_t winner_steps;
int start_rank;
int num_ranks;
int count;
if(flag)
{
start_rank = 32 + (my_rank-40) * 2;
num_ranks = 2;
}
else
{
start_rank = (my_rank - 32) * 4;
num_ranks = 4;
}
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
count = 0;
while(1)
{
winner_flag = 0;
for(i=start_rank; i<start_rank + num_ranks; i++)
{
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, i);
remote_token = (token_t*)val_array;
if( (i==start_rank) || (remote_token->steps < winner_steps) )
{
winner_steps = remote_token->steps;
winner_rank = remote_token->rank;
winner_flag = 1;
}
}
if(winner_flag)
{
my_token.steps = winner_steps;
my_token.rank = winner_rank;
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
}
count++;
if(count == 1000)
{
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, 47);
remote_token = (token_t*)val_array;
if(remote_token->exit >= 32) break;
count = 0;
}
}
}
void super_master()
{
int i;
int winner_rank;
int winner_flag;
stamp_t winner_steps;
int start_rank;
int count;
int old_winner_rank = -1;
stamp_t old_winner_steps = 0;
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
while(1)
{
winner_flag = 0;
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, 44);
remote_token = (token_t*)val_array;
winner_steps = remote_token->steps;
winner_rank = remote_token->rank;
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, 45);
remote_token = (token_t*)val_array;
if(remote_token->steps < winner_steps)
{
winner_steps = remote_token->steps;
winner_rank = remote_token->rank;
}
if( (winner_steps > old_winner_steps) || ( (winner_steps == old_winner_steps) && (winner_rank != old_winner_rank) ) )
{
winner_flag = 1;
old_winner_rank = winner_rank;
old_winner_steps = winner_steps;
}
if( winner_flag && (winner_rank < 32) && (winner_rank % 2 == RCCE_ue() % 2) )
{
my_token.steps = winner_steps;
my_token.rank = winner_rank;
my_token.exit = 1;
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, winner_rank);
}
count++;
if(count == 1000)
{
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, 47);
remote_token = (token_t*)val_array;
if(remote_token->exit >= 32) break;
count = 0;
}
}
}
#endif
int RCCE_APP(int argc, char **argv)
{
int i, j;
double timer;
RCCE_init(&argc, &argv);
my_rank = RCCE_ue();
num_ranks = RCCE_num_ues();
srand(my_rank);
global_tokens = (token_t*)RCCE_malloc(RCCE_LINE_SIZE);
my_token.steps = 0;
my_token.exit = 0;
my_token.rank = RCCE_ue();
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
RCCE_barrier(&RCCE_COMM_WORLD);
#ifdef _TOKEN_PASSING_
if(my_rank == 0) printf("MINIMUM started with %d procs and TOKEN PASSING ...\n", num_ranks); fflush(stdout);
#else
#ifdef _MASTER_CORE_
if(my_rank == 0) printf("MINIMUM started with %d procs and MASTER CORE ...\n", num_ranks); fflush(stdout);
#else
#ifdef _MASTER_TREE_
if(my_rank == 0) printf("MINIMUM started with %d procs and MASTER TREE ...\n", num_ranks); fflush(stdout);
#else
if(my_rank == 0) printf("MINIMUM started with %d procs and GLOBAL VIEW ...\n", num_ranks); fflush(stdout);
#endif
#endif
#endif
RCCE_barrier(&RCCE_COMM_WORLD);
timer = RCCE_wtime() - timer;
#ifdef _MASTER_CORE_
if(my_rank == RCCE_num_ues()-1) one_single_master();
else for(steps=0; steps < MAX_STEPS / (num_ranks -1); steps++)
#else
#ifdef _MASTER_TREE_
if(my_rank >= 32)
{
if(my_rank < 40) multiple_masters(0);
else if(my_rank < 46) multiple_masters(1);
else super_master();
}
else for(steps=0; steps < MAX_STEPS / 32; steps++)
#else
for(steps=0; steps < MAX_STEPS / num_ranks; steps++)
#endif
#endif
{
if( (rand() % OCCURRENCE) == 0 )
{
stop_and_check();
}
my_token.steps = steps;
my_token.rank = RCCE_ue();
my_token.exit = 0;
#ifndef _SCCPRAM_PUT_REMOTE_
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
#else
neighbor = RCCE_ue() + distance;
if( neighbor > RCCE_num_ues() - 1 ) neighbor = neighbor - RCCE_num_ues();
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, neighbor);
#endif
}
#if defined(_MASTER_CORE_) || defined(_MASTER_TREE_)
RCCE_acquire_lock(num_ranks-1);
RCCE_get(val_array, (t_vcharp)global_tokens, RCCE_LINE_SIZE, num_ranks-1);
remote_token = (token_t*)val_array;
remote_token->exit++;
RCCE_put((t_vcharp)global_tokens, val_array, RCCE_LINE_SIZE, num_ranks-1);
RCCE_release_lock(num_ranks-1);
#ifdef _MASTER_TREE_
if(my_rank < 32)
{
my_token.steps = steps;
my_token.rank = RCCE_ue();
my_token.exit = 1;
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
}
#endif
#else
my_token.steps = steps;
my_token.rank = RCCE_ue();
my_token.exit = 1;
RCCE_put((t_vcharp)global_tokens, (t_vcharp)&my_token, RCCE_LINE_SIZE, RCCE_ue());
#endif
RCCE_barrier(&RCCE_COMM_WORLD);
timer = RCCE_wtime() - timer;
//printf("EXIT: %d at %lld / count: %d\n", my_rank, steps, remote_token->exit); fflush(stdout);
if(my_rank == 0) printf("MINIMUM finished after %1.3lf sec.\n", timer); fflush(stdout);
RCCE_finalize();
return 0;
}
|
diffterm.gold.h | #include "common/common.hpp"
extern "C" void diffterm_gold (double *in_difflux_1, double *in_difflux_2, double *in_difflux_3, double *in_difflux_4, double *in_q_1, double *in_q_2, double *in_q_3, double *in_q_5, double *in_ux, double *in_uy, double *in_uz, double *in_vx, double *in_vy, double *in_vz, double *in_wx, double *in_wy, double *in_wz, int N) {
double (*difflux_1)[320][320] = (double (*)[320][320])in_difflux_1;
double (*difflux_2)[320][320] = (double (*)[320][320])in_difflux_2;
double (*difflux_3)[320][320] = (double (*)[320][320])in_difflux_3;
double (*difflux_4)[320][320] = (double (*)[320][320])in_difflux_4;
double (*q_1)[320][320] = (double (*)[320][320])in_q_1;
double (*q_2)[320][320] = (double (*)[320][320])in_q_2;
double (*q_3)[320][320] = (double (*)[320][320])in_q_3;
double (*q_5)[320][320] = (double (*)[320][320])in_q_5;
double (*ux)[320][320] = (double (*)[320][320])in_ux;
double (*uy)[320][320] = (double (*)[320][320])in_uy;
double (*uz)[320][320] = (double (*)[320][320])in_uz;
double (*vx)[320][320] = (double (*)[320][320])in_vx;
double (*vy)[320][320] = (double (*)[320][320])in_vy;
double (*vz)[320][320] = (double (*)[320][320])in_vz;
double (*wx)[320][320] = (double (*)[320][320])in_wx;
double (*wy)[320][320] = (double (*)[320][320])in_wy;
double (*wz)[320][320] = (double (*)[320][320])in_wz;
double dxinv0 = 0.01;
double dxinv1 = 0.02;
double dxinv2 = 0.03;
int t, i, j, k;
#pragma omp parallel
{
#pragma omp for private(j,i)
for (k = 4; k < N-4; k++) {
for (j = 4; j < N-4; j++) {
#pragma GCC ivdep
#pragma clang loop vectorize (enable) interleave(enable)
for (i = 4; i < N-4; i++) {
ux[k][j][i] = (0.8 * (q_1[k][j][i+1] - q_1[k][j][i-1]) + -0.2 * (q_1[k][j][i+2] - q_1[k][j][i-2]) + 0.038 * (q_1[k][j][i+3] - q_1[k][j][i-3]) + -0.0035 * (q_1[k][j][i+4] - q_1[k][j][i-4])) * dxinv0;
vx[k][j][i] = (0.8 * (q_2[k][j][i+1] - q_2[k][j][i-1]) + -0.2 * (q_2[k][j][i+2] - q_2[k][j][i-2]) + 0.038 * (q_2[k][j][i+3] - q_2[k][j][i-3]) + -0.0035 * (q_2[k][j][i+4] - q_2[k][j][i-4])) * dxinv0;
wx[k][j][i] = (0.8 * (q_3[k][j][i+1] - q_3[k][j][i-1]) + -0.2 * (q_3[k][j][i+2] - q_3[k][j][i-2]) + 0.038 * (q_3[k][j][i+3] - q_3[k][j][i-3]) + -0.0035 * (q_3[k][j][i+4] - q_3[k][j][i-4])) * dxinv0;
}
}
}
#pragma omp for private(j,i)
for (k = 4; k < N-4; k++) {
for (j = 4; j < N-4; j++) {
#pragma GCC ivdep
#pragma clang loop vectorize (enable) interleave(enable)
for (i = 4; i < N-4; i++) {
uy[k][j][i] = (0.8 * (q_1[k][j+1][i] - q_1[k][j-1][i]) + -0.2 * (q_1[k][j+2][i] - q_1[k][j-2][i]) + 0.038 * (q_1[k][j+3][i] - q_1[k][j-3][i]) + -0.0035 * (q_1[k][j+4][i] - q_1[k][j-4][i])) * dxinv1;
vy[k][j][i] = (0.8 * (q_2[k][j+1][i] - q_2[k][j-1][i]) + -0.2 * (q_2[k][j+2][i] - q_2[k][j-2][i]) + 0.038 * (q_2[k][j+3][i] - q_2[k][j-3][i]) + -0.0035 * (q_2[k][j+4][i] - q_2[k][j-4][i])) * dxinv1;
wy[k][j][i] = (0.8 * (q_3[k][j+1][i] - q_3[k][j-1][i]) + -0.2 * (q_3[k][j+2][i] - q_3[k][j-2][i]) + 0.038 * (q_3[k][j+3][i] - q_3[k][j-3][i]) + -0.0035 * (q_3[k][j+4][i] - q_3[k][j-4][i])) * dxinv1;
}
}
}
#pragma omp for private(j,i)
for (k = 4; k < N-4; k++) {
for (j = 4; j < N-4; j++) {
#pragma GCC ivdep
#pragma clang loop vectorize (enable) interleave(enable)
for (i = 4; i < N-4; i++) {
uz[k][j][i] = (0.8 * (q_1[k+1][j][i] - q_1[k-1][j][i]) + -0.2 * (q_1[k+2][j][i] - q_1[k-2][j][i]) + 0.038 * (q_1[k+3][j][i] - q_1[k-3][j][i]) + -0.0035 * (q_1[k+4][j][i] - q_1[k-4][j][i])) * dxinv2;
vz[k][j][i] = (0.8 * (q_2[k+1][j][i] - q_2[k-1][j][i]) + -0.2 * (q_2[k+2][j][i] - q_2[k-2][j][i]) + 0.038 * (q_2[k+3][j][i] - q_2[k-3][j][i]) + -0.0035 * (q_2[k+4][j][i] - q_2[k-4][j][i])) * dxinv2;
wz[k][j][i] = (0.8 * (q_3[k+1][j][i] - q_3[k-1][j][i]) + -0.2 * (q_3[k+2][j][i] - q_3[k-2][j][i]) + 0.038 * (q_3[k+3][j][i] - q_3[k-3][j][i]) + -0.0035 * (q_3[k+4][j][i] - q_3[k-4][j][i])) * dxinv2;
}
}
}
#pragma omp for private(j,i)
for (k = 4; k < N-4; k++) {
for (j = 4; j < N-4; j++) {
#pragma GCC ivdep
#pragma clang loop vectorize (enable) interleave(enable)
for (i = 4; i < N-4; i++) {
double uxx = (-2.847 * q_1[k][j][i]+1.6 * (q_1[k][j][i+1] + q_1[k][j][i-1]) + -0.2 * (q_1[k][j][i+2] + q_1[k][j][i-2]) + 0.0253 * (q_1[k][j][i+3] + q_1[k][j][i-3]) + -0.0017 * (q_1[k][j][i+4] + q_1[k][j][i-4])) * (dxinv0*dxinv0);
double uyy = (-2.847 * q_1[k][j][i]+1.6 * (q_1[k][j+1][i] + q_1[k][j-1][i]) + -0.2 * (q_1[k][j+2][i] + q_1[k][j-2][i]) + 0.0253 * (q_1[k][j+3][i] + q_1[k][j-3][i]) + -0.0017 * (q_1[k][j+4][i] + q_1[k][j-4][i])) * (dxinv1*dxinv1);
double uzz = (-2.847 * q_1[k][j][i]+1.6 * (q_1[k+1][j][i] + q_1[k-1][j][i]) + -0.2 * (q_1[k+2][j][i] + q_1[k-2][j][i]) + 0.0253 * (q_1[k+3][j][i] + q_1[k-3][j][i]) + -0.0017 * (q_1[k+4][j][i] + q_1[k-4][j][i])) * (dxinv2*dxinv2);
double vyx = (0.8 * (vy[k][j][i+1] - vy[k][j][i-1]) + -0.2 * (vy[k][j][i+2] - vy[k][j][i-2]) + 0.038 * (vy[k][j][i+3] - vy[k][j][i-3]) + -0.0035 * (vy[k][j][i+4] - vy[k][j][i-4])) * dxinv0;
double wzx = (0.8 * (wz[k][j][i+1] - wz[k][j][i-1]) + -0.2 * (wz[k][j][i+2] - wz[k][j][i-2]) + 0.038 * (wz[k][j][i+3] - wz[k][j][i-3]) + -0.0035 * (wz[k][j][i+4] - wz[k][j][i-4])) * dxinv0;
difflux_1[k][j][i] = 0.3311 * (1.333 * uxx + uyy + uzz + 0.333 * (vyx + wzx));
}
}
}
#pragma omp for private(j,i)
for (k = 4; k < N-4; k++) {
for (j = 4; j < N-4; j++) {
#pragma GCC ivdep
#pragma clang loop vectorize (enable) interleave(enable)
for (i = 4; i < N-4; i++) {
double vxx = (-2.847 * q_2[k][j][i]+1.6 * (q_2[k][j][i+1] + q_2[k][j][i-1]) + -0.2 * (q_2[k][j][i+2] + q_2[k][j][i-2]) + 0.0253 * (q_2[k][j][i+3] + q_2[k][j][i-3]) + -0.0017 * (q_2[k][j][i+4] + q_2[k][j][i-4])) * (dxinv0*dxinv0);
double vyy = (-2.847 * q_2[k][j][i]+1.6 * (q_2[k][j+1][i] + q_2[k][j-1][i]) + -0.2 * (q_2[k][j+2][i] + q_2[k][j-2][i]) + 0.0253 * (q_2[k][j+3][i] + q_2[k][j-3][i]) + -0.0017 * (q_2[k][j+4][i] + q_2[k][j-4][i])) * (dxinv1*dxinv1);
double vzz = (-2.847 * q_2[k][j][i]+1.6 * (q_2[k+1][j][i] + q_2[k-1][j][i]) + -0.2 * (q_2[k+2][j][i] + q_2[k-2][j][i]) + 0.0253 * (q_2[k+3][j][i] + q_2[k-3][j][i]) + -0.0017 * (q_2[k+4][j][i] + q_2[k-4][j][i])) * (dxinv2*dxinv2);
double uxy = (0.8 * (ux[k][j+1][i] - ux[k][j-1][i]) + -0.2 * (ux[k][j+2][i] - ux[k][j-2][i]) + 0.038 * (ux[k][j+3][i] - ux[k][j-3][i]) + -0.0035 * (ux[k][j+4][i] - ux[k][j-4][i])) * dxinv1;
double wzy = (0.8 * (wz[k][j+1][i] - wz[k][j-1][i]) + -0.2 * (wz[k][j+2][i] - wz[k][j-2][i]) + 0.038 * (wz[k][j+3][i] - wz[k][j-3][i]) + -0.0035 * (wz[k][j+4][i] - wz[k][j-4][i])) * dxinv1;
difflux_2[k][j][i] = 0.3311 * (vxx+1.333 * vyy + vzz + 0.333 * (uxy + wzy));
}
}
}
#pragma omp for private(j,i)
for (k = 4; k < N-4; k++) {
for (j = 4; j < N-4; j++) {
#pragma GCC ivdep
#pragma clang loop vectorize (enable) interleave(enable)
for (i = 4; i < N-4; i++) {
double wxx = (-2.847 * q_3[k][j][i]+1.6 * (q_3[k][j][i+1] + q_3[k][j][i-1]) + -0.2 * (q_3[k][j][i+2] + q_3[k][j][i-2]) + 0.0253 * (q_3[k][j][i+3] + q_3[k][j][i-3]) + -0.0017 * (q_3[k][j][i+4] + q_3[k][j][i-4])) * (dxinv0*dxinv0);
double wyy = (-2.847 * q_3[k][j][i]+1.6 * (q_3[k][j+1][i] + q_3[k][j-1][i]) + -0.2 * (q_3[k][j+2][i] + q_3[k][j-2][i]) + 0.0253 * (q_3[k][j+3][i] + q_3[k][j-3][i]) + -0.0017 * (q_3[k][j+4][i] + q_3[k][j-4][i])) * (dxinv1*dxinv1);
double wzz = (-2.847 * q_3[k][j][i]+1.6 * (q_3[k+1][j][i] + q_3[k-1][j][i]) + -0.2 * (q_3[k+2][j][i] + q_3[k-2][j][i]) + 0.0253 * (q_3[k+3][j][i] + q_3[k-3][j][i]) + -0.0017 * (q_3[k+4][j][i] + q_3[k-4][j][i])) * (dxinv2*dxinv2);
double uxz = (0.8 * (ux[k+1][j][i] - ux[k-1][j][i]) + -0.2 * (ux[k+2][j][i] - ux[k-2][j][i]) + 0.038 * (ux[k+3][j][i] - ux[k-3][j][i]) + -0.0035 * (ux[k+4][j][i] - ux[k-4][j][i])) * dxinv2;
double vyz = (0.8 * (vy[k+1][j][i] - vy[k-1][j][i]) + -0.2 * (vy[k+2][j][i] - vy[k-2][j][i]) + 0.038 * (vy[k+3][j][i] - vy[k-3][j][i]) + -0.0035 * (vy[k+4][j][i] - vy[k-4][j][i])) * dxinv2;
difflux_3[k][j][i] = 0.3311 * (wxx + wyy+1.333 * wzz + 0.333 * (uxz + vyz));
}
}
}
#pragma omp for private(j,i)
for (k = 4; k < N-4; k++) {
for (j = 4; j < N-4; j++) {
#pragma GCC ivdep
#pragma clang loop vectorize (enable) interleave(enable)
for (i = 4; i < N-4; i++) {
double txx = (-2.847 * q_5[k][j][i]+1.6 * (q_5[k][j][i+1] + q_5[k][j][i-1]) + -0.2 * (q_5[k][j][i+2] + q_5[k][j][i-2]) + 0.0253 * (q_5[k][j][i+3] + q_5[k][j][i-3]) + -0.0017 * (q_5[k][j][i+4] + q_5[k][j][i-4])) * (dxinv0*dxinv0);
double tyy = (-2.847 * q_5[k][j][i]+1.6 * (q_5[k][j+1][i] + q_5[k][j-1][i]) + -0.2 * (q_5[k][j+2][i] + q_5[k][j-2][i]) + 0.0253 * (q_5[k][j+3][i] + q_5[k][j-3][i]) + -0.0017 * (q_5[k][j+4][i] + q_5[k][j-4][i])) * (dxinv1*dxinv1);
double tzz = (-2.847 * q_5[k][j][i]+1.6 * (q_5[k+1][j][i] + q_5[k-1][j][i]) + -0.2 * (q_5[k+2][j][i] + q_5[k-2][j][i]) + 0.0253 * (q_5[k+3][j][i] + q_5[k-3][j][i]) + -0.0017 * (q_5[k+4][j][i] + q_5[k-4][j][i])) * (dxinv2*dxinv2);
double divu = 0.666 * (ux[k][j][i] + vy[k][j][i] + wz[k][j][i]);
double tauxx = 2.e0 * ux[k][j][i] - divu;
double tauyy = 2.e0 * vy[k][j][i] - divu;
double tauzz = 2.e0 * wz[k][j][i] - divu;
double tauxy = uy[k][j][i] + vx[k][j][i];
double tauxz = uz[k][j][i] + wx[k][j][i];
double tauyz = vz[k][j][i] + wy[k][j][i];
double mechwork = tauxx * ux[k][j][i] + tauyy * vy[k][j][i] + tauzz * wz[k][j][i] + (tauxy*tauxy) + (tauxz*tauxz) + (tauyz*tauyz);
mechwork = 0.3311 * mechwork + difflux_1[k][j][i] * q_1[k][j][i] + difflux_2[k][j][i] * q_2[k][j][i] + difflux_3[k][j][i] * q_3[k][j][i];
difflux_4[k][j][i] = 0.7112 * (txx + tyy + tzz) + mechwork;
}
}
}
}
}
|
gramschmidt.c | /**
* gramschmidt.c: This file was adapted from PolyBench/GPU 1.0 test
* suite to run on GPU with OpenMP 4.0 pragmas and OpenCL driver.
*
* http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU
*
* Contacts: Marcio M Pereira <mpereira@ic.unicamp.br>
* Rafael Cardoso F Sousa <rafael.cardoso@students.ic.unicamp.br>
* Luís Felipe Mattos <ra107822@students.ic.unicamp.br>
*/
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "BenchmarksUtil.h"
// define the error threshold for the results "not matching"
#define PERCENT_DIFF_ERROR_THRESHOLD 0.05
/* Problem size. */
#ifdef RUN_TEST
#define SIZE 1100
#elif RUN_BENCHMARK
#define SIZE 9600
#else
#define SIZE 1000
#endif
/* Problem size */
#define M SIZE
#define N SIZE
/* Can switch DATA_TYPE between float and double */
typedef float DATA_TYPE;
void gramschmidt(DATA_TYPE *A, DATA_TYPE *R, DATA_TYPE *Q) {
int i, j, k;
DATA_TYPE nrm;
for (k = 0; k < N; k++) {
nrm = 0;
for (i = 0; i < M; i++) {
nrm += A[i * N + k] * A[i * N + k];
}
R[k * N + k] = sqrt(nrm);
for (i = 0; i < M; i++) {
Q[i * N + k] = A[i * N + k] / R[k * N + k];
}
for (j = k + 1; j < N; j++) {
R[k * N + j] = 0;
for (i = 0; i < M; i++) {
R[k * N + j] += Q[i * N + k] * A[i * N + j];
}
for (i = 0; i < M; i++) {
A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j];
}
}
}
}
void gramschmidt_OMP(DATA_TYPE *A, DATA_TYPE *R, DATA_TYPE *Q) {
int i, j, k;
DATA_TYPE nrm;
#pragma omp target device(DEVICE_ID)
for (k = 0; k < N; k++) {
// CPU
nrm = 0;
for (i = 0; i < M; i++) {
nrm += A[i * N + k] * A[i * N + k];
}
R[k * N + k] = sqrt(nrm);
for (i = 0; i < M; i++) {
Q[i * N + k] = A[i * N + k] / R[k * N + k];
}
#pragma omp target map(to : R[ : M *N], Q[ : M *N]) map(tofrom : A[ : M *N])
#pragma omp parallel for schedule(static, 16)
for (j = k + 1; j < N; j++) {
R[k * N + j] = 0;
for (i = 0; i < M; i++) {
R[k * N + j] += Q[i * N + k] * A[i * N + j];
}
for (i = 0; i < M; i++) {
A[i * N + j] = A[i * N + j] - Q[i * N + k] * R[k * N + j];
}
}
}
}
void init_array(DATA_TYPE *A, DATA_TYPE *A2) {
int i, j;
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
A[i * N + j] = ((DATA_TYPE)(i + 1) * (j + 1)) / (M + 1);
A2[i * N + j] = A[i * N + j];
}
}
}
int compareResults(DATA_TYPE *A, DATA_TYPE *A_outputFromGpu) {
int i, j, fail;
fail = 0;
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
if (percentDiff(A[i * N + j], A_outputFromGpu[i * N + j]) >
PERCENT_DIFF_ERROR_THRESHOLD) {
fail++;
// printf("i: %d j: %d \n1: %f\n 2: %f\n", i, j, A[i*N + j],
// A_outputFromGpu[i*N + j]);
}
}
}
// Print results
printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f "
"Percent: %d\n",
PERCENT_DIFF_ERROR_THRESHOLD, fail);
return fail;
}
int main(int argc, char *argv[]) {
double t_start, t_end;
int fail = 0;
DATA_TYPE *A;
DATA_TYPE *A_outputFromGpu;
DATA_TYPE *R;
DATA_TYPE *Q;
A = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE));
A_outputFromGpu = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE));
R = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE));
Q = (DATA_TYPE *)malloc(M * N * sizeof(DATA_TYPE));
fprintf(stdout, "<< Gram-Schmidt decomposition >>\n");
init_array(A, A_outputFromGpu);
t_start = rtclock();
gramschmidt_OMP(A_outputFromGpu, R, Q);
t_end = rtclock();
fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end - t_start);
#ifdef RUN_TEST
t_start = rtclock();
gramschmidt(A, R, Q);
t_end = rtclock();
fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start);
fail = compareResults(A, A_outputFromGpu);
#endif
free(A);
free(A_outputFromGpu);
free(R);
free(Q);
return fail;
}
|
eavlDestinationTopologyScatterMapOp.h | // Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information.
#ifndef EAVL_DESTINATION_TOPOLOGY_SCATTER_MAP_OP_H
#define EAVL_DESTINATION_TOPOLOGY_SCATTER_MAP_OP_H
#include "eavlCUDA.h"
#include "eavlCellSet.h"
#include "eavlCellSetExplicit.h"
#include "eavlCellSetAllStructured.h"
#include "eavlDataSet.h"
#include "eavlArray.h"
#include "eavlOpDispatch.h"
#include "eavlOperation.h"
#include "eavlTopology.h"
#include "eavlException.h"
#include <time.h>
#ifdef HAVE_OPENMP
#include <omp.h>
#endif
#ifndef DOXYGEN
template <class CONN>
struct eavlDestinationTopologyScatterMapOp_CPU
{
static inline eavlArray::Location location() { return eavlArray::HOST; }
template <class F, class IN, class OUT, class INDEX>
static void call(int nitems, CONN &conn,
const IN inputs, OUT outputs,
INDEX indices, F &functor)
{
int *sparseindices = get<0>(indices).array;
int ids[MAX_LOCAL_TOPOLOGY_IDS];
#pragma omp parallel for private(ids)
for (int denseindex = 0; denseindex < nitems; ++denseindex)
{
int sparseindex = sparseindices[get<0>(indices).indexer.index(denseindex)];
int nids;
int shapeType = conn.GetElementComponents(sparseindex, nids, ids);
collect(sparseindex, outputs) = functor(shapeType, nids, ids,
collect(denseindex, inputs));
}
}
};
#if defined __CUDACC__
template <class CONN, class F, class IN, class OUT, class INDEX>
__global__ void
eavlDestinationTopologyScatterMapOp_kernel(int nitems, CONN conn,
const IN inputs, OUT outputs,
INDEX indices, F functor)
{
int *sparseindices = get<0>(indices).array;
const int numThreads = blockDim.x * gridDim.x;
const int threadID = blockIdx.x * blockDim.x + threadIdx.x;
int ids[MAX_LOCAL_TOPOLOGY_IDS];
for (int denseindex = threadID; denseindex < nitems; denseindex += numThreads)
{
int sparseindex = sparseindices[get<0>(indices).indexer.index(denseindex)];
int nids;
int shapeType = conn.GetElementComponents(sparseindex, nids, ids);
collect(sparseindex, outputs) = functor(shapeType, nids, ids,
collect(denseindex, inputs));
}
}
template <class CONN>
struct eavlDestinationTopologyScatterMapOp_GPU
{
static inline eavlArray::Location location() { return eavlArray::DEVICE; }
template <class F, class IN, class OUT, class INDEX>
static void call(int nitems, CONN &conn,
const IN inputs, OUT outputs,
INDEX indices, F &functor)
{
int numThreads = 256;
dim3 threads(numThreads, 1, 1);
dim3 blocks (32, 1, 1);
eavlDestinationTopologyScatterMapOp_kernel<<< blocks, threads >>>(nitems, conn,
inputs, outputs,
indices, functor);
CUDA_CHECK_ERROR();
}
};
#endif
#endif
// ****************************************************************************
// Class: eavlDestinationTopologyScatterMapOp
//
// Purpose:
/// Map from one element in a mesh to the same element, with
/// topological information passed along to the functor.
/// In this scatter version of the operation, the inputs (on the destination)
/// topology are sparsely indexed and the outputs are compacted, i.e.
/// the outputs are densely indexed 0 to n-1.
//
// Programmer: Jeremy Meredith
// Creation: August 1, 2013
//
// Modifications:
// ****************************************************************************
template <class I, class O, class INDEX, class F>
class eavlDestinationTopologyScatterMapOp : public eavlOperation
{
protected:
eavlCellSet *cells;
eavlTopology topology;
I inputs;
O outputs;
INDEX indices;
F functor;
public:
eavlDestinationTopologyScatterMapOp(eavlCellSet *c, eavlTopology t,
I i, O o, INDEX ind, F f)
: cells(c), topology(t), inputs(i), outputs(o), indices(ind), functor(f)
{
}
virtual void GoCPU()
{
eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells);
eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells);
int n = outputs.first.length();
if (elExp)
{
eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology);
eavlOpDispatch<eavlDestinationTopologyScatterMapOp_CPU<eavlExplicitConnectivity> >(n, conn, inputs, outputs, indices, functor);
}
else if (elStr)
{
eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology);
eavlOpDispatch<eavlDestinationTopologyScatterMapOp_CPU<eavlRegularConnectivity> >(n, conn, inputs, outputs, indices, functor);
}
}
virtual void GoGPU()
{
#ifdef HAVE_CUDA
eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells);
eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells);
int n = outputs.first.length();
if (elExp)
{
eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology);
conn.shapetype.NeedOnDevice();
conn.connectivity.NeedOnDevice();
conn.mapCellToIndex.NeedOnDevice();
eavlOpDispatch<eavlDestinationTopologyScatterMapOp_GPU<eavlExplicitConnectivity> >(n, conn, inputs, outputs, indices, functor);
conn.shapetype.NeedOnHost();
conn.connectivity.NeedOnHost();
conn.mapCellToIndex.NeedOnHost();
}
else if (elStr)
{
eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology);
eavlOpDispatch<eavlDestinationTopologyScatterMapOp_GPU<eavlRegularConnectivity> >(n, conn, inputs, outputs, indices, functor);
}
#else
THROW(eavlException,"Executing GPU code without compiling under CUDA compiler.");
#endif
}
};
// helper function for type deduction
template <class I, class O, class INDEX, class F>
eavlDestinationTopologyScatterMapOp<I,O,INDEX,F> *new_eavlDestinationTopologyScatterMapOp(eavlCellSet *c, eavlTopology t,
I i, O o, INDEX indices, F f)
{
return new eavlDestinationTopologyScatterMapOp<I,O,INDEX,F>(c,t,i,o,indices,f);
}
#endif
|
displacement_lagrangemultiplier_residual_frictional_contact_criteria.h | // KRATOS ___| | | |
// \___ \ __| __| | | __| __| | | __| _` | |
// | | | | | ( | | | | ( | |
// _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS
//
// License: BSD License
// license: StructuralMechanicsApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_RESIDUAL_FRICTIONAL_CONTACT_CRITERIA_H)
#define KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_RESIDUAL_FRICTIONAL_CONTACT_CRITERIA_H
/* System includes */
/* External includes */
/* Project includes */
#include "utilities/table_stream_utility.h"
#include "custom_strategies/custom_convergencecriterias/base_mortar_criteria.h"
#include "utilities/color_utilities.h"
#include "custom_utilities/active_set_utilities.h"
namespace Kratos
{
///@addtogroup ContactStructuralMechanicsApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@name Kratos Classes
///@{
/**
* @class DisplacementLagrangeMultiplierResidualFrictionalContactCriteria
* @ingroup ContactStructuralMechanicsApplication
* @brief Convergence criteria for contact problems (only for frictional cases)
* This class implements a convergence control based on nodal displacement and
* lagrange multiplier values. The error is evaluated separately for each of them, and
* relative and absolute tolerances for both must be specified.
* @author Vicente Mataix Ferrandiz
*/
template< class TSparseSpace,
class TDenseSpace >
class DisplacementLagrangeMultiplierResidualFrictionalContactCriteria
: public ConvergenceCriteria< TSparseSpace, TDenseSpace >
{
public:
///@name Type Definitions
///@{
/// Pointer definition of DisplacementLagrangeMultiplierResidualFrictionalContactCriteria
KRATOS_CLASS_POINTER_DEFINITION( DisplacementLagrangeMultiplierResidualFrictionalContactCriteria );
/// Local Flags
KRATOS_DEFINE_LOCAL_FLAG( ENSURE_CONTACT );
KRATOS_DEFINE_LOCAL_FLAG( PRINTING_OUTPUT );
KRATOS_DEFINE_LOCAL_FLAG( TABLE_IS_INITIALIZED );
KRATOS_DEFINE_LOCAL_FLAG( PURE_SLIP );
KRATOS_DEFINE_LOCAL_FLAG( INITIAL_RESIDUAL_IS_SET );
KRATOS_DEFINE_LOCAL_FLAG( INITIAL_STICK_RESIDUAL_IS_SET );
KRATOS_DEFINE_LOCAL_FLAG( INITIAL_SLIP_RESIDUAL_IS_SET );
/// The base class definition (and it subclasses)
typedef ConvergenceCriteria< TSparseSpace, TDenseSpace > BaseType;
typedef typename BaseType::TDataType TDataType;
typedef typename BaseType::DofsArrayType DofsArrayType;
typedef typename BaseType::TSystemMatrixType TSystemMatrixType;
typedef typename BaseType::TSystemVectorType TSystemVectorType;
/// The sparse space used
typedef TSparseSpace SparseSpaceType;
/// The r_table stream definition TODO: Replace by logger
typedef TableStreamUtility::Pointer TablePrinterPointerType;
/// The index type definition
typedef std::size_t IndexType;
/// The key type definition
typedef std::size_t KeyType;
///@}
///@name Life Cycle
///@{
/**
* @brief Default constructor
* @param DispRatioTolerance Relative tolerance for displacement residual error
* @param DispAbsTolerance Absolute tolerance for displacement residual error
* @param LMRatioTolerance Relative tolerance for lagrange multiplier residual error
* @param LMAbsTolerance Absolute tolerance for lagrange multiplier residual error
* @param EnsureContact To check if the contact is lost
* @param NormalTangentRatio Ratio between the normal and tangent that will accepted as converged
* @param pTable The pointer to the output r_table
* @param PrintingOutput If the output is going to be printed in a txt file
*/
explicit DisplacementLagrangeMultiplierResidualFrictionalContactCriteria(
const TDataType DispRatioTolerance,
const TDataType DispAbsTolerance,
const TDataType LMNormalRatioTolerance,
const TDataType LMNormalAbsTolerance,
const TDataType LMTangentRatioTolerance,
const TDataType LMTangentAbsTolerance,
const TDataType NormalTangentRatio,
const bool EnsureContact = false,
const bool PureSlip = false,
const bool PrintingOutput = false
) : BaseType()
{
// Set local flags
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::ENSURE_CONTACT, EnsureContact);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PRINTING_OUTPUT, PrintingOutput);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::TABLE_IS_INITIALIZED, false);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP, PureSlip);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_STICK_RESIDUAL_IS_SET, false);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_SLIP_RESIDUAL_IS_SET, false);
// The displacement residual
mDispRatioTolerance = DispRatioTolerance;
mDispAbsTolerance = DispAbsTolerance;
// The normal contact residual
mLMNormalRatioTolerance = LMNormalRatioTolerance;
mLMNormalAbsTolerance = LMNormalAbsTolerance;
// The tangent contact residual
mLMTangentRatioTolerance = LMTangentRatioTolerance;
mLMTangentAbsTolerance = LMTangentAbsTolerance;
// We get the ratio between the normal and tangent that will accepted as converged
mNormalTangentRatio = NormalTangentRatio;
}
/**
* @brief Default constructor (parameters)
* @param ThisParameters The configuration parameters
*/
explicit DisplacementLagrangeMultiplierResidualFrictionalContactCriteria( Parameters ThisParameters = Parameters(R"({})"))
: BaseType()
{
// The default parameters
Parameters default_parameters = Parameters(R"(
{
"ensure_contact" : false,
"pure_slip" : false,
"print_convergence_criterion" : false,
"residual_relative_tolerance" : 1.0e-4,
"residual_absolute_tolerance" : 1.0e-9,
"contact_residual_relative_tolerance" : 1.0e-4,
"contact_residual_absolute_tolerance" : 1.0e-9,
"frictional_contact_residual_relative_tolerance" : 1.0e-4,
"frictional_contact_residual_absolute_tolerance" : 1.0e-9
})" );
ThisParameters.ValidateAndAssignDefaults(default_parameters);
// The displacement residual
mDispRatioTolerance = ThisParameters["residual_relative_tolerance"].GetDouble();
mDispAbsTolerance = ThisParameters["residual_absolute_tolerance"].GetDouble();
// The normal contact residual
mLMNormalRatioTolerance = ThisParameters["contact_displacement_absolute_tolerance"].GetDouble();
mLMNormalAbsTolerance = ThisParameters["contact_residual_absolute_tolerance"].GetDouble();
// The tangent contact residual
mLMTangentRatioTolerance = ThisParameters["frictional_contact_residual_relative_tolerance"].GetDouble();
mLMTangentAbsTolerance = ThisParameters["frictional_contact_residual_absolute_tolerance"].GetDouble();
// We get the ratio between the normal and tangent that will accepted as converged
mNormalTangentRatio = ThisParameters["ratio_normal_tangent_threshold"].GetDouble();
// Set local flags
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::ENSURE_CONTACT, ThisParameters["ensure_contact"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PRINTING_OUTPUT, ThisParameters["print_convergence_criterion"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::TABLE_IS_INITIALIZED, false);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP, ThisParameters["pure_slip"].GetBool());
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_STICK_RESIDUAL_IS_SET, false);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_SLIP_RESIDUAL_IS_SET, false);
}
// Copy constructor.
DisplacementLagrangeMultiplierResidualFrictionalContactCriteria( DisplacementLagrangeMultiplierResidualFrictionalContactCriteria const& rOther )
:BaseType(rOther)
,mOptions(rOther.mOptions)
,mDispRatioTolerance(rOther.mDispRatioTolerance)
,mDispAbsTolerance(rOther.mDispAbsTolerance)
,mDispInitialResidualNorm(rOther.mDispInitialResidualNorm)
,mDispCurrentResidualNorm(rOther.mDispCurrentResidualNorm)
,mLMNormalRatioTolerance(rOther.mLMNormalRatioTolerance)
,mLMNormalAbsTolerance(rOther.mLMNormalAbsTolerance)
,mLMNormalInitialResidualNorm(rOther.mLMNormalInitialResidualNorm)
,mLMNormalCurrentResidualNorm(rOther.mLMNormalCurrentResidualNorm)
,mLMTangentRatioTolerance(rOther.mLMTangentRatioTolerance)
,mLMTangentAbsTolerance(rOther.mLMTangentAbsTolerance)
,mLMTangentStickInitialResidualNorm(rOther.mLMTangentStickInitialResidualNorm)
,mLMTangentStickCurrentResidualNorm(rOther.mLMTangentStickCurrentResidualNorm)
,mStickCounter(rOther.mStickCounter)
,mSlipCounter(rOther.mSlipCounter)
,mNormalTangentRatio(rOther.mNormalTangentRatio)
{
}
/// Destructor.
~DisplacementLagrangeMultiplierResidualFrictionalContactCriteria() override = default;
///@}
///@name Operators
///@{
/**
* @brief Compute relative and absolute error.
* @param rModelPart Reference to the ModelPart containing the contact problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual)
* @return true if convergence is achieved, false otherwise
*/
bool PostCriteria(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
if (SparseSpaceType::Size(rb) != 0) { //if we are solving for something
// Getting process info
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
// Compute the active set
if (!r_process_info[ACTIVE_SET_COMPUTED]) {
const array_1d<std::size_t, 2> is_converged = ActiveSetUtilities::ComputeALMFrictionalActiveSet(rModelPart, mOptions.Is(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP), this->GetEchoLevel());
// We save to the process info if the active set has converged
r_process_info[ACTIVE_SET_CONVERGED] = is_converged[0] == 0 ? true : false;
r_process_info[SLIP_SET_CONVERGED] = is_converged[1] == 0 ? true : false;
r_process_info[ACTIVE_SET_COMPUTED] = true;
}
// Initialize
TDataType disp_residual_solution_norm = 0.0, normal_lm_residual_solution_norm = 0.0, tangent_lm_stick_residual_solution_norm = 0.0, tangent_lm_slip_residual_solution_norm = 0.0;
IndexType disp_dof_num(0),lm_dof_num(0), lm_stick_dof_num(0), lm_slip_dof_num(0);
// The nodes array
auto& r_nodes_array = rModelPart.Nodes();
// First iterator
const auto it_dof_begin = rDofSet.begin();
// Auxiliar values
std::size_t dof_id = 0;
TDataType residual_dof_value = 0.0;
// Loop over Dofs
#pragma omp parallel for reduction(+:disp_residual_solution_norm, normal_lm_residual_solution_norm, tangent_lm_stick_residual_solution_norm, tangent_lm_slip_residual_solution_norm, disp_dof_num, lm_dof_num, lm_stick_dof_num, lm_slip_dof_num, dof_id,residual_dof_value)
for (int i = 0; i < static_cast<int>(rDofSet.size()); i++) {
auto it_dof = it_dof_begin + i;
if (it_dof->IsFree()) {
// The component of the residual
dof_id = it_dof->EquationId();
residual_dof_value = rb[dof_id];
const auto curr_var = it_dof->GetVariable();
if (curr_var == VECTOR_LAGRANGE_MULTIPLIER_X) {
// The normal of the node (TODO: how to solve this without accesing all the time to the database?)
const auto it_node = r_nodes_array.find(it_dof->Id());
const double normal_x = it_node->FastGetSolutionStepValue(NORMAL_X);
const TDataType normal_comp_residual = residual_dof_value * normal_x;
normal_lm_residual_solution_norm += std::pow(normal_comp_residual, 2);
if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP)) {
tangent_lm_slip_residual_solution_norm += std::pow(residual_dof_value - normal_comp_residual, 2);
++lm_slip_dof_num;
} else {
tangent_lm_stick_residual_solution_norm += std::pow(residual_dof_value - normal_comp_residual, 2);
++lm_stick_dof_num;
}
lm_dof_num++;
} else if (curr_var == VECTOR_LAGRANGE_MULTIPLIER_Y) {
// The normal of the node (TODO: how to solve this without accesing all the time to the database?)
const auto it_node = r_nodes_array.find(it_dof->Id());
const double normal_y = it_node->FastGetSolutionStepValue(NORMAL_Y);
const TDataType normal_comp_residual = residual_dof_value * normal_y;
normal_lm_residual_solution_norm += std::pow(normal_comp_residual, 2);
if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP)) {
tangent_lm_slip_residual_solution_norm += std::pow(residual_dof_value - normal_comp_residual, 2);
++lm_slip_dof_num;
} else {
tangent_lm_stick_residual_solution_norm += std::pow(residual_dof_value - normal_comp_residual, 2);
++lm_stick_dof_num;
}
lm_dof_num++;
} else if (curr_var == VECTOR_LAGRANGE_MULTIPLIER_Z) {
// The normal of the node (TODO: how to solve this without accesing all the time to the database?)
const auto it_node = r_nodes_array.find(it_dof->Id());
const double normal_z = it_node->FastGetSolutionStepValue(NORMAL_Z);
const TDataType normal_comp_residual = residual_dof_value * normal_z;
normal_lm_residual_solution_norm += std::pow(normal_comp_residual, 2);
if (it_node->Is(SLIP) || mOptions.Is(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP)) {
tangent_lm_slip_residual_solution_norm += std::pow(residual_dof_value - normal_comp_residual, 2);
++lm_slip_dof_num;
} else {
tangent_lm_stick_residual_solution_norm += std::pow(residual_dof_value - normal_comp_residual, 2);
++lm_stick_dof_num;
}
lm_dof_num++;
} else {
disp_residual_solution_norm += residual_dof_value * residual_dof_value;
disp_dof_num++;
}
}
}
// Auxiliar dofs counters
if (mStickCounter > 0) {
if (lm_stick_dof_num == 0) {
mStickCounter = 0;
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_STICK_RESIDUAL_IS_SET, false);
}
} else {
if (lm_stick_dof_num > 0) {
mStickCounter = lm_stick_dof_num;
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_STICK_RESIDUAL_IS_SET, false);
}
}
if (mSlipCounter > 0) {
if (lm_slip_dof_num == 0) {
mSlipCounter = 0;
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_SLIP_RESIDUAL_IS_SET, false);
}
} else {
if (lm_slip_dof_num > 0) {
mSlipCounter = lm_slip_dof_num;
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_SLIP_RESIDUAL_IS_SET, false);
}
}
mDispCurrentResidualNorm = disp_residual_solution_norm;
mLMNormalCurrentResidualNorm = normal_lm_residual_solution_norm;
mLMTangentStickCurrentResidualNorm = tangent_lm_stick_residual_solution_norm;
mLMTangentSlipCurrentResidualNorm = tangent_lm_slip_residual_solution_norm;
TDataType residual_disp_ratio = 1.0;
TDataType residual_normal_lm_ratio = 1.0;
TDataType residual_tangent_lm_stick_ratio = 1.0;
TDataType residual_tangent_lm_slip_ratio = 1.0;
// We initialize the solution
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET)) {
mDispInitialResidualNorm = (disp_residual_solution_norm == 0.0) ? 1.0 : disp_residual_solution_norm;
mLMNormalInitialResidualNorm = (normal_lm_residual_solution_norm == 0.0) ? 1.0 : normal_lm_residual_solution_norm;
residual_disp_ratio = 1.0;
residual_normal_lm_ratio = 1.0;
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, true);
}
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_STICK_RESIDUAL_IS_SET) && lm_stick_dof_num > 0) {
mLMTangentStickInitialResidualNorm = (tangent_lm_stick_residual_solution_norm == 0.0) ? 1.0 : tangent_lm_stick_residual_solution_norm;
residual_tangent_lm_stick_ratio = 1.0;
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_STICK_RESIDUAL_IS_SET, true);
}
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_SLIP_RESIDUAL_IS_SET) && lm_slip_dof_num > 0) {
mLMTangentSlipInitialResidualNorm = (tangent_lm_slip_residual_solution_norm == 0.0) ? 1.0 : tangent_lm_slip_residual_solution_norm;
residual_tangent_lm_slip_ratio = 1.0;
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_SLIP_RESIDUAL_IS_SET, true);
}
// We calculate the ratio of the displacements
residual_disp_ratio = mDispCurrentResidualNorm/mDispInitialResidualNorm;
// We calculate the ratio of the LM
residual_normal_lm_ratio = mLMNormalCurrentResidualNorm/mLMNormalInitialResidualNorm;
if (lm_stick_dof_num > 0) {
residual_tangent_lm_stick_ratio = mLMTangentStickCurrentResidualNorm/mLMTangentStickInitialResidualNorm;
} else {
residual_tangent_lm_stick_ratio = 0.0;
}
if (lm_slip_dof_num > 0) {
residual_tangent_lm_slip_ratio = mLMTangentSlipCurrentResidualNorm/mLMTangentSlipInitialResidualNorm;
} else {
residual_tangent_lm_slip_ratio = 0.0;
}
KRATOS_ERROR_IF(mOptions.Is(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::ENSURE_CONTACT) && residual_normal_lm_ratio == 0.0) << "ERROR::CONTACT LOST::ARE YOU SURE YOU ARE SUPPOSED TO HAVE CONTACT?" << std::endl;
// We calculate the absolute norms
const TDataType residual_disp_abs = mDispCurrentResidualNorm/static_cast<TDataType>(disp_dof_num);
const TDataType residual_normal_lm_abs = mLMNormalCurrentResidualNorm/static_cast<TDataType>(lm_dof_num);
const TDataType residual_tangent_lm_stick_abs = lm_stick_dof_num > 0 ? mLMTangentStickCurrentResidualNorm/static_cast<TDataType>(lm_stick_dof_num) : 0.0;
const TDataType residual_tangent_lm_slip_abs = lm_slip_dof_num > 0 ? mLMTangentSlipCurrentResidualNorm/static_cast<TDataType>(lm_slip_dof_num) : 0.0;
const TDataType normal_tangent_stick_ratio = residual_tangent_lm_stick_abs/residual_normal_lm_abs;
const TDataType normal_tangent_slip_ratio = residual_tangent_lm_slip_abs/residual_normal_lm_abs;
// We print the results // TODO: Replace for the new log
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
std::cout.precision(4);
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP)) {
r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << residual_normal_lm_ratio << mLMNormalRatioTolerance << residual_normal_lm_abs << mLMNormalAbsTolerance << residual_tangent_lm_stick_ratio << mLMTangentRatioTolerance << residual_tangent_lm_stick_abs << mLMTangentAbsTolerance << residual_tangent_lm_slip_ratio << mLMTangentRatioTolerance << residual_tangent_lm_slip_abs << mLMTangentAbsTolerance;
} else {
r_table << residual_disp_ratio << mDispRatioTolerance << residual_disp_abs << mDispAbsTolerance << residual_normal_lm_ratio << mLMNormalRatioTolerance << residual_normal_lm_abs << mLMNormalAbsTolerance << residual_tangent_lm_slip_ratio << mLMTangentRatioTolerance << residual_tangent_lm_slip_abs << mLMTangentAbsTolerance;
}
} else {
std::cout.precision(4);
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PRINTING_OUTPUT)) {
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << BOLDFONT("RESIDUAL CONVERGENCE CHECK") << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific;
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << BOLDFONT("\tDISPLACEMENT: RATIO = ") << residual_disp_ratio << BOLDFONT(" EXP.RATIO = ") << mDispRatioTolerance << BOLDFONT(" ABS = ") << residual_disp_abs << BOLDFONT(" EXP.ABS = ") << mDispAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << BOLDFONT("\tNORMAL LAGRANGE MUL: RATIO = ") << residual_normal_lm_ratio << BOLDFONT(" EXP.RATIO = ") << mLMNormalRatioTolerance << BOLDFONT(" ABS = ") << residual_normal_lm_abs << BOLDFONT(" EXP.ABS = ") << mLMNormalAbsTolerance << std::endl;
KRATOS_INFO_IF("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP)) << BOLDFONT("\tSTICK LAGRANGE MUL: RATIO = ") << residual_tangent_lm_stick_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentRatioTolerance << BOLDFONT(" ABS = ") << residual_tangent_lm_stick_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << BOLDFONT("\tSLIP LAGRANGE MUL: RATIO = ") << residual_tangent_lm_slip_ratio << BOLDFONT(" EXP.RATIO = ") << mLMTangentRatioTolerance << BOLDFONT(" ABS = ") << residual_tangent_lm_slip_abs << BOLDFONT(" EXP.ABS = ") << mLMTangentAbsTolerance << std::endl;
} else {
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << "RESIDUAL CONVERGENCE CHECK" << "\tSTEP: " << r_process_info[STEP] << "\tNL ITERATION: " << r_process_info[NL_ITERATION_NUMBER] << std::endl << std::scientific;
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << "\tDISPLACEMENT: RATIO = " << residual_disp_ratio << " EXP.RATIO = " << mDispRatioTolerance << " ABS = " << residual_disp_abs << " EXP.ABS = " << mDispAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << "\tNORMAL LAGRANGE MUL: RATIO = " << residual_normal_lm_ratio << " EXP.RATIO = " << mLMNormalRatioTolerance << " ABS = " << residual_normal_lm_abs << " EXP.ABS = " << mLMNormalAbsTolerance << std::endl;
KRATOS_INFO_IF("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria", mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP)) << "\tSTICK LAGRANGE MUL: RATIO = " << residual_tangent_lm_stick_ratio << " EXP.RATIO = " << mLMTangentRatioTolerance << " ABS = " << residual_tangent_lm_stick_abs << " EXP.ABS = " << mLMTangentAbsTolerance << std::endl;
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << "\tSLIP LAGRANGE MUL: RATIO = " << residual_tangent_lm_slip_ratio << " EXP.RATIO = " << mLMTangentRatioTolerance << " ABS = " << residual_tangent_lm_slip_abs << " EXP.ABS = " << mLMTangentAbsTolerance << std::endl;
}
}
}
// NOTE: Here we don't include the tangent counter part
r_process_info[CONVERGENCE_RATIO] = (residual_disp_ratio > residual_normal_lm_ratio) ? residual_disp_ratio : residual_normal_lm_ratio;
r_process_info[RESIDUAL_NORM] = (residual_normal_lm_abs > mLMNormalAbsTolerance) ? residual_normal_lm_abs : mLMNormalAbsTolerance;
// We check if converged
const bool disp_converged = (residual_disp_ratio <= mDispRatioTolerance || residual_disp_abs <= mDispAbsTolerance);
const bool lm_converged = (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::ENSURE_CONTACT) && residual_normal_lm_ratio == 0.0) ? true : (residual_normal_lm_ratio <= mLMNormalRatioTolerance || residual_normal_lm_abs <= mLMNormalAbsTolerance) && (residual_tangent_lm_stick_ratio <= mLMTangentRatioTolerance || residual_tangent_lm_stick_abs <= mLMTangentAbsTolerance || normal_tangent_stick_ratio <= mNormalTangentRatio) && (residual_tangent_lm_slip_ratio <= mLMTangentRatioTolerance || residual_tangent_lm_slip_abs <= mLMTangentAbsTolerance || normal_tangent_slip_ratio <= mNormalTangentRatio);
if (disp_converged && lm_converged ) {
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PRINTING_OUTPUT))
r_table << BOLDFONT(FGRN(" Achieved"));
else
r_table << "Achieved";
} else {
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PRINTING_OUTPUT))
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << BOLDFONT("\tResidual") << " convergence is " << BOLDFONT(FGRN("achieved")) << std::endl;
else
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << "\tResidual convergence is achieved" << std::endl;
}
}
return true;
} else {
if (rModelPart.GetCommunicator().MyPID() == 0 && this->GetEchoLevel() > 0) {
if (r_process_info.Has(TABLE_UTILITY)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PRINTING_OUTPUT))
r_table << BOLDFONT(FRED(" Not achieved"));
else
r_table << "Not achieved";
} else {
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PRINTING_OUTPUT))
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << BOLDFONT("\tResidual") << " convergence is " << BOLDFONT(FRED(" not achieved")) << std::endl;
else
KRATOS_INFO("DisplacementLagrangeMultiplierResidualFrictionalContactCriteria") << "\tResidual convergence is not achieved" << std::endl;
}
}
return false;
}
} else // In this case all the displacements are imposed!
return true;
}
/**
* @brief This function initialize the convergence criteria
* @param rModelPart Reference to the ModelPart containing the contact problem. (unused)
*/
void Initialize( ModelPart& rModelPart) override
{
BaseType::mConvergenceCriteriaIsInitialized = true;
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
if (r_process_info.Has(TABLE_UTILITY) && mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::TABLE_IS_INITIALIZED)) {
TablePrinterPointerType p_table = r_process_info[TABLE_UTILITY];
auto& r_table = p_table->GetTable();
r_table.AddColumn("DP RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
r_table.AddColumn("N.LM RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
if (mOptions.IsNot(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::PURE_SLIP)) {
r_table.AddColumn("STI. RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
}
r_table.AddColumn("SLIP RATIO", 10);
r_table.AddColumn("EXP. RAT", 10);
r_table.AddColumn("ABS", 10);
r_table.AddColumn("EXP. ABS", 10);
r_table.AddColumn("CONVERGENCE", 15);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::TABLE_IS_INITIALIZED, true);
}
}
/**
* @brief This function initializes the solution step
* @param rModelPart Reference to the ModelPart containing the contact problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual)
*/
void InitializeSolutionStep(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_RESIDUAL_IS_SET, false);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_STICK_RESIDUAL_IS_SET, false);
mOptions.Set(DisplacementLagrangeMultiplierResidualFrictionalContactCriteria::INITIAL_SLIP_RESIDUAL_IS_SET, false);
}
/**
* @brief This function finalizes the non-linear iteration
* @param rModelPart Reference to the ModelPart containing the problem.
* @param rDofSet Reference to the container of the problem's degrees of freedom (stored by the BuilderAndSolver)
* @param rA System matrix (unused)
* @param rDx Vector of results (variations on nodal variables)
* @param rb RHS vector (residual + reactions)
*/
void FinalizeNonLinearIteration(
ModelPart& rModelPart,
DofsArrayType& rDofSet,
const TSystemMatrixType& rA,
const TSystemVectorType& rDx,
const TSystemVectorType& rb
) override
{
// Calling base criteria
BaseType::FinalizeNonLinearIteration(rModelPart, rDofSet, rA, rDx, rb);
// The current process info
ProcessInfo& r_process_info = rModelPart.GetProcessInfo();
r_process_info.SetValue(ACTIVE_SET_COMPUTED, false);
}
///@}
///@name Operations
///@{
///@}
///@name Acces
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Friends
///@{
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
Flags mOptions; /// Local flags
TDataType mDispRatioTolerance; /// The ratio threshold for the norm of the displacement residual
TDataType mDispAbsTolerance; /// The absolute value threshold for the norm of the displacement residual
TDataType mDispInitialResidualNorm; /// The reference norm of the displacement residual
TDataType mDispCurrentResidualNorm; /// The current norm of the displacement residual
TDataType mLMNormalRatioTolerance; /// The ratio threshold for the norm of the normal LM residual
TDataType mLMNormalAbsTolerance; /// The absolute value threshold for the norm of the normal LM residual
TDataType mLMNormalInitialResidualNorm; /// The reference norm of the normal LM residual
TDataType mLMNormalCurrentResidualNorm; /// The current norm of the normal LM residual
TDataType mLMTangentRatioTolerance; /// The ratio threshold for the norm of the tangent LM residual
TDataType mLMTangentAbsTolerance; /// The absolute value threshold for the norm of the tangent LM residual
TDataType mLMTangentStickInitialResidualNorm; /// The reference norm of the tangent LM residual (stick)
TDataType mLMTangentStickCurrentResidualNorm; /// The current norm of the tangent LM residual (stick)
TDataType mLMTangentSlipInitialResidualNorm; /// The reference norm of the tangent LM residual (slip)
TDataType mLMTangentSlipCurrentResidualNorm; /// The current norm of the tangent LM residual (slip)
std::size_t mStickCounter = 0; /// This is an auxiliar counter for stick dofs
std::size_t mSlipCounter = 0; /// This is an auxiliar counter for slip dofs
TDataType mNormalTangentRatio; /// The ratio to accept a non converged tangent component in case
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
///@name Private Inquiry
///@{
///@}
///@name Unaccessible methods
///@{
///@}
}; // Kratos DisplacementLagrangeMultiplierResidualFrictionalContactCriteria
///@name Local flags creation
///@{
/// Local Flags
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::ENSURE_CONTACT(Kratos::Flags::Create(0));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_ENSURE_CONTACT(Kratos::Flags::Create(0, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PRINTING_OUTPUT(Kratos::Flags::Create(1));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_PRINTING_OUTPUT(Kratos::Flags::Create(1, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::TABLE_IS_INITIALIZED(Kratos::Flags::Create(2));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_TABLE_IS_INITIALIZED(Kratos::Flags::Create(2, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::PURE_SLIP(Kratos::Flags::Create(3));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_PURE_SLIP(Kratos::Flags::Create(3, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(4));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_INITIAL_RESIDUAL_IS_SET(Kratos::Flags::Create(4, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::INITIAL_STICK_RESIDUAL_IS_SET(Kratos::Flags::Create(5));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_INITIAL_STICK_RESIDUAL_IS_SET(Kratos::Flags::Create(5, false));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::INITIAL_SLIP_RESIDUAL_IS_SET(Kratos::Flags::Create(6));
template<class TSparseSpace, class TDenseSpace>
const Kratos::Flags DisplacementLagrangeMultiplierResidualFrictionalContactCriteria<TSparseSpace, TDenseSpace>::NOT_INITIAL_SLIP_RESIDUAL_IS_SET(Kratos::Flags::Create(6, false));
}
#endif /* KRATOS_DISPLACEMENT_LAGRANGE_MULTIPLIER_RESIDUAL_FRICTIONAL_CONTACT_CRITERIA_H */
|
GB_unaryop__abs_fp64_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__abs_fp64_int8
// op(A') function: GB_tran__abs_fp64_int8
// C type: double
// A type: int8_t
// cast: double cij = (double) aij
// unaryop: cij = fabs (aij)
#define GB_ATYPE \
int8_t
#define GB_CTYPE \
double
// 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 = fabs (x) ;
// casting
#define GB_CASTING(z, aij) \
double z = (double) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_FP64 || GxB_NO_INT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_fp64_int8
(
double *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__abs_fp64_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
|
openmp_wrapper.h | /*!
* Copyright (c) 2017 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_OPENMP_WRAPPER_H_
#define LIGHTGBM_OPENMP_WRAPPER_H_
#ifdef _OPENMP
#include <LightGBM/utils/log.h>
#include <omp.h>
#include <exception>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <vector>
inline int OMP_NUM_THREADS() {
int ret = 1;
#pragma omp parallel
#pragma omp master
{ ret = omp_get_num_threads(); }
return ret;
}
class ThreadExceptionHelper {
public:
ThreadExceptionHelper() {
ex_ptr_ = nullptr;
}
~ThreadExceptionHelper() {
ReThrow();
}
void ReThrow() {
if (ex_ptr_ != nullptr) {
std::rethrow_exception(ex_ptr_);
}
}
void CaptureException() {
// only catch first exception.
if (ex_ptr_ != nullptr) { return; }
std::unique_lock<std::mutex> guard(lock_);
if (ex_ptr_ != nullptr) { return; }
ex_ptr_ = std::current_exception();
}
private:
std::exception_ptr ex_ptr_;
std::mutex lock_;
};
#define OMP_INIT_EX() ThreadExceptionHelper omp_except_helper
#define OMP_LOOP_EX_BEGIN() try {
#define OMP_LOOP_EX_END() \
} \
catch (std::exception & ex) { \
Log::Warning(ex.what()); \
omp_except_helper.CaptureException(); \
} \
catch (...) { \
omp_except_helper.CaptureException(); \
}
#define OMP_THROW_EX() omp_except_helper.ReThrow()
#else
#ifdef _MSC_VER
#pragma warning(disable : 4068) // disable unknown pragma warning
#endif
#ifdef __cplusplus
extern "C" {
#endif
/** Fall here if no OPENMP support, so just
simulate a single thread running.
All #pragma omp should be ignored by the compiler **/
inline void omp_set_num_threads(int) {}
inline int omp_get_num_threads() {return 1;}
inline int omp_get_thread_num() {return 0;}
inline int OMP_NUM_THREADS() { return 1; }
#ifdef __cplusplus
} // extern "C"
#endif
#define OMP_INIT_EX()
#define OMP_LOOP_EX_BEGIN()
#define OMP_LOOP_EX_END()
#define OMP_THROW_EX()
#endif
#endif /* LIGHTGBM_OPENMP_WRAPPER_H_ */
|
naive.c | #include "constants.h"
/* Lower bound on timings by a single memcpy
* gives ~1.19 seconds for 10 iterations, 1757 MB /0.11s ~= 1600 MB/s
[root@laptopjisk ~]# dmidecode -t 17
# dmidecode 3.1
Getting SMBIOS data from sysfs.
SMBIOS 3.0.0 present.
Handle 0x0039, DMI type 17, 40 bytes
Memory Device
Array Handle: 0x0038
Error Information Handle: Not Provided
Total Width: 64 bits
Data Width: 64 bits
Size: 8192 MB
Form Factor: Row Of Chips
Set: None
Locator: System Board Memory
Bank Locator: BANK 0
Type: LPDDR3
Type Detail: Synchronous Unbuffered (Unregistered)
Speed: 1867 MT/s
Manufacturer: Micron
Serial Number: 00000000
Asset Tag: 9876543210
Part Number: MT52L1G32D4PG-107
Rank: 2
Configured Clock Speed: 1867 MT/s
Minimum Voltage: 1.25 V
Maximum Voltage: 1.25 V
Configured Voltage: 1.2 V
*/
/**
* Deinterleave (transpose) an IQUV ring buffer page to the ordering needed for FITS files
* Note that this is probably a slow function, and is not meant to be run real-time
*
* data in: tab, channel/4, time/500 packets of time,channel,pn
* data out: tab, channel, pol, time
*
* Suggested use is:
* 1. realtime: ringbuffer -> [trigger] -> dada_dbdisk
* 2. offline: dada_dbdisk -> ringbuffer -> dadafits
*
* @param {const unsigned char *} page Ringbuffer page with interleaved data
* @param {int} ntabs Number of tabs
* @param {int} nchannels Number of channels
* @param {int} npackets Number of packets per sequence
*/
void deinterleave(unsigned char * restrict const page, unsigned char * restrict const transposed, const int ntabs, const int nchannels, const int npackets) {
// and find the matching address in the transposed buffer
const int ni = ntabs * nchannels / NCHANS;
const int nj = npackets * NSAMPS;
const int nk = NCHANS * NPOLS;
int i = 0;
#pragma omp parallel for
for (i = 0; i < ni; i++) {
int j;
for (j = 0; j < nj; j++) {
int k = 0;
for (k = 0; k < nk; k++) {
transposed[(i * nk + k) * nj + j] = page[(i * nj + j) * nk + k];
}
}
}
}
|
dft.c | // Copyright Naoki Shibata and contributors 2010 - 2020.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <signal.h>
#include <setjmp.h>
#include <math.h>
#include "sleef.h"
#include "misc.h"
#include "common.h"
#include "arraymap.h"
#include "dftcommon.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#if BASETYPEID == 1
typedef double real;
typedef Sleef_double2 sc_t;
#define BASETYPESTRING "double"
#define MAGIC 0x27182818
#define MAGIC2D 0x17320508
#define INIT SleefDFT_double_init1d
#define EXECUTE SleefDFT_double_execute
#define INIT2D SleefDFT_double_init2d
#define CTBL ctbl_double
#define REALSUB0 realSub0_double
#define REALSUB1 realSub1_double
#define GETINT getInt_double
#define GETPTR getPtr_double
#define DFTF dftf_double
#define DFTB dftb_double
#define TBUTF tbutf_double
#define TBUTB tbutb_double
#define BUTF butf_double
#define BUTB butb_double
#define SINCOSPI Sleef_sincospi_u05
#include "dispatchdp.h"
#elif BASETYPEID == 2
typedef float real;
typedef Sleef_float2 sc_t;
#define BASETYPESTRING "float"
#define MAGIC 0x31415926
#define MAGIC2D 0x22360679
#define INIT SleefDFT_float_init1d
#define EXECUTE SleefDFT_float_execute
#define INIT2D SleefDFT_float_init2d
#define CTBL ctbl_float
#define REALSUB0 realSub0_float
#define REALSUB1 realSub1_float
#define GETINT getInt_float
#define GETPTR getPtr_float
#define DFTF dftf_float
#define DFTB dftb_float
#define TBUTF tbutf_float
#define TBUTB tbutb_float
#define BUTF butf_float
#define BUTB butb_float
#define SINCOSPI Sleef_sincospif_u05
#include "dispatchsp.h"
#elif BASETYPEID == 3
typedef long double real;
typedef Sleef_longdouble2 sc_t;
#define BASETYPESTRING "long double"
#define MAGIC 0x14142135
#define MAGIC2D 0x26457513
#define INIT SleefDFT_longdouble_init1d
#define EXECUTE SleefDFT_longdouble_execute
#define INIT2D SleefDFT_longdouble_init2d
#define CTBL ctbl_longdouble
#define REALSUB0 realSub0_longdouble
#define REALSUB1 realSub1_longdouble
#define GETINT getInt_longdouble
#define GETPTR getPtr_longdouble
#define DFTF dftf_longdouble
#define DFTB dftb_longdouble
#define TBUTF tbutf_longdouble
#define TBUTB tbutb_longdouble
#define BUTF butf_longdouble
#define BUTB butb_longdouble
#define SINCOSPI Sleef_sincospil_u05
#include "dispatchld.h"
#elif BASETYPEID == 4
typedef Sleef_quad real;
typedef Sleef_quad2 sc_t;
#define BASETYPESTRING "Sleef_quad"
#define MAGIC 0x33166247
#define MAGIC2D 0x36055512
#define INIT SleefDFT_quad_init1d
#define EXECUTE SleefDFT_quad_execute
#define INIT2D SleefDFT_quad_init2d
#define CTBL ctbl_Sleef_quad
#define REALSUB0 realSub0_Sleef_quad
#define REALSUB1 realSub1_Sleef_quad
#define GETINT getInt_Sleef_quad
#define GETPTR getPtr_Sleef_quad
#define DFTF dftf_Sleef_quad
#define DFTB dftb_Sleef_quad
#define TBUTF tbutf_Sleef_quad
#define TBUTB tbutb_Sleef_quad
#define BUTF butf_Sleef_quad
#define BUTB butb_Sleef_quad
#define SINCOSPI Sleef_sincospiq_u05
#include "dispatchqp.h"
#else
#error No BASETYPEID specified
#endif
#define IMPORT_IS_EXPORT
#include "sleefdft.h"
//
#if BASETYPEID == 4
real CTBL[] = {
0.7071067811865475243818940365159164684883Q, -0.7071067811865475243818940365159164684883Q,
0.9238795325112867561014214079495587839119Q, -0.382683432365089771723257530688933059082Q,
0.382683432365089771723257530688933059082Q, -0.9238795325112867561014214079495587839119Q,
#if MAXBUTWIDTH >= 5
0.9807852804032304491190993878113602022495Q, -0.1950903220161282678433729148581576851029Q,
0.5555702330196022247573058028269343822103Q, -0.8314696123025452370808655033762590846891Q,
0.8314696123025452370808655033762590846891Q, -0.5555702330196022247573058028269343822103Q,
0.1950903220161282678433729148581576851029Q, -0.9807852804032304491190993878113602022495Q,
#endif
#if MAXBUTWIDTH >= 6
0.9951847266721968862310254699821143731242Q, -0.09801714032956060199569840382660679267701Q,
0.6343932841636454982026105398063009488396Q, -0.7730104533627369607965383602188325085081Q,
0.881921264348355029715105513066220055407Q, -0.4713967368259976485449225247492677226546Q,
0.2902846772544623676448431737195932100803Q, -0.9569403357322088649310892760624369657307Q,
0.9569403357322088649310892760624369657307Q, -0.2902846772544623676448431737195932100803Q,
0.4713967368259976485449225247492677226546Q, -0.881921264348355029715105513066220055407Q,
0.7730104533627369607965383602188325085081Q, -0.6343932841636454982026105398063009488396Q,
0.09801714032956060199569840382660679267701Q, -0.9951847266721968862310254699821143731242Q,
#endif
#if MAXBUTWIDTH >= 7
0.9987954562051723927007702841240899260811Q, -0.04906767432741801425355085940205324135377Q,
0.6715589548470184006194634573905233310143Q, -0.7409511253549590911932944126139233276263Q,
0.9039892931234433315823215138173907234886Q, -0.427555093430282094315230886905077056781Q,
0.336889853392220050702686798271834334173Q, -0.9415440651830207783906830087961026265475Q,
0.9700312531945439926159106824865574481009Q, -0.2429801799032638899447731489766866275204Q,
0.5141027441932217266072797923204262815489Q, -0.8577286100002720698929313536407192941624Q,
0.8032075314806449097991200569701675249235Q, -0.5956993044924333434615715265891822127742Q,
0.1467304744553617516588479505190711904561Q, -0.9891765099647809734561415551112872890371Q,
0.9891765099647809734561415551112872890371Q, -0.1467304744553617516588479505190711904561Q,
0.5956993044924333434615715265891822127742Q, -0.8032075314806449097991200569701675249235Q,
0.8577286100002720698929313536407192941624Q, -0.5141027441932217266072797923204262815489Q,
0.2429801799032638899447731489766866275204Q, -0.9700312531945439926159106824865574481009Q,
0.9415440651830207783906830087961026265475Q, -0.336889853392220050702686798271834334173Q,
0.427555093430282094315230886905077056781Q, -0.9039892931234433315823215138173907234886Q,
0.7409511253549590911932944126139233276263Q, -0.6715589548470184006194634573905233310143Q,
0.04906767432741801425355085940205324135377Q, -0.9987954562051723927007702841240899260811Q,
#endif
};
#else
real CTBL[] = {
0.7071067811865475243818940365159164684883L, -0.7071067811865475243818940365159164684883L,
0.9238795325112867561014214079495587839119L, -0.382683432365089771723257530688933059082L,
0.382683432365089771723257530688933059082L, -0.9238795325112867561014214079495587839119L,
#if MAXBUTWIDTH >= 5
0.9807852804032304491190993878113602022495L, -0.1950903220161282678433729148581576851029L,
0.5555702330196022247573058028269343822103L, -0.8314696123025452370808655033762590846891L,
0.8314696123025452370808655033762590846891L, -0.5555702330196022247573058028269343822103L,
0.1950903220161282678433729148581576851029L, -0.9807852804032304491190993878113602022495L,
#endif
#if MAXBUTWIDTH >= 6
0.9951847266721968862310254699821143731242L, -0.09801714032956060199569840382660679267701L,
0.6343932841636454982026105398063009488396L, -0.7730104533627369607965383602188325085081L,
0.881921264348355029715105513066220055407L, -0.4713967368259976485449225247492677226546L,
0.2902846772544623676448431737195932100803L, -0.9569403357322088649310892760624369657307L,
0.9569403357322088649310892760624369657307L, -0.2902846772544623676448431737195932100803L,
0.4713967368259976485449225247492677226546L, -0.881921264348355029715105513066220055407L,
0.7730104533627369607965383602188325085081L, -0.6343932841636454982026105398063009488396L,
0.09801714032956060199569840382660679267701L, -0.9951847266721968862310254699821143731242L,
#endif
#if MAXBUTWIDTH >= 7
0.9987954562051723927007702841240899260811L, -0.04906767432741801425355085940205324135377L,
0.6715589548470184006194634573905233310143L, -0.7409511253549590911932944126139233276263L,
0.9039892931234433315823215138173907234886L, -0.427555093430282094315230886905077056781L,
0.336889853392220050702686798271834334173L, -0.9415440651830207783906830087961026265475L,
0.9700312531945439926159106824865574481009L, -0.2429801799032638899447731489766866275204L,
0.5141027441932217266072797923204262815489L, -0.8577286100002720698929313536407192941624L,
0.8032075314806449097991200569701675249235L, -0.5956993044924333434615715265891822127742L,
0.1467304744553617516588479505190711904561L, -0.9891765099647809734561415551112872890371L,
0.9891765099647809734561415551112872890371L, -0.1467304744553617516588479505190711904561L,
0.5956993044924333434615715265891822127742L, -0.8032075314806449097991200569701675249235L,
0.8577286100002720698929313536407192941624L, -0.5141027441932217266072797923204262815489L,
0.2429801799032638899447731489766866275204L, -0.9700312531945439926159106824865574481009L,
0.9415440651830207783906830087961026265475L, -0.336889853392220050702686798271834334173L,
0.427555093430282094315230886905077056781L, -0.9039892931234433315823215138173907234886L,
0.7409511253549590911932944126139233276263L, -0.6715589548470184006194634573905233310143L,
0.04906767432741801425355085940205324135377L, -0.9987954562051723927007702841240899260811L,
#endif
};
#endif
#ifndef ENABLE_STREAM
#error ENABLE_STREAM not defined
#endif
static const int constK[] = { 0, 2, 6, 14, 38, 94, 230, 542, 1254 };
extern const char *configStr[];
extern int planFilePathSet;
// Utility functions
static jmp_buf sigjmp;
static void sighandler(int signum) { longjmp(sigjmp, 1); }
static int checkISAAvailability(int isa) {
signal(SIGILL, sighandler);
if (setjmp(sigjmp) == 0) {
int ret = GETINT[isa] != NULL && (*GETINT[isa])(BASETYPEID);
signal(SIGILL, SIG_DFL);
return ret;
}
signal(SIGILL, SIG_DFL);
return 0;
}
#ifdef _OPENMP
static int omp_thread_count() {
int n = 0;
#pragma omp parallel reduction(+:n)
n += 1;
return n;
}
#endif
static void startAllThreads(const int nth) {
#ifdef _OPENMP
volatile int8_t *state = calloc(nth, 1);
int th=0;
#pragma omp parallel for
for(th=0;th<nth;th++) {
state[th] = 1;
for(;;) {
int i;
for(i=0;i<nth;i++) if (state[i] == 0) break;
if (i == nth) break;
}
}
free((void *)state);
#endif
}
// Dispatcher
static void dispatch(SleefDFT *p, const int N, real *d, const real *s, const int level, const int config) {
const int K = constK[N], log2len = p->log2len;
if (level == N) {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
void (*func)(real *, const real *, const int) = DFTF[config][p->isa][N];
(*func)(d, s, log2len-N);
} else {
void (*func)(real *, const real *, const int) = DFTB[config][p->isa][N];
(*func)(d, s, log2len-N);
}
} else if (level == log2len) {
assert(p->vecwidth <= (1 << N));
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
void (*func)(real *, uint32_t *, const real *, const int, const real *, const int) = TBUTF[config][p->isa][N];
(*func)(d, p->perm[level], s, log2len-N, p->tbl[N][level], K);
} else {
void (*func)(real *, uint32_t *, const real *, const int, const real *, const int) = TBUTB[config][p->isa][N];
(*func)(d, p->perm[level], s, log2len-N, p->tbl[N][level], K);
}
} else {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
void (*func)(real *, uint32_t *, const int, const real *, const int, const real *, const int) = BUTF[config][p->isa][N];
(*func)(d, p->perm[level], log2len-level, s, log2len-N, p->tbl[N][level], K);
} else {
void (*func)(real *, uint32_t *, const int, const real *, const int, const real *, const int) = BUTB[config][p->isa][N];
(*func)(d, p->perm[level], log2len-level, s, log2len-N, p->tbl[N][level], K);
}
}
}
// Transposer
#if defined(__GNUC__) && __GNUC__ < 5
// This is another workaround of a bug in gcc-4
#define LOG2BS 3
#else
#define LOG2BS 4
#endif
#define BS (1 << LOG2BS)
#define TRANSPOSE_BLOCK(y2) do { \
for(int x2=y2+1;x2<BS;x2++) { \
element_t r = *(element_t *)&row[y2].r[x2*2+0]; \
*(element_t *)&row[y2].r[x2*2+0] = *(element_t *)&row[x2].r[y2*2+0]; \
*(element_t *)&row[x2].r[y2*2+0] = r; \
}} while(0)
static void transpose(real *RESTRICT ALIGNED(256) d, real *RESTRICT ALIGNED(256) s, const int log2n, const int log2m) {
if (log2n < LOG2BS || log2m < LOG2BS) {
for(int y=0;y<(1 << log2n);y++) {
for(int x=0;x<(1 << log2m);x++) {
real r0 = s[((y << log2m)+x)*2+0];
real r1 = s[((y << log2m)+x)*2+1];
d[((x << log2n)+y)*2+0] = r0;
d[((x << log2n)+y)*2+1] = r1;
}
}
} else {
#if defined(__GNUC__) && !defined(__clang__)
typedef struct { real __attribute__((vector_size(sizeof(real)*BS*2))) r; } row_t;
typedef struct { real __attribute__((vector_size(sizeof(real)*2))) r; } element_t;
#else
typedef struct { real r[BS*2]; } row_t;
typedef struct { real r0, r1; } element_t;
#endif
for(int y=0;y<(1 << log2n);y+=BS) {
for(int x=0;x<(1 << log2m);x+=BS) {
row_t row[BS];
for(int y2=0;y2<BS;y2++) {
row[y2] = *(row_t *)&s[(((y+y2) << log2m)+x)*2];
}
#if LOG2BS == 4
TRANSPOSE_BLOCK( 0); TRANSPOSE_BLOCK( 1);
TRANSPOSE_BLOCK( 2); TRANSPOSE_BLOCK( 3);
TRANSPOSE_BLOCK( 4); TRANSPOSE_BLOCK( 5);
TRANSPOSE_BLOCK( 6); TRANSPOSE_BLOCK( 7);
TRANSPOSE_BLOCK( 8); TRANSPOSE_BLOCK( 9);
TRANSPOSE_BLOCK(10); TRANSPOSE_BLOCK(11);
TRANSPOSE_BLOCK(12); TRANSPOSE_BLOCK(13);
TRANSPOSE_BLOCK(14); TRANSPOSE_BLOCK(15);
#else
for(int y2=0;y2<BS;y2++) {
for(int x2=y2+1;x2<BS;x2++) {
element_t r = *(element_t *)&row[y2].r[x2*2+0];
*(element_t *)&row[y2].r[x2*2+0] = *(element_t *)&row[x2].r[y2*2+0];
*(element_t *)&row[x2].r[y2*2+0] = r;
}
}
#endif
for(int y2=0;y2<BS;y2++) {
*(row_t *)&d[(((x+y2) << log2n)+y)*2] = row[y2];
}
}
}
}
}
#ifdef _OPENMP
static void transposeMT(real *RESTRICT ALIGNED(256) d, real *RESTRICT ALIGNED(256) s, int log2n, int log2m) {
if (log2n < LOG2BS || log2m < LOG2BS) {
for(int y=0;y<(1 << log2n);y++) {
for(int x=0;x<(1 << log2m);x++) {
real r0 = s[((y << log2m)+x)*2+0];
real r1 = s[((y << log2m)+x)*2+1];
d[((x << log2n)+y)*2+0] = r0;
d[((x << log2n)+y)*2+1] = r1;
}
}
} else {
#if defined(__GNUC__) && !defined(__clang__)
typedef struct { real __attribute__((vector_size(sizeof(real)*BS*2))) r; } row_t;
typedef struct { real __attribute__((vector_size(sizeof(real)*2))) r; } element_t;
#else
typedef struct { real r[BS*2]; } row_t;
typedef struct { real r0, r1; } element_t;
#endif
int y=0;
#pragma omp parallel for
for(y=0;y<(1 << log2n);y+=BS) {
for(int x=0;x<(1 << log2m);x+=BS) {
row_t row[BS];
for(int y2=0;y2<BS;y2++) {
row[y2] = *(row_t *)&s[(((y+y2) << log2m)+x)*2];
}
#if LOG2BS == 4
TRANSPOSE_BLOCK( 0); TRANSPOSE_BLOCK( 1);
TRANSPOSE_BLOCK( 2); TRANSPOSE_BLOCK( 3);
TRANSPOSE_BLOCK( 4); TRANSPOSE_BLOCK( 5);
TRANSPOSE_BLOCK( 6); TRANSPOSE_BLOCK( 7);
TRANSPOSE_BLOCK( 8); TRANSPOSE_BLOCK( 9);
TRANSPOSE_BLOCK(10); TRANSPOSE_BLOCK(11);
TRANSPOSE_BLOCK(12); TRANSPOSE_BLOCK(13);
TRANSPOSE_BLOCK(14); TRANSPOSE_BLOCK(15);
#else
for(int y2=0;y2<BS;y2++) {
for(int x2=y2+1;x2<BS;x2++) {
element_t r = *(element_t *)&row[y2].r[x2*2+0];
*(element_t *)&row[y2].r[x2*2+0] = *(element_t *)&row[x2].r[y2*2+0];
*(element_t *)&row[x2].r[y2*2+0] = r;
}
}
#endif
for(int y2=0;y2<BS;y2++) {
*(row_t *)&d[(((x+y2) << log2n)+y)*2] = row[y2];
}
}
}
}
}
#endif // #ifdef _OPENMP
// Table generator
static sc_t r2coefsc(int i, int log2len, int level) {
return SINCOSPI((i & ((-1 << (log2len - level)) & ~(-1 << log2len))) * ((real)1.0/(1 << (log2len-1))));
}
static sc_t srcoefsc(int i, int log2len, int level) {
return SINCOSPI(((3*(i & (-1 << (log2len - level)))) & ~(-1 << log2len)) * ((real)1.0/(1 << (log2len-1))));
}
static int makeTableRecurse(real *x, int *p, const int log2len, const int levelorg, const int levelinc, const int sign, const int top, const int bot, const int N, int cnt) {
if (levelinc >= N-1) return cnt;
const int level = levelorg - levelinc;
if (bot - top > 4) {
const int bl = 1 << (N - levelinc);
const int w = bl/4;
for(int j=0;j<(bot-top)/bl;j++) {
for(int i=0;i<w;i++) {
int a = sign*(p[(levelinc << N) + top+bl*j+i] & (-1 << (log2len - level)));
sc_t sc;
sc = r2coefsc(a, log2len, level);
x[cnt++] = -sc.x; x[cnt++] = -sc.y;
sc = srcoefsc(a, log2len, level);
x[cnt++] = -sc.x; x[cnt++] = -sc.y;
}
cnt = makeTableRecurse(x, p, log2len, levelorg, levelinc+1, sign, top+bl*j , top+bl*j + bl/2, N, cnt);
cnt = makeTableRecurse(x, p, log2len, levelorg, levelinc+2, sign, top+bl*j + bl/2, top+bl*j + bl , N, cnt);
}
} else if (bot - top == 4) {
int a = sign*(p[(levelinc << N) + top] & (-1 << (log2len - level)));
sc_t sc;
sc = r2coefsc(a, log2len, level);
x[cnt++] = -sc.x; x[cnt++] = -sc.y;
sc = srcoefsc(a, log2len, level);
x[cnt++] = -sc.x; x[cnt++] = -sc.y;
}
return cnt;
}
static uint32_t perm(int nbits, uint32_t k, int s, int d) {
s = MIN(MAX(s, 0), nbits);
d = MIN(MAX(d, 0), nbits);
uint32_t r;
r = (((k & 0xaaaaaaaa) >> 1) | ((k & 0x55555555) << 1));
r = (((r & 0xcccccccc) >> 2) | ((r & 0x33333333) << 2));
r = (((r & 0xf0f0f0f0) >> 4) | ((r & 0x0f0f0f0f) << 4));
r = (((r & 0xff00ff00) >> 8) | ((r & 0x00ff00ff) << 8));
r = ((r >> 16) | (r << 16)) >> (32-nbits);
return (((r << s) | (k & ~(-1 << s))) & ~(-1 << d)) |
((((k >> s) | (r & (-1 << (nbits-s)))) << d) & ~(-1 << nbits));
}
static real **makeTable(int sign, int vecwidth, int log2len, const int N, const int K) {
if (log2len < N) return NULL;
int *p = (int *)malloc(sizeof(int)*((N+1)<<N));
real **tbl = (real **)calloc(sizeof(real *), (log2len+1));
for(int level=N;level<=log2len;level++) {
if (level == log2len && (1 << (log2len-N)) < vecwidth) { tbl[level] = NULL; continue; }
int tblOffset = 0;
tbl[level] = (real *)Sleef_malloc(sizeof(real) * (K << (level-N)));
for(int i0=0;i0 < (1 << (log2len-N));i0+=(1 << (log2len - level))) {
for(int j=0;j<N+1;j++) {
for(int i=0;i<(1 << N);i++) {
p[(j << N) + i] = perm(log2len, i0 + (i << (log2len-N)), log2len-level, log2len-(level-j));
}
}
int a = -sign*(p[((N-1) << N) + 0] & (-1 << (log2len - level)));
sc_t sc = r2coefsc(a, log2len, level-N+1);
tbl[level][tblOffset++] = sc.y; tbl[level][tblOffset++] = sc.x;
tblOffset = makeTableRecurse(tbl[level], p, log2len, level, 0, sign, 0, 1 << N, N, tblOffset);
}
if (level == log2len) {
real *atbl = (real *)Sleef_malloc(sizeof(real)*(K << (log2len-N))*2);
tblOffset = 0;
while(tblOffset < (K << (log2len-N))) {
for(int k=0;k < K;k++) {
for(int v = 0;v < vecwidth;v++) {
assert((tblOffset + k * vecwidth + v)*2 + 1 < (K << (log2len-N))*2);
atbl[(tblOffset + k * vecwidth + v)*2 + 0] = tbl[log2len][tblOffset + v * K + k];
atbl[(tblOffset + k * vecwidth + v)*2 + 1] = tbl[log2len][tblOffset + v * K + k];
}
}
tblOffset += K * vecwidth;
}
Sleef_free(tbl[log2len]);
tbl[log2len] = atbl;
}
}
free(p);
return tbl;
}
// Random planner (for debugging)
static int searchForRandomPathRecurse(SleefDFT *p, int level, int *path, int *pathConfig, uint64_t tm, int nTrial) {
if (level == 0) {
p->bestTime = tm;
for(uint32_t j = 0;j < p->log2len+1;j++) {
p->bestPathConfig[j] = pathConfig[j];
p->bestPath[j] = path[j];
}
return nTrial;
}
if (level < 1) return nTrial-1;
for(int i=0;i<10;i++) {
int N;
do {
N = 1 + rand() % MAXBUTWIDTH;
} while(p->tm[0][level*(MAXBUTWIDTH+1)+N] >= 1ULL << 60);
if (p->vecwidth > (1 << N) || N == p->log2len) continue;
path[level] = N;
for(;;) {
pathConfig[level] = rand() % CONFIGMAX;
#if ENABLE_STREAM == 0
pathConfig[level] &= ~1;
#endif
if ((p->mode2 & SLEEF_MODE2_MT1D) == 0 && (pathConfig[level] & CONFIG_MT) != 0) continue;
break;
}
for(int j = level-1;j >= 0;j--) path[j] = 0;
nTrial = searchForRandomPathRecurse(p, level - N, path, pathConfig, 0, nTrial);
if (nTrial <= 0) break;
if (p->bestTime < 1ULL << 60) break;
}
return nTrial - 1;
}
// Planner
#define NSHORTESTPATHS 15
#define MAXPATHLEN (MAXLOG2LEN+1)
#define POSMAX (CONFIGMAX * MAXLOG2LEN * (MAXBUTWIDTH+1))
static int cln2pos(int config, int level, int N) { return (config * MAXLOG2LEN + level) * MAXBUTWIDTH + N; }
static int pos2config(int pos) { return pos == -1 ? -1 : ((pos - 1) / (MAXBUTWIDTH * MAXLOG2LEN)); }
static int pos2level(int pos) { return pos == -1 ? -1 : (((pos - 1) / MAXBUTWIDTH) % MAXLOG2LEN); }
static int pos2N(int pos) { return pos == -1 ? -1 : ((pos - 1) % MAXBUTWIDTH + 1); }
typedef struct {
SleefDFT *p;
int countu[POSMAX];
int path[NSHORTESTPATHS][MAXPATHLEN];
int pathLen[NSHORTESTPATHS];
uint64_t cost[NSHORTESTPATHS];
int nPaths;
int *heap;
int *heapLen;
uint64_t *heapCost;
int heapSize, nPathsInHeap;
} ks_t;
static ks_t *ksInit(SleefDFT *p) {
ks_t *q = calloc(1, sizeof(ks_t));
q->p = p;
q->heapSize = 10;
q->heap = calloc(q->heapSize, sizeof(int)*MAXPATHLEN);
q->heapCost = calloc(q->heapSize, sizeof(uint64_t));
q->heapLen = calloc(q->heapSize, sizeof(int));
return q;
}
static void ksDispose(ks_t *q) {
free(q->heapCost);
free(q->heapLen);
free(q->heap);
free(q);
}
// returns the number of paths in the heap
static int ksSize(ks_t *q) { return q->nPathsInHeap; }
// adds a path to the heap
static void ksAddPath(ks_t *q, int *path, int pathLen, uint64_t cost) {
assert(pathLen <= MAXPATHLEN);
if (q->nPathsInHeap == q->heapSize) {
q->heapSize *= 2;
q->heap = realloc(q->heap, q->heapSize * sizeof(int)*MAXPATHLEN);
q->heapCost = realloc(q->heapCost, q->heapSize * sizeof(uint64_t));
q->heapLen = realloc(q->heapLen, q->heapSize * sizeof(int));
}
for(int i=0;i<pathLen;i++) q->heap[q->nPathsInHeap * MAXPATHLEN + i] = path[i];
q->heapLen[q->nPathsInHeap] = pathLen;
q->heapCost[q->nPathsInHeap] = cost;
q->nPathsInHeap++;
}
// returns the cost of n-th paths in the heap
static uint64_t ksCost(ks_t *q, int n) {
assert(0 <= n && n < q->nPathsInHeap);
return q->heapCost[n];
}
// copies the n-th paths in the heap to path, returns its length
static int ksGetPath(ks_t *q, int *path, int n) {
assert(0 <= n && n < q->nPathsInHeap);
int len = q->heapLen[n];
for(int i=0;i<len;i++) path[i] = q->heap[n * MAXPATHLEN + i];
return len;
}
// removes the n-th paths in the heap
static void ksRemove(ks_t *q, int n) {
assert(0 <= n && n < q->nPathsInHeap);
for(int i=n;i<q->nPathsInHeap-1;i++) {
int len = q->heapLen[i+1];
assert(len < MAXPATHLEN);
for(int j=0;j<len;j++) q->heap[i * MAXPATHLEN + j] = q->heap[(i+1) * MAXPATHLEN + j];
q->heapLen[i] = q->heapLen[i+1];
q->heapCost[i] = q->heapCost[i+1];
}
q->nPathsInHeap--;
}
// returns the countu value at pos
static int ksCountu(ks_t *q, int pos) {
assert(0 <= pos && pos < POSMAX);
return q->countu[pos];
}
// set the countu value at pos to n
static void ksSetCountu(ks_t *q, int pos, int n) {
assert(0 <= pos && pos < POSMAX);
q->countu[pos] = n;
}
// adds a path as one of the best k paths, returns the number best paths
static int ksAddBestPath(ks_t *q, int *path, int pathLen, uint64_t cost) {
assert(pathLen <= MAXPATHLEN);
assert(q->nPaths < NSHORTESTPATHS);
for(int i=0;i<pathLen;i++) q->path[q->nPaths][i] = path[i];
q->pathLen[q->nPaths] = pathLen;
q->cost[q->nPaths] = cost;
q->nPaths++;
return q->nPaths;
}
// returns if pos is a destination
static int ksIsDest(ks_t *q, int pos) { return pos2level(pos) == 0; }
// returns n-th adjacent nodes at pos.
static int ksAdjacent(ks_t *q, int pos, int n) {
if (pos != -1 && pos2level(pos) == 0) return -1;
int NMAX = MIN(MIN(q->p->log2len, MAXBUTWIDTH+1), q->p->log2len - q->p->log2vecwidth + 1);
if (pos == -1) {
int N = n / 2 + MAX(q->p->log2vecwidth, 1);
if (N >= NMAX) return -1;
return cln2pos((n & 1) * CONFIG_MT, q->p->log2len, N);
}
int config = (pos2config(pos) & CONFIG_MT);
int N = n + 1;
int level = pos2level(pos) - pos2N(pos);
if (level < 0 || N >= NMAX) return -1;
if (level == 0) return n == 0 ? cln2pos(0, 0, 0) : -1;
return cln2pos(config, level, N);
}
static uint64_t ksAdjacentCost(ks_t *q, int pos, int n) {
int nxpos = ksAdjacent(q, pos, n);
if (nxpos == -1) return 0;
int config = pos2config(nxpos), level = pos2level(nxpos), N = pos2N(nxpos);
uint64_t ret0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t ret1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
return MIN(ret0, ret1);
}
static void searchForBestPath(SleefDFT *p) {
ks_t *q = ksInit(p);
for(int i=0;;i++) {
int v = ksAdjacent(q, -1, i);
if (v == -1) break;
uint64_t c = ksAdjacentCost(q, -1, i);
int path[1] = { v };
ksAddPath(q, path, 1, c);
}
while(ksSize(q) != 0) {
uint64_t bestCost = 1ULL << 60;
int bestPathNum = -1;
for(int i=0;i<ksSize(q);i++) {
if (ksCost(q, i) < bestCost) {
bestCost = ksCost(q, i);
bestPathNum = i;
}
}
if (bestPathNum == -1) break;
int path[MAXPATHLEN];
int pathLen = ksGetPath(q, path, bestPathNum);
uint64_t cost = ksCost(q, bestPathNum);
ksRemove(q, bestPathNum);
int lastPos = path[pathLen-1];
if (ksCountu(q, lastPos) >= NSHORTESTPATHS) continue;
ksSetCountu(q, lastPos, ksCountu(q, lastPos)+1);
if (ksIsDest(q, lastPos)) {
if (ksAddBestPath(q, path, pathLen, cost) >= NSHORTESTPATHS) break;
continue;
}
for(int i=0;;i++) {
int v = ksAdjacent(q, lastPos, i);
if (v == -1) break;
assert(0 <= pos2N(v) && pos2N(v) <= q->p->log2len);
uint64_t c = ksAdjacentCost(q, lastPos, i);
path[pathLen] = v;
ksAddPath(q, path, pathLen+1, cost + c);
}
}
for(int j = p->log2len;j >= 0;j--) p->bestPath[j] = 0;
if (((p->mode & SLEEF_MODE_MEASURE) != 0 || (planFilePathSet && (p->mode & SLEEF_MODE_MEASUREBITS) == 0))) {
uint64_t besttm = 1ULL << 62;
int bestPath = -1;
const int niter = 1 + 5000000 / ((1 << p->log2len) + 1);
real *s2 = NULL, *d2 = NULL;
const real *s = p->in == NULL ? (s2 = (real *)memset(Sleef_malloc((2 << p->log2len) * sizeof(real)), 0, sizeof(real) * (2 << p->log2len))) : p->in;
real *d = p->out == NULL ? (d2 = (real *)memset(Sleef_malloc((2 << p->log2len) * sizeof(real)), 0, sizeof(real) * (2 << p->log2len))) : p->out;
#ifdef _OPENMP
const int tn = omp_get_thread_num();
#else
const int tn = 0;
#endif
real *t[] = { p->x1[tn], p->x0[tn], d };
for(int mt=0;mt<2;mt++) {
for(int i=q->nPaths-1;i>=0;i--) {
if (((pos2config(q->path[i][0]) & CONFIG_MT) != 0) != mt) continue;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) {
for(int j=0;j<q->pathLen[i];j++) {
int N = pos2N(q->path[i][j]);
int level = pos2level(q->path[i][j]);
int config = pos2config(q->path[i][j]) & ~1;
uint64_t t0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t t1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
config = t0 < t1 ? config : (config | 1);
if (N != 0) printf("%d(%s) ", N, configStr[config]);
}
}
if (mt) startAllThreads(p->nThread);
uint64_t tm0 = Sleef_currentTimeMicros();
for(int k=0;k<niter;k++) {
int nb = 0;
const real *lb = s;
if ((p->pathLen & 1) == 1) nb = -1;
for(int level = p->log2len, j=0;level >= 1;j++) {
assert(pos2level(q->path[i][j]) == level);
int N = pos2N(q->path[i][j]);
int config = pos2config(q->path[i][j]) & ~1;
uint64_t t0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t t1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
config = t0 < t1 ? config : (config | 1);
dispatch(p, N, t[nb+1], lb, level, config);
level -= N;
lb = t[nb+1];
nb = (nb + 1) & 1;
}
}
uint64_t tm1 = Sleef_currentTimeMicros();
for(int k=0;k<niter;k++) {
int nb = 0;
const real *lb = s;
if ((p->pathLen & 1) == 1) nb = -1;
for(int level = p->log2len, j=0;level >= 1;j++) {
assert(pos2level(q->path[i][j]) == level);
int N = pos2N(q->path[i][j]);
int config = pos2config(q->path[i][j]) & ~1;
uint64_t t0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t t1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
config = t0 < t1 ? config : (config | 1);
dispatch(p, N, t[nb+1], lb, level, config);
level -= N;
lb = t[nb+1];
nb = (nb + 1) & 1;
}
}
uint64_t tm2 = Sleef_currentTimeMicros();
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf(" : %lld %lld\n", (long long int)(tm1 - tm0), (long long int)(tm2 - tm1));
if ((tm1 - tm0) < besttm) {
bestPath = i;
besttm = tm1 - tm0;
}
if ((tm2 - tm1) < besttm) {
bestPath = i;
besttm = tm2 - tm1;
}
}
}
for(int level = p->log2len, j=0;level >= 1;j++) {
assert(pos2level(q->path[bestPath][j]) == level);
int N = pos2N(q->path[bestPath][j]);
int config = pos2config(q->path[bestPath][j]) & ~1;
uint64_t t0 = q->p->tm[config | 0][level*(MAXBUTWIDTH+1) + N];
uint64_t t1 = q->p->tm[config | 1][level*(MAXBUTWIDTH+1) + N];
config = t0 < t1 ? config : (config | 1);
p->bestPath[level] = N;
p->bestPathConfig[level] = config;
level -= N;
}
if (d2 != NULL) Sleef_free(d2);
if (s2 != NULL) Sleef_free(s2);
} else {
for(int level = p->log2len, j=0;level >= 1;j++) {
int bestPath = 0;
assert(pos2level(q->path[bestPath][j]) == level);
int N = pos2N(q->path[bestPath][j]);
int config = pos2config(q->path[bestPath][j]);
p->bestPath[level] = N;
p->bestPathConfig[level] = config;
level -= N;
}
}
ksDispose(q);
}
//
static uint64_t estimate(int log2len, int level, int N, int config) {
uint64_t ret = N * 1000 + ABS(N-3) * 1000;
if (log2len >= 14 && (config & CONFIG_MT) != 0) ret /= 2;
return ret;
}
static void measureBut(SleefDFT *p) {
if (p->x0 == NULL) return;
//
#ifdef _OPENMP
const int tn = omp_get_thread_num();
#else
const int tn = 0;
#endif
real *s = (real *)memset(p->x0[tn], 0, sizeof(real) * (2 << p->log2len));
real *d = (real *)memset(p->x1[tn], 0, sizeof(real) * (2 << p->log2len));
const int niter = 1 + 100000 / ((1 << p->log2len) + 1);
#define MEASURE_REPEAT 4
for(int rep=1;rep<=MEASURE_REPEAT;rep++) {
for(int config=0;config<CONFIGMAX;config++) {
#if ENABLE_STREAM == 0
if ((config & 1) != 0) continue;
#endif
if ((p->mode2 & SLEEF_MODE2_MT1D) == 0 && (config & CONFIG_MT) != 0) continue;
for(uint32_t level = p->log2len;level >= 1;level--) {
for(uint32_t N=1;N<=MAXBUTWIDTH;N++) {
if (level < N || p->log2len <= N) continue;
if (level == N) {
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
uint64_t tm = Sleef_currentTimeMicros();
for(int i=0;i<niter*2;i++) {
dispatch(p, N, d, s, level, config);
}
tm = Sleef_currentTimeMicros() - tm + 1;
p->tm[config][level*(MAXBUTWIDTH+1)+N] = MIN(p->tm[config][level*(MAXBUTWIDTH+1)+N], tm);
} else if (level == p->log2len) {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > (1 << N)) continue;
if ((config & CONFIG_MT) != 0) {
int i1=0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(i1=0;i1 < (1 << (p->log2len-N-p->log2vecwidth));i1++) {
int i0 = i1 << p->log2vecwidth;
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
} else {
for(int i0=0, i1=0;i0 < (1 << (p->log2len-N));i0+=p->vecwidth, i1++) {
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
}
uint64_t tm = Sleef_currentTimeMicros();
for(int i=0;i<niter;i++) {
dispatch(p, N, d, s, level, config);
dispatch(p, N, s, d, level, config);
}
tm = Sleef_currentTimeMicros() - tm + 1;
p->tm[config][level*(MAXBUTWIDTH+1)+N] = MIN(p->tm[config][level*(MAXBUTWIDTH+1)+N], tm);
} else {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > 2 && p->log2len <= N+2) continue;
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
if ((config & CONFIG_MT) != 0) {
int i1=0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for(i1=0;i1 < (1 << (p->log2len-N-p->log2vecwidth));i1++) {
int i0 = i1 << p->log2vecwidth;
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
} else {
for(int i0=0, i1=0;i0 < (1 << (p->log2len-N));i0+=p->vecwidth, i1++) {
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
}
uint64_t tm = Sleef_currentTimeMicros();
for(int i=0;i<niter;i++) {
dispatch(p, N, d, s, level, config);
dispatch(p, N, s, d, level, config);
}
tm = Sleef_currentTimeMicros() - tm + 1;
p->tm[config][level*(MAXBUTWIDTH+1)+N] = MIN(p->tm[config][level*(MAXBUTWIDTH+1)+N], tm);
}
}
}
}
}
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) {
for(uint32_t level = p->log2len;level >= 1;level--) {
for(uint32_t N=1;N<=MAXBUTWIDTH;N++) {
if (level < N || p->log2len <= N) continue;
if (level == N) {
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
printf("bot %d, %d, %d, ", p->log2len, level, N);
for(int config=0;config<CONFIGMAX;config++) {
if (p->tm[config][level*(MAXBUTWIDTH+1)+N] == 1ULL << 60) {
printf("N/A, ");
} else {
printf("%lld, ", (long long int)p->tm[config][level*(MAXBUTWIDTH+1)+N]);
}
}
printf("\n");
} else if (level == p->log2len) {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > (1 << N)) continue;
printf("top %d, %d, %d, ", p->log2len, level, N);
for(int config=0;config<CONFIGMAX;config++) {
if (p->tm[config][level*(MAXBUTWIDTH+1)+N] == 1ULL << 60) {
printf("N/A, ");
} else {
printf("%lld, ", (long long int)p->tm[config][level*(MAXBUTWIDTH+1)+N]);
}
}
printf("\n");
} else {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > 2 && p->log2len <= N+2) continue;
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
printf("mid %d, %d, %d, ", p->log2len, level, N);
for(int config=0;config<CONFIGMAX;config++) {
if (p->tm[config][level*(MAXBUTWIDTH+1)+N] == 1ULL << 60) {
printf("N/A, ");
} else {
printf("%lld, ", (long long int)p->tm[config][level*(MAXBUTWIDTH+1)+N]);
}
}
printf("\n");
}
}
}
}
}
static void estimateBut(SleefDFT *p) {
for(uint32_t level = p->log2len;level >= 1;level--) {
for(uint32_t N=1;N<=MAXBUTWIDTH;N++) {
if (level < N || p->log2len <= N) continue;
if (level == N) {
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
for(int config=0;config<CONFIGMAX;config++) {
#if ENABLE_STREAM == 0
if ((config & 1) != 0) continue;
#endif
p->tm[config][level*(MAXBUTWIDTH+1)+N] = estimate(p->log2len, level, N, config);
}
} else if (level == p->log2len) {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > (1 << N)) continue;
for(int config=0;config<CONFIGMAX;config++) {
#if ENABLE_STREAM == 0
if ((config & 1) != 0) continue;
#endif
p->tm[config][level*(MAXBUTWIDTH+1)+N] = estimate(p->log2len, level, N, config);
}
} else {
if (p->tbl[N] == NULL || p->tbl[N][level] == NULL) continue;
if (p->vecwidth > 2 && p->log2len <= N+2) continue;
if ((int)p->log2len - (int)level < p->log2vecwidth) continue;
for(int config=0;config<CONFIGMAX;config++) {
#if ENABLE_STREAM == 0
if ((config & 1) != 0) continue;
#endif
p->tm[config][level*(MAXBUTWIDTH+1)+N] = estimate(p->log2len, level, N, config);
}
}
}
}
}
static int measure(SleefDFT *p, int randomize) {
if (p->log2len == 1) {
p->bestTime = 1ULL << 60;
p->pathLen = 1;
p->bestPath[1] = 1;
return 1;
}
if (PlanManager_loadMeasurementResultsP(p, (p->mode & SLEEF_MODE_NO_MT) != 0 ? 1 : 0)) {
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) {
printf("Path(loaded) : ");
for(int j = p->log2len;j >= 0;j--) if (p->bestPath[j] != 0) printf("%d(%s) ", p->bestPath[j], configStr[p->bestPathConfig[j]]);
printf("\n");
}
return 1;
}
int toBeSaved = 0;
for(uint32_t level = p->log2len;level >= 1;level--) {
for(uint32_t N=1;N<=MAXBUTWIDTH;N++) {
for(int config=0;config<CONFIGMAX;config++) {
p->tm[config][level*(MAXBUTWIDTH+1)+N] = 1ULL << 60;
}
}
}
if (((p->mode & SLEEF_MODE_MEASURE) != 0 || (planFilePathSet && (p->mode & SLEEF_MODE_MEASUREBITS) == 0)) && !randomize) {
measureBut(p);
toBeSaved = 1;
} else {
estimateBut(p);
}
int executable = 0;
for(int i=1;i<=MAXBUTWIDTH && !executable;i++) {
if (p->tm[0][p->log2len*(MAXBUTWIDTH+1)+i] < (1ULL << 60)) executable = 1;
}
if (!executable) return 0;
p->bestTime = 1ULL << 60;
p->bestPath[p->log2len] = 0;
if (!randomize) {
searchForBestPath(p);
} else {
int path[MAXLOG2LEN+1];
int pathConfig[MAXLOG2LEN+1];
for(int j = p->log2len;j >= 0;j--) path[j] = pathConfig[j] = 0;
int nTrial = 100000;
do {
nTrial = searchForRandomPathRecurse(p, p->log2len, path, pathConfig, 0, nTrial);
} while(p->bestTime == 1ULL << 60 && nTrial >= 0);
}
if (p->bestPath[p->log2len] == 0) return 0;
p->pathLen = 0;
for(int j = p->log2len;j >= 0;j--) if (p->bestPath[j] != 0) p->pathLen++;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) {
printf("Path");
if (randomize) printf("(random) :");
else if (toBeSaved) printf("(measured) :");
else printf("(estimated) :");
for(int j = p->log2len;j >= 0;j--) if (p->bestPath[j] != 0) printf("%d(%s) ", p->bestPath[j], configStr[p->bestPathConfig[j]]);
printf("\n");
}
if (toBeSaved) {
PlanManager_saveMeasurementResultsP(p, (p->mode & SLEEF_MODE_NO_MT) != 0 ? 1 : 0);
}
return 1;
}
static void measureTranspose(SleefDFT *p) {
if (PlanManager_loadMeasurementResultsT(p)) {
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose NoMT(loaded): %lld\n", (long long int)p->tmNoMT);
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose MT(loaded): %lld\n", (long long int)p->tmMT);
return;
}
if ((p->mode & SLEEF_MODE_MEASURE) == 0 && (!planFilePathSet || (p->mode & SLEEF_MODE_MEASUREBITS) != 0)) {
if (p->log2hlen + p->log2vlen >= 14) {
p->tmNoMT = 20;
p->tmMT = 10;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose : selected MT(estimated)\n");
} else {
p->tmNoMT = 10;
p->tmMT = 20;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose : selected NoMT(estimated)\n");
}
return;
}
real *tBuf2 = (real *)Sleef_malloc(sizeof(real)*2*p->hlen*p->vlen);
const int niter = 1 + 5000000 / (p->hlen * p->vlen + 1);
uint64_t tm;
tm = Sleef_currentTimeMicros();
for(int i=0;i<niter;i++) {
transpose(tBuf2, p->tBuf, p->log2hlen, p->log2vlen);
transpose(tBuf2, p->tBuf, p->log2vlen, p->log2hlen);
}
p->tmNoMT = Sleef_currentTimeMicros() - tm + 1;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose NoMT(measured): %lld\n", (long long int)p->tmNoMT);
#ifdef _OPENMP
tm = Sleef_currentTimeMicros();
for(int i=0;i<niter;i++) {
transposeMT(tBuf2, p->tBuf, p->log2hlen, p->log2vlen);
transposeMT(tBuf2, p->tBuf, p->log2vlen, p->log2hlen);
}
p->tmMT = Sleef_currentTimeMicros() - tm + 1;
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("transpose MT(measured): %lld\n", (long long int)p->tmMT);
#else
p->tmMT = p->tmNoMT*2;
#endif
Sleef_free(tBuf2);
PlanManager_saveMeasurementResultsT(p);
}
// Implementation of SleefDFT_*_init1d
EXPORT SleefDFT *INIT(uint32_t n, const real *in, real *out, uint64_t mode) {
SleefDFT *p = (SleefDFT *)calloc(1, sizeof(SleefDFT));
p->magic = MAGIC;
p->baseTypeID = BASETYPEID;
p->in = (const void *)in;
p->out = (void *)out;
// Mode
p->mode = mode;
if ((p->mode & SLEEF_MODE_NO_MT) == 0) {
p->mode2 |= SLEEF_MODE2_MT1D;
}
if ((mode & SLEEF_MODE_REAL) != 0) n /= 2;
p->log2len = ilog2(n);
if (p->log2len <= 1) return p;
if ((mode & SLEEF_MODE_ALT) != 0) p->mode = mode = mode ^ SLEEF_MODE_BACKWARD;
#ifdef _OPENMP
p->nThread = omp_thread_count();
#else
p->nThread = 1;
p->mode2 &= ~SLEEF_MODE2_MT1D;
#endif
// ISA availability
int bestPriority = -1;
p->isa = -1;
for(int i=0;i<ISAMAX;i++) {
if (checkISAAvailability(i) && bestPriority < (*GETINT[i])(GETINT_DFTPRIORITY) && n >= (*GETINT[i])(GETINT_VECWIDTH) * (*GETINT[i])(GETINT_VECWIDTH)) {
bestPriority = (*GETINT[i])(GETINT_DFTPRIORITY);
p->isa = i;
}
}
if (p->isa == -1) {
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("ISA not available\n");
p->magic = 0;
free(p);
return NULL;
}
// Tables
p->perm = (uint32_t **)calloc(sizeof(uint32_t *), p->log2len+1);
for(int level = p->log2len;level >= 1;level--) {
p->perm[level] = (uint32_t *)Sleef_malloc(sizeof(uint32_t) * ((1 << p->log2len) + 8));
}
p->x0 = malloc(sizeof(real *) * p->nThread);
p->x1 = malloc(sizeof(real *) * p->nThread);
for(int i=0;i<p->nThread;i++) {
p->x0[i] = (real *)Sleef_malloc(sizeof(real) * 2 * n);
p->x1[i] = (real *)Sleef_malloc(sizeof(real) * 2 * n);
}
if ((mode & SLEEF_MODE_REAL) != 0) {
p->rtCoef0 = (real *)Sleef_malloc(sizeof(real) * n);
p->rtCoef1 = (real *)Sleef_malloc(sizeof(real) * n);
if ((mode & SLEEF_MODE_BACKWARD) == 0) {
for(uint32_t i=0;i<n/2;i++) {
sc_t sc = SINCOSPI(i*((real)-1.0/n));
((real *)p->rtCoef0)[i*2+0] = ((real *)p->rtCoef0)[i*2+1] = (real)0.5 - (real)0.5 * sc.x;
((real *)p->rtCoef1)[i*2+0] = ((real *)p->rtCoef1)[i*2+1] = (real)0.5*sc.y;
}
} else {
for(uint32_t i=0;i<n/2;i++) {
sc_t sc = SINCOSPI(i*((real)-1.0/n));
((real *)p->rtCoef0)[i*2+0] = ((real *)p->rtCoef0)[i*2+1] = (real)0.5 + (real)0.5 * sc.x;
((real *)p->rtCoef1)[i*2+0] = ((real *)p->rtCoef1)[i*2+1] = (real)0.5*sc.y;
}
}
}
// Measure
int sign = (mode & SLEEF_MODE_BACKWARD) != 0 ? -1 : 1;
p->vecwidth = (*GETINT[p->isa])(GETINT_VECWIDTH);
p->log2vecwidth = ilog2(p->vecwidth);
for(int i=1;i<=MAXBUTWIDTH;i++) {
((real ***)p->tbl)[i] = makeTable(sign, p->vecwidth, p->log2len, i, constK[i]);
}
if (!measure(p, (mode & SLEEF_MODE_DEBUG))) {
// Fall back to the first ISA
freeTables(p);
p->isa = 0;
p->vecwidth = (*GETINT[p->isa])(GETINT_VECWIDTH);
p->log2vecwidth = ilog2(p->vecwidth);
for(int i=1;i<=MAXBUTWIDTH;i++) {
((real ***)p->tbl)[i] = makeTable(sign, p->vecwidth, p->log2len, i, constK[i]);
}
for(int level = p->log2len;level >= 1;) {
int N = ABS(p->bestPath[level]);
if (level == N) { level -= N; continue; }
int i1 = 0;
for(int i0=0;i0 < (1 << (p->log2len-N));i0+=p->vecwidth, i1++) {
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
for(;i1 < (1 << p->log2len) + 8;i1++) p->perm[level][i1] = 0;
level -= N;
}
if (!measure(p, (mode & SLEEF_MODE_DEBUG))) {
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("Suitable ISA not found. This should not happen.\n");
return NULL;
}
}
for(int level = p->log2len;level >= 1;) {
int N = ABS(p->bestPath[level]);
if (level == N) { level -= N; continue; }
int i1 = 0;
for(int i0=0;i0 < (1 << (p->log2len-N));i0+=p->vecwidth, i1++) {
p->perm[level][i1] = 2*perm(p->log2len, i0, p->log2len-level, p->log2len-(level-N));
}
for(;i1 < (1 << p->log2len) + 8;i1++) p->perm[level][i1] = 0;
level -= N;
}
if ((p->mode & SLEEF_MODE_VERBOSE) != 0) printf("ISA : %s %d bit %s\n", (char *)(*GETPTR[p->isa])(0), (int)(GETINT[p->isa](GETINT_VECWIDTH) * sizeof(real) * 16), BASETYPESTRING);
return p;
}
// Implementation of SleefDFT_*_init2d
EXPORT SleefDFT *INIT2D(uint32_t vlen, uint32_t hlen, const real *in, real *out, uint64_t mode) {
SleefDFT *p = (SleefDFT *)calloc(1, sizeof(SleefDFT));
p->magic = MAGIC2D;
p->mode = mode;
p->baseTypeID = BASETYPEID;
p->in = in;
p->out = out;
p->hlen = hlen;
p->log2hlen = ilog2(hlen);
p->vlen = vlen;
p->log2vlen = ilog2(vlen);
uint64_t mode1D = mode;
mode1D |= SLEEF_MODE_NO_MT;
if ((mode & SLEEF_MODE_NO_MT) == 0) p->mode3 |= SLEEF_MODE3_MT2D;
p->instH = p->instV = INIT(hlen, NULL, NULL, mode1D);
if (hlen != vlen) p->instV = INIT(vlen, NULL, NULL, mode1D);
p->tBuf = (void *)Sleef_malloc(sizeof(real)*2*hlen*vlen);
measureTranspose(p);
return p;
}
// Implementation of SleefDFT_*_execute
EXPORT void EXECUTE(SleefDFT *p, const real *s0, real *d0) {
assert(p != NULL && (p->magic == MAGIC || p->magic == MAGIC2D));
const real *s = s0 == NULL ? p->in : s0;
real *d = d0 == NULL ? p->out : d0;
if (p->magic == MAGIC2D) {
// S -> T -> D -> T -> D
real *tBuf = (real *)(p->tBuf);
#ifdef _OPENMP
if ((p->mode3 & SLEEF_MODE3_MT2D) != 0 &&
(((p->mode & SLEEF_MODE_DEBUG) == 0 && p->tmMT < p->tmNoMT) ||
((p->mode & SLEEF_MODE_DEBUG) != 0 && (rand() & 1))))
{
int y=0;
#pragma omp parallel for
for(y=0;y<p->vlen;y++) {
EXECUTE(p->instH, &s[p->hlen*2*y], &tBuf[p->hlen*2*y]);
}
transposeMT(d, tBuf, p->log2vlen, p->log2hlen);
#pragma omp parallel for
for(y=0;y<p->hlen;y++) {
EXECUTE(p->instV, &d[p->vlen*2*y], &tBuf[p->vlen*2*y]);
}
transposeMT(d, tBuf, p->log2hlen, p->log2vlen);
} else
#endif
{
for(int y=0;y<p->vlen;y++) {
EXECUTE(p->instH, &s[p->hlen*2*y], &tBuf[p->hlen*2*y]);
}
transpose(d, tBuf, p->log2vlen, p->log2hlen);
for(int y=0;y<p->hlen;y++) {
EXECUTE(p->instV, &d[p->vlen*2*y], &tBuf[p->vlen*2*y]);
}
transpose(d, tBuf, p->log2hlen, p->log2vlen);
}
return;
}
if (p->log2len <= 1) {
if ((p->mode & SLEEF_MODE_REAL) == 0) {
real r0 = s[0] + s[2];
real r1 = s[1] + s[3];
real r2 = s[0] - s[2];
real r3 = s[1] - s[3];
d[0] = r0; d[1] = r1; d[2] = r2; d[3] = r3;
} else {
if ((p->mode & SLEEF_MODE_ALT) == 0) {
if (p->log2len == 1) {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
real r0 = s[0] + s[2] + (s[1] + s[3]);
real r1 = s[0] + s[2] - (s[1] + s[3]);
real r2 = s[0] - s[2];
real r3 = s[3] - s[1];
d[0] = r0; d[1] = 0; d[2] = r2; d[3] = r3; d[4] = r1; d[5] = 0;
} else {
real r0 = (s[0] + s[4])*(real)0.5 + s[2];
real r1 = (s[0] - s[4])*(real)0.5 - s[3];
real r2 = (s[0] + s[4])*(real)0.5 - s[2];
real r3 = (s[0] - s[4])*(real)0.5 + s[3];
d[0] = r0*2; d[1] = r1*2; d[2] = r2*2; d[3] = r3*2;
}
} else {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
real r0 = s[0] + s[1];
real r1 = s[0] - s[1];
d[0] = r0; d[1] = 0; d[2] = r1; d[3] = 0;
} else {
real r0 = s[0] + s[2];
real r1 = s[0] - s[2];
d[0] = r0; d[1] = r1;
}
}
} else {
if (p->log2len == 1) {
if ((p->mode & SLEEF_MODE_BACKWARD) == 0) {
real r0 = s[0] + s[2] + (s[1] + s[3]);
real r1 = s[0] + s[2] - (s[1] + s[3]);
real r2 = s[0] - s[2];
real r3 = s[1] - s[3];
d[0] = r0; d[1] = r1; d[2] = r2; d[3] = r3;
} else {
real r0 = (s[0] + s[1])*(real)0.5 + s[2];
real r1 = (s[0] - s[1])*(real)0.5 + s[3];
real r2 = (s[0] + s[1])*(real)0.5 - s[2];
real r3 = (s[0] - s[1])*(real)0.5 - s[3];
d[0] = r0; d[1] = r1; d[2] = r2; d[3] = r3;
}
} else {
real c = ((p->mode & SLEEF_MODE_BACKWARD) != 0) ? (real)0.5 : (real)1.0;
real r0 = s[0] + s[1];
real r1 = s[0] - s[1];
d[0] = r0 * c; d[1] = r1 * c;
}
}
}
return;
}
//
#ifdef _OPENMP
const int tn = omp_get_thread_num();
real *t[] = { p->x1[tn], p->x0[tn], d };
#else
real *t[] = { p->x1[0], p->x0[0], d };
#endif
const real *lb = s;
int nb = 0;
if ((p->mode & SLEEF_MODE_REAL) != 0 && (p->pathLen & 1) == 0 &&
((p->mode & SLEEF_MODE_BACKWARD) != 0) != ((p->mode & SLEEF_MODE_ALT) != 0)) nb = -1;
if ((p->mode & SLEEF_MODE_REAL) == 0 && (p->pathLen & 1) == 1) nb = -1;
if ((p->mode & SLEEF_MODE_REAL) != 0 &&
((p->mode & SLEEF_MODE_BACKWARD) != 0) != ((p->mode & SLEEF_MODE_ALT) != 0)) {
(*REALSUB1[p->isa])(t[nb+1], s, p->log2len, p->rtCoef0, p->rtCoef1, (p->mode & SLEEF_MODE_ALT) == 0);
if ((p-> mode & SLEEF_MODE_ALT) == 0) t[nb+1][(1 << p->log2len)+1] = -s[(1 << p->log2len)+1] * 2;
lb = t[nb+1];
nb = (nb + 1) & 1;
}
for(int level = p->log2len;level >= 1;) {
int N = ABS(p->bestPath[level]), config = p->bestPathConfig[level];
dispatch(p, N, t[nb+1], lb, level, config);
level -= N;
lb = t[nb+1];
nb = (nb + 1) & 1;
}
if ((p->mode & SLEEF_MODE_REAL) != 0 &&
((p->mode & SLEEF_MODE_BACKWARD) == 0) != ((p->mode & SLEEF_MODE_ALT) != 0)) {
(*REALSUB0[p->isa])(d, lb, p->log2len, p->rtCoef0, p->rtCoef1);
if ((p->mode & SLEEF_MODE_ALT) == 0) {
d[(1 << p->log2len)+1] = -d[(1 << p->log2len)+1];
d[(2 << p->log2len)+0] = d[1];
d[(2 << p->log2len)+1] = 0;
d[1] = 0;
}
}
}
|
segment.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS EEEEE GGGG M M EEEEE N N TTTTT %
% SS E G MM MM E NN N T %
% SSS EEE G GGG M M M EEE N N N T %
% SS E G G M M E N NN T %
% SSSSS EEEEE GGGG M M EEEEE N N T %
% %
% %
% MagickCore Methods to Segment an Image with Thresholding Fuzzy c-Means %
% %
% Software Design %
% Cristy %
% April 1993 %
% %
% %
% Copyright 1999-2016 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. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Segment segments an image by analyzing the histograms of the color
% components and identifying units that are homogeneous with the fuzzy
% c-means technique. The scale-space filter analyzes the histograms of
% the three color components of the image and identifies a set of
% classes. The extents of each class is used to coarsely segment the
% image with thresholding. The color associated with each class is
% determined by the mean color of all pixels within the extents of a
% particular class. Finally, any unclassified pixels are assigned to
% the closest class with the fuzzy c-means technique.
%
% The fuzzy c-Means algorithm can be summarized as follows:
%
% o Build a histogram, one for each color component of the image.
%
% o For each histogram, successively apply the scale-space filter and
% build an interval tree of zero crossings in the second derivative
% at each scale. Analyze this scale-space ``fingerprint'' to
% determine which peaks and valleys in the histogram are most
% predominant.
%
% o The fingerprint defines intervals on the axis of the histogram.
% Each interval contains either a minima or a maxima in the original
% signal. If each color component lies within the maxima interval,
% that pixel is considered ``classified'' and is assigned an unique
% class number.
%
% o Any pixel that fails to be classified in the above thresholding
% pass is classified using the fuzzy c-Means technique. It is
% assigned to one of the classes discovered in the histogram analysis
% phase.
%
% The fuzzy c-Means technique attempts to cluster a pixel by finding
% the local minima of the generalized within group sum of squared error
% objective function. A pixel is assigned to the closest class of
% which the fuzzy membership has a maximum value.
%
% Segment is strongly based on software written by Andy Gallo,
% University of Delaware.
%
% The following reference was used in creating this program:
%
% Young Won Lim, Sang Uk Lee, "On The Color Image Segmentation
% Algorithm Based on the Thresholding and the Fuzzy c-Means
% Techniques", Pattern Recognition, Volume 23, Number 9, pages
% 935-952, 1990.
%
%
*/
#include "magick/studio.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/quantize.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
/*
Define declarations.
*/
#define MaxDimension 3
#define DeltaTau 0.5f
#if defined(FastClassify)
#define WeightingExponent 2.0
#define SegmentPower(ratio) (ratio)
#else
#define WeightingExponent 2.5
#define SegmentPower(ratio) pow(ratio,(double) (1.0/(weighting_exponent-1.0)));
#endif
#define Tau 5.2f
/*
Typedef declarations.
*/
typedef struct _ExtentPacket
{
MagickRealType
center;
ssize_t
index,
left,
right;
} ExtentPacket;
typedef struct _Cluster
{
struct _Cluster
*next;
ExtentPacket
red,
green,
blue;
ssize_t
count,
id;
} Cluster;
typedef struct _IntervalTree
{
MagickRealType
tau;
ssize_t
left,
right;
MagickRealType
mean_stability,
stability;
struct _IntervalTree
*sibling,
*child;
} IntervalTree;
typedef struct _ZeroCrossing
{
MagickRealType
tau,
histogram[256];
short
crossings[256];
} ZeroCrossing;
/*
Constant declarations.
*/
static const int
Blue = 2,
Green = 1,
Red = 0,
SafeMargin = 3,
TreeLength = 600;
/*
Method prototypes.
*/
static MagickRealType
OptimalTau(const ssize_t *,const double,const double,const double,
const double,short *);
static ssize_t
DefineRegion(const short *,ExtentPacket *);
static void
InitializeHistogram(const Image *,ssize_t **,ExceptionInfo *),
ScaleSpace(const ssize_t *,const MagickRealType,MagickRealType *),
ZeroCrossHistogram(MagickRealType *,const MagickRealType,short *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l a s s i f y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Classify() defines one or more classes. Each pixel is thresholded to
% determine which class it belongs to. If the class is not identified it is
% assigned to the closest class based on the fuzzy c-Means technique.
%
% The format of the Classify method is:
%
% MagickBooleanType Classify(Image *image,short **extrema,
% const MagickRealType cluster_threshold,
% const MagickRealType weighting_exponent,
% const MagickBooleanType verbose)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
% o cluster_threshold: This MagickRealType represents the minimum number of
% pixels contained in a hexahedra before it can be considered valid
% (expressed as a percentage).
%
% o weighting_exponent: Specifies the membership weighting exponent.
%
% o verbose: A value greater than zero prints detailed information about
% the identified classes.
%
*/
static MagickBooleanType Classify(Image *image,short **extrema,
const MagickRealType cluster_threshold,
const MagickRealType weighting_exponent,const MagickBooleanType verbose)
{
#define SegmentImageTag "Segment/Image"
CacheView
*image_view;
Cluster
*cluster,
*head,
*last_cluster,
*next_cluster;
ExceptionInfo
*exception;
ExtentPacket
blue,
green,
red;
MagickOffsetType
progress;
MagickRealType
*free_squares;
MagickStatusType
status;
register ssize_t
i;
register MagickRealType
*squares;
size_t
number_clusters;
ssize_t
count,
y;
/*
Form clusters.
*/
cluster=(Cluster *) NULL;
head=(Cluster *) NULL;
(void) ResetMagickMemory(&red,0,sizeof(red));
(void) ResetMagickMemory(&green,0,sizeof(green));
(void) ResetMagickMemory(&blue,0,sizeof(blue));
while (DefineRegion(extrema[Red],&red) != 0)
{
green.index=0;
while (DefineRegion(extrema[Green],&green) != 0)
{
blue.index=0;
while (DefineRegion(extrema[Blue],&blue) != 0)
{
/*
Allocate a new class.
*/
if (head != (Cluster *) NULL)
{
cluster->next=(Cluster *) AcquireMagickMemory(
sizeof(*cluster->next));
cluster=cluster->next;
}
else
{
cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
head=cluster;
}
if (cluster == (Cluster *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
}
}
}
if (head == (Cluster *) NULL)
{
/*
No classes were identified-- create one.
*/
cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
if (cluster == (Cluster *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
head=cluster;
}
/*
Count the pixels for each cluster.
*/
status=MagickTrue;
count=0;
progress=0;
exception=(&image->exception);
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
if (((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) >=
(cluster->red.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) <=
(cluster->red.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) >=
(cluster->green.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) <=
(cluster->green.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) >=
(cluster->blue.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) <=
(cluster->blue.right+SafeMargin)))
{
/*
Count this pixel.
*/
count++;
cluster->red.center+=(MagickRealType) ScaleQuantumToChar(GetPixelRed(p));
cluster->green.center+=(MagickRealType)
ScaleQuantumToChar(GetPixelGreen(p));
cluster->blue.center+=(MagickRealType) ScaleQuantumToChar(GetPixelBlue(p));
cluster->count++;
break;
}
p++;
}
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_Classify)
#endif
proceed=SetImageProgress(image,SegmentImageTag,progress++,
2*image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
/*
Remove clusters that do not meet minimum cluster threshold.
*/
count=0;
last_cluster=head;
next_cluster=head;
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
if ((cluster->count > 0) &&
(cluster->count >= (count*cluster_threshold/100.0)))
{
/*
Initialize cluster.
*/
cluster->id=count;
cluster->red.center/=cluster->count;
cluster->green.center/=cluster->count;
cluster->blue.center/=cluster->count;
count++;
last_cluster=cluster;
continue;
}
/*
Delete cluster.
*/
if (cluster == head)
head=next_cluster;
else
last_cluster->next=next_cluster;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
number_clusters=(size_t) count;
if (verbose != MagickFalse)
{
/*
Print cluster statistics.
*/
(void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n");
(void) FormatLocaleFile(stdout,"===================\n\n");
(void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double)
cluster_threshold);
(void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double)
weighting_exponent);
(void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n",
(double) number_clusters);
/*
Print the total number of points per cluster.
*/
(void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n");
(void) FormatLocaleFile(stdout,"=============================\n\n");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
(void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double)
cluster->id,(double) cluster->count);
/*
Print the cluster extents.
*/
(void) FormatLocaleFile(stdout,
"\n\n\nCluster Extents: (Vector Size: %d)\n",MaxDimension);
(void) FormatLocaleFile(stdout,"================");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
(void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
cluster->id);
(void) FormatLocaleFile(stdout,
"%.20g-%.20g %.20g-%.20g %.20g-%.20g\n",(double)
cluster->red.left,(double) cluster->red.right,(double)
cluster->green.left,(double) cluster->green.right,(double)
cluster->blue.left,(double) cluster->blue.right);
}
/*
Print the cluster center values.
*/
(void) FormatLocaleFile(stdout,
"\n\n\nCluster Center Values: (Vector Size: %d)\n",MaxDimension);
(void) FormatLocaleFile(stdout,"=====================");
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
(void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double)
cluster->id);
(void) FormatLocaleFile(stdout,"%g %g %g\n",(double)
cluster->red.center,(double) cluster->green.center,(double)
cluster->blue.center);
}
(void) FormatLocaleFile(stdout,"\n");
}
if (number_clusters > 256)
ThrowBinaryException(ImageError,"TooManyClusters",image->filename);
/*
Speed up distance calculations.
*/
squares=(MagickRealType *) AcquireQuantumMemory(513UL,sizeof(*squares));
if (squares == (MagickRealType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
squares+=255;
for (i=(-255); i <= 255; i++)
squares[i]=(MagickRealType) i*(MagickRealType) i;
/*
Allocate image colormap.
*/
if (AcquireImageColormap(image,number_clusters) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
i=0;
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
(cluster->red.center+0.5));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
(cluster->green.center+0.5));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
(cluster->blue.center+0.5));
i++;
}
/*
Do course grain classes.
*/
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
Cluster
*cluster;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(indexes+x,0);
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
{
if (((ssize_t) ScaleQuantumToChar(q->red) >=
(cluster->red.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(q->red) <=
(cluster->red.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(q->green) >=
(cluster->green.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(q->green) <=
(cluster->green.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(q->blue) >=
(cluster->blue.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(q->blue) <=
(cluster->blue.right+SafeMargin)))
{
/*
Classify this pixel.
*/
SetPixelIndex(indexes+x,cluster->id);
break;
}
}
if (cluster == (Cluster *) NULL)
{
MagickRealType
distance_squared,
local_minima,
numerator,
ratio,
sum;
register ssize_t
j,
k;
/*
Compute fuzzy membership.
*/
local_minima=0.0;
for (j=0; j < (ssize_t) image->colors; j++)
{
sum=0.0;
p=image->colormap+j;
distance_squared=squares[(ssize_t) ScaleQuantumToChar(q->red)-
(ssize_t) ScaleQuantumToChar(GetPixelRed(p))]+
squares[(ssize_t) ScaleQuantumToChar(q->green)-
(ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]+
squares[(ssize_t) ScaleQuantumToChar(q->blue)-
(ssize_t) ScaleQuantumToChar(GetPixelBlue(p))];
numerator=distance_squared;
for (k=0; k < (ssize_t) image->colors; k++)
{
p=image->colormap+k;
distance_squared=squares[(ssize_t) ScaleQuantumToChar(q->red)-
(ssize_t) ScaleQuantumToChar(GetPixelRed(p))]+
squares[(ssize_t) ScaleQuantumToChar(q->green)-
(ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]+
squares[(ssize_t) ScaleQuantumToChar(q->blue)-
(ssize_t) ScaleQuantumToChar(GetPixelBlue(p))];
ratio=numerator/distance_squared;
sum+=SegmentPower(ratio);
}
if ((sum != 0.0) && ((1.0/sum) > local_minima))
{
/*
Classify this pixel.
*/
local_minima=1.0/sum;
SetPixelIndex(indexes+x,j);
}
}
}
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_Classify)
#endif
proceed=SetImageProgress(image,SegmentImageTag,progress++,
2*image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
status&=SyncImage(image);
/*
Relinquish resources.
*/
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
squares-=255;
free_squares=squares;
free_squares=(MagickRealType *) RelinquishMagickMemory(free_squares);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n s o l i d a t e C r o s s i n g s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConsolidateCrossings() guarantees that an even number of zero crossings
% always lie between two crossings.
%
% The format of the ConsolidateCrossings method is:
%
% ConsolidateCrossings(ZeroCrossing *zero_crossing,
% const size_t number_crossings)
%
% A description of each parameter follows.
%
% o zero_crossing: Specifies an array of structures of type ZeroCrossing.
%
% o number_crossings: This size_t specifies the number of elements
% in the zero_crossing array.
%
*/
static void ConsolidateCrossings(ZeroCrossing *zero_crossing,
const size_t number_crossings)
{
register ssize_t
i,
j,
k,
l;
ssize_t
center,
correct,
count,
left,
right;
/*
Consolidate zero crossings.
*/
for (i=(ssize_t) number_crossings-1; i >= 0; i--)
for (j=0; j <= 255; j++)
{
if (zero_crossing[i].crossings[j] == 0)
continue;
/*
Find the entry that is closest to j and still preserves the
property that there are an even number of crossings between
intervals.
*/
for (k=j-1; k > 0; k--)
if (zero_crossing[i+1].crossings[k] != 0)
break;
left=MagickMax(k,0);
center=j;
for (k=j+1; k < 255; k++)
if (zero_crossing[i+1].crossings[k] != 0)
break;
right=MagickMin(k,255);
/*
K is the zero crossing just left of j.
*/
for (k=j-1; k > 0; k--)
if (zero_crossing[i].crossings[k] != 0)
break;
if (k < 0)
k=0;
/*
Check center for an even number of crossings between k and j.
*/
correct=(-1);
if (zero_crossing[i+1].crossings[j] != 0)
{
count=0;
for (l=k+1; l < center; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (center != k))
correct=center;
}
/*
Check left for an even number of crossings between k and j.
*/
if (correct == -1)
{
count=0;
for (l=k+1; l < left; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (left != k))
correct=left;
}
/*
Check right for an even number of crossings between k and j.
*/
if (correct == -1)
{
count=0;
for (l=k+1; l < right; l++)
if (zero_crossing[i+1].crossings[l] != 0)
count++;
if (((count % 2) == 0) && (right != k))
correct=right;
}
l=(ssize_t) zero_crossing[i].crossings[j];
zero_crossing[i].crossings[j]=0;
if (correct != -1)
zero_crossing[i].crossings[correct]=(short) l;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e f i n e R e g i o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DefineRegion() defines the left and right boundaries of a peak region.
%
% The format of the DefineRegion method is:
%
% ssize_t DefineRegion(const short *extrema,ExtentPacket *extents)
%
% A description of each parameter follows.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
% o extents: This pointer to an ExtentPacket represent the extends
% of a particular peak or valley of a color component.
%
*/
static ssize_t DefineRegion(const short *extrema,ExtentPacket *extents)
{
/*
Initialize to default values.
*/
extents->left=0;
extents->center=0.0;
extents->right=255;
/*
Find the left side (maxima).
*/
for ( ; extents->index <= 255; extents->index++)
if (extrema[extents->index] > 0)
break;
if (extents->index > 255)
return(MagickFalse); /* no left side - no region exists */
extents->left=extents->index;
/*
Find the right side (minima).
*/
for ( ; extents->index <= 255; extents->index++)
if (extrema[extents->index] < 0)
break;
extents->right=extents->index-1;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e r i v a t i v e H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DerivativeHistogram() determines the derivative of the histogram using
% central differencing.
%
% The format of the DerivativeHistogram method is:
%
% DerivativeHistogram(const MagickRealType *histogram,
% MagickRealType *derivative)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of MagickRealTypes representing the number
% of pixels for each intensity of a particular color component.
%
% o derivative: This array of MagickRealTypes is initialized by
% DerivativeHistogram to the derivative of the histogram using central
% differencing.
%
*/
static void DerivativeHistogram(const MagickRealType *histogram,
MagickRealType *derivative)
{
register ssize_t
i,
n;
/*
Compute endpoints using second order polynomial interpolation.
*/
n=255;
derivative[0]=(-1.5*histogram[0]+2.0*histogram[1]-0.5*histogram[2]);
derivative[n]=(0.5*histogram[n-2]-2.0*histogram[n-1]+1.5*histogram[n]);
/*
Compute derivative using central differencing.
*/
for (i=1; i < n; i++)
derivative[i]=(histogram[i+1]-histogram[i-1])/2.0;
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e D y n a m i c T h r e s h o l d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageDynamicThreshold() returns the dynamic threshold for an image.
%
% The format of the GetImageDynamicThreshold method is:
%
% MagickBooleanType GetImageDynamicThreshold(const Image *image,
% const double cluster_threshold,const double smooth_threshold,
% MagickPixelPacket *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o cluster_threshold: This MagickRealType represents the minimum number of
% pixels contained in a hexahedra before it can be considered valid
% (expressed as a percentage).
%
% o smooth_threshold: the smoothing threshold eliminates noise in the second
% derivative of the histogram. As the value is increased, you can expect a
% smoother second derivative.
%
% o pixel: return the dynamic threshold here.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *image,
const double cluster_threshold,const double smooth_threshold,
MagickPixelPacket *pixel,ExceptionInfo *exception)
{
Cluster
*background,
*cluster,
*object,
*head,
*last_cluster,
*next_cluster;
ExtentPacket
blue,
green,
red;
MagickBooleanType
proceed;
MagickRealType
threshold;
register const PixelPacket
*p;
register ssize_t
i,
x;
short
*extrema[MaxDimension];
ssize_t
count,
*histogram[MaxDimension],
y;
/*
Allocate histogram and extrema.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
GetMagickPixelPacket(image,pixel);
for (i=0; i < MaxDimension; i++)
{
histogram[i]=(ssize_t *) AcquireQuantumMemory(256UL,sizeof(**histogram));
extrema[i]=(short *) AcquireQuantumMemory(256UL,sizeof(**histogram));
if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL))
{
for (i-- ; i >= 0; i--)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
}
/*
Initialize histogram.
*/
InitializeHistogram(image,histogram,exception);
(void) OptimalTau(histogram[Red],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Red]);
(void) OptimalTau(histogram[Green],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Green]);
(void) OptimalTau(histogram[Blue],Tau,0.2f,DeltaTau,
(smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Blue]);
/*
Form clusters.
*/
cluster=(Cluster *) NULL;
head=(Cluster *) NULL;
(void) ResetMagickMemory(&red,0,sizeof(red));
(void) ResetMagickMemory(&green,0,sizeof(green));
(void) ResetMagickMemory(&blue,0,sizeof(blue));
while (DefineRegion(extrema[Red],&red) != 0)
{
green.index=0;
while (DefineRegion(extrema[Green],&green) != 0)
{
blue.index=0;
while (DefineRegion(extrema[Blue],&blue) != 0)
{
/*
Allocate a new class.
*/
if (head != (Cluster *) NULL)
{
cluster->next=(Cluster *) AcquireMagickMemory(
sizeof(*cluster->next));
cluster=cluster->next;
}
else
{
cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
head=cluster;
}
if (cluster == (Cluster *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
return(MagickFalse);
}
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
}
}
}
if (head == (Cluster *) NULL)
{
/*
No classes were identified-- create one.
*/
cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster));
if (cluster == (Cluster *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
/*
Initialize a new class.
*/
cluster->count=0;
cluster->red=red;
cluster->green=green;
cluster->blue=blue;
cluster->next=(Cluster *) NULL;
head=cluster;
}
/*
Count the pixels for each cluster.
*/
count=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next)
if (((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) >=
(cluster->red.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) <=
(cluster->red.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) >=
(cluster->green.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) <=
(cluster->green.right+SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) >=
(cluster->blue.left-SafeMargin)) &&
((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) <=
(cluster->blue.right+SafeMargin)))
{
/*
Count this pixel.
*/
count++;
cluster->red.center+=(MagickRealType)
ScaleQuantumToChar(GetPixelRed(p));
cluster->green.center+=(MagickRealType)
ScaleQuantumToChar(GetPixelGreen(p));
cluster->blue.center+=(MagickRealType)
ScaleQuantumToChar(GetPixelBlue(p));
cluster->count++;
break;
}
p++;
}
proceed=SetImageProgress(image,SegmentImageTag,(MagickOffsetType) y,
2*image->rows);
if (proceed == MagickFalse)
break;
}
/*
Remove clusters that do not meet minimum cluster threshold.
*/
count=0;
last_cluster=head;
next_cluster=head;
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
if ((cluster->count > 0) &&
(cluster->count >= (count*cluster_threshold/100.0)))
{
/*
Initialize cluster.
*/
cluster->id=count;
cluster->red.center/=cluster->count;
cluster->green.center/=cluster->count;
cluster->blue.center/=cluster->count;
count++;
last_cluster=cluster;
continue;
}
/*
Delete cluster.
*/
if (cluster == head)
head=next_cluster;
else
last_cluster->next=next_cluster;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
object=head;
background=head;
if (count > 1)
{
object=head->next;
for (cluster=object; cluster->next != (Cluster *) NULL; )
{
if (cluster->count < object->count)
object=cluster;
cluster=cluster->next;
}
background=head->next;
for (cluster=background; cluster->next != (Cluster *) NULL; )
{
if (cluster->count > background->count)
background=cluster;
cluster=cluster->next;
}
}
if (background != (Cluster *) NULL)
{
threshold=(background->red.center+object->red.center)/2.0;
pixel->red=(MagickRealType) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
threshold=(background->green.center+object->green.center)/2.0;
pixel->green=(MagickRealType) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
threshold=(background->blue.center+object->blue.center)/2.0;
pixel->blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
(threshold+0.5));
}
/*
Relinquish resources.
*/
for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster)
{
next_cluster=cluster->next;
cluster=(Cluster *) RelinquishMagickMemory(cluster);
}
for (i=0; i < MaxDimension; i++)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n i t i a l i z e H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitializeHistogram() computes the histogram for an image.
%
% The format of the InitializeHistogram method is:
%
% InitializeHistogram(const Image *image,ssize_t **histogram)
%
% A description of each parameter follows.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
% o histogram: Specifies an array of integers representing the number
% of pixels for each intensity of a particular color component.
%
*/
static void InitializeHistogram(const Image *image,ssize_t **histogram,
ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Initialize histogram.
*/
for (i=0; i <= 255; i++)
{
histogram[Red][i]=0;
histogram[Green][i]=0;
histogram[Blue][i]=0;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
histogram[Red][(ssize_t) ScaleQuantumToChar(GetPixelRed(p))]++;
histogram[Green][(ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]++;
histogram[Blue][(ssize_t) ScaleQuantumToChar(GetPixelBlue(p))]++;
p++;
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n i t i a l i z e I n t e r v a l T r e e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitializeIntervalTree() initializes an interval tree from the lists of
% zero crossings.
%
% The format of the InitializeIntervalTree method is:
%
% InitializeIntervalTree(IntervalTree **list,ssize_t *number_nodes,
% IntervalTree *node)
%
% A description of each parameter follows.
%
% o zero_crossing: Specifies an array of structures of type ZeroCrossing.
%
% o number_crossings: This size_t specifies the number of elements
% in the zero_crossing array.
%
*/
static void InitializeList(IntervalTree **list,ssize_t *number_nodes,
IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->child == (IntervalTree *) NULL)
list[(*number_nodes)++]=node;
InitializeList(list,number_nodes,node->sibling);
InitializeList(list,number_nodes,node->child);
}
static void MeanStability(IntervalTree *node)
{
register IntervalTree
*child;
if (node == (IntervalTree *) NULL)
return;
node->mean_stability=0.0;
child=node->child;
if (child != (IntervalTree *) NULL)
{
register ssize_t
count;
register MagickRealType
sum;
sum=0.0;
count=0;
for ( ; child != (IntervalTree *) NULL; child=child->sibling)
{
sum+=child->stability;
count++;
}
node->mean_stability=sum/(MagickRealType) count;
}
MeanStability(node->sibling);
MeanStability(node->child);
}
static void Stability(IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->child == (IntervalTree *) NULL)
node->stability=0.0;
else
node->stability=node->tau-(node->child)->tau;
Stability(node->sibling);
Stability(node->child);
}
static IntervalTree *InitializeIntervalTree(const ZeroCrossing *zero_crossing,
const size_t number_crossings)
{
IntervalTree
*head,
**list,
*node,
*root;
register ssize_t
i;
ssize_t
j,
k,
left,
number_nodes;
/*
Allocate interval tree.
*/
list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength,
sizeof(*list));
if (list == (IntervalTree **) NULL)
return((IntervalTree *) NULL);
/*
The root is the entire histogram.
*/
root=(IntervalTree *) AcquireMagickMemory(sizeof(*root));
root->child=(IntervalTree *) NULL;
root->sibling=(IntervalTree *) NULL;
root->tau=0.0;
root->left=0;
root->right=255;
for (i=(-1); i < (ssize_t) number_crossings; i++)
{
/*
Initialize list with all nodes with no children.
*/
number_nodes=0;
InitializeList(list,&number_nodes,root);
/*
Split list.
*/
for (j=0; j < number_nodes; j++)
{
head=list[j];
left=head->left;
node=head;
for (k=head->left+1; k < head->right; k++)
{
if (zero_crossing[i+1].crossings[k] != 0)
{
if (node == head)
{
node->child=(IntervalTree *) AcquireMagickMemory(
sizeof(*node->child));
node=node->child;
}
else
{
node->sibling=(IntervalTree *) AcquireMagickMemory(
sizeof(*node->sibling));
node=node->sibling;
}
node->tau=zero_crossing[i+1].tau;
node->child=(IntervalTree *) NULL;
node->sibling=(IntervalTree *) NULL;
node->left=left;
node->right=k;
left=k;
}
}
if (left != head->left)
{
node->sibling=(IntervalTree *) AcquireMagickMemory(
sizeof(*node->sibling));
node=node->sibling;
node->tau=zero_crossing[i+1].tau;
node->child=(IntervalTree *) NULL;
node->sibling=(IntervalTree *) NULL;
node->left=left;
node->right=head->right;
}
}
}
/*
Determine the stability: difference between a nodes tau and its child.
*/
Stability(root->child);
MeanStability(root->child);
list=(IntervalTree **) RelinquishMagickMemory(list);
return(root);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ O p t i m a l T a u %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OptimalTau() finds the optimal tau for each band of the histogram.
%
% The format of the OptimalTau method is:
%
% MagickRealType OptimalTau(const ssize_t *histogram,const double max_tau,
% const double min_tau,const double delta_tau,
% const double smooth_threshold,short *extrema)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of integers representing the number
% of pixels for each intensity of a particular color component.
%
% o extrema: Specifies a pointer to an array of integers. They
% represent the peaks and valleys of the histogram for each color
% component.
%
*/
static void ActiveNodes(IntervalTree **list,ssize_t *number_nodes,
IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
if (node->stability >= node->mean_stability)
{
list[(*number_nodes)++]=node;
ActiveNodes(list,number_nodes,node->sibling);
}
else
{
ActiveNodes(list,number_nodes,node->sibling);
ActiveNodes(list,number_nodes,node->child);
}
}
static void FreeNodes(IntervalTree *node)
{
if (node == (IntervalTree *) NULL)
return;
FreeNodes(node->sibling);
FreeNodes(node->child);
node=(IntervalTree *) RelinquishMagickMemory(node);
}
static MagickRealType OptimalTau(const ssize_t *histogram,const double max_tau,
const double min_tau,const double delta_tau,const double smooth_threshold,
short *extrema)
{
IntervalTree
**list,
*node,
*root;
MagickBooleanType
peak;
MagickRealType
average_tau,
*derivative,
*second_derivative,
tau,
value;
register ssize_t
i,
x;
size_t
count,
number_crossings;
ssize_t
index,
j,
k,
number_nodes;
ZeroCrossing
*zero_crossing;
/*
Allocate interval tree.
*/
list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength,
sizeof(*list));
if (list == (IntervalTree **) NULL)
return(0.0);
/*
Allocate zero crossing list.
*/
count=(size_t) ((max_tau-min_tau)/delta_tau)+2;
zero_crossing=(ZeroCrossing *) AcquireQuantumMemory((size_t) count,
sizeof(*zero_crossing));
if (zero_crossing == (ZeroCrossing *) NULL)
return(0.0);
for (i=0; i < (ssize_t) count; i++)
zero_crossing[i].tau=(-1.0);
/*
Initialize zero crossing list.
*/
derivative=(MagickRealType *) AcquireQuantumMemory(256,sizeof(*derivative));
second_derivative=(MagickRealType *) AcquireQuantumMemory(256,
sizeof(*second_derivative));
if ((derivative == (MagickRealType *) NULL) ||
(second_derivative == (MagickRealType *) NULL))
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDerivatives");
i=0;
for (tau=max_tau; tau >= min_tau; tau-=delta_tau)
{
zero_crossing[i].tau=tau;
ScaleSpace(histogram,tau,zero_crossing[i].histogram);
DerivativeHistogram(zero_crossing[i].histogram,derivative);
DerivativeHistogram(derivative,second_derivative);
ZeroCrossHistogram(second_derivative,smooth_threshold,
zero_crossing[i].crossings);
i++;
}
/*
Add an entry for the original histogram.
*/
zero_crossing[i].tau=0.0;
for (j=0; j <= 255; j++)
zero_crossing[i].histogram[j]=(MagickRealType) histogram[j];
DerivativeHistogram(zero_crossing[i].histogram,derivative);
DerivativeHistogram(derivative,second_derivative);
ZeroCrossHistogram(second_derivative,smooth_threshold,
zero_crossing[i].crossings);
number_crossings=(size_t) i;
derivative=(MagickRealType *) RelinquishMagickMemory(derivative);
second_derivative=(MagickRealType *)
RelinquishMagickMemory(second_derivative);
/*
Ensure the scale-space fingerprints form lines in scale-space, not loops.
*/
ConsolidateCrossings(zero_crossing,number_crossings);
/*
Force endpoints to be included in the interval.
*/
for (i=0; i <= (ssize_t) number_crossings; i++)
{
for (j=0; j < 255; j++)
if (zero_crossing[i].crossings[j] != 0)
break;
zero_crossing[i].crossings[0]=(-zero_crossing[i].crossings[j]);
for (j=255; j > 0; j--)
if (zero_crossing[i].crossings[j] != 0)
break;
zero_crossing[i].crossings[255]=(-zero_crossing[i].crossings[j]);
}
/*
Initialize interval tree.
*/
root=InitializeIntervalTree(zero_crossing,number_crossings);
if (root == (IntervalTree *) NULL)
return(0.0);
/*
Find active nodes: stability is greater (or equal) to the mean stability of
its children.
*/
number_nodes=0;
ActiveNodes(list,&number_nodes,root->child);
/*
Initialize extrema.
*/
for (i=0; i <= 255; i++)
extrema[i]=0;
for (i=0; i < number_nodes; i++)
{
/*
Find this tau in zero crossings list.
*/
k=0;
node=list[i];
for (j=0; j <= (ssize_t) number_crossings; j++)
if (zero_crossing[j].tau == node->tau)
k=j;
/*
Find the value of the peak.
*/
peak=zero_crossing[k].crossings[node->right] == -1 ? MagickTrue :
MagickFalse;
index=node->left;
value=zero_crossing[k].histogram[index];
for (x=node->left; x <= node->right; x++)
{
if (peak != MagickFalse)
{
if (zero_crossing[k].histogram[x] > value)
{
value=zero_crossing[k].histogram[x];
index=x;
}
}
else
if (zero_crossing[k].histogram[x] < value)
{
value=zero_crossing[k].histogram[x];
index=x;
}
}
for (x=node->left; x <= node->right; x++)
{
if (index == 0)
index=256;
if (peak != MagickFalse)
extrema[x]=(short) index;
else
extrema[x]=(short) (-index);
}
}
/*
Determine the average tau.
*/
average_tau=0.0;
for (i=0; i < number_nodes; i++)
average_tau+=list[i]->tau;
average_tau/=(MagickRealType) number_nodes;
/*
Relinquish resources.
*/
FreeNodes(root);
zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing);
list=(IntervalTree **) RelinquishMagickMemory(list);
return(average_tau);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S c a l e S p a c e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleSpace() performs a scale-space filter on the 1D histogram.
%
% The format of the ScaleSpace method is:
%
% ScaleSpace(const ssize_t *histogram,const MagickRealType tau,
% MagickRealType *scale_histogram)
%
% A description of each parameter follows.
%
% o histogram: Specifies an array of MagickRealTypes representing the number
% of pixels for each intensity of a particular color component.
%
*/
static void ScaleSpace(const ssize_t *histogram,const MagickRealType tau,
MagickRealType *scale_histogram)
{
double
alpha,
beta,
*gamma,
sum;
register ssize_t
u,
x;
gamma=(double *) AcquireQuantumMemory(256,sizeof(*gamma));
if (gamma == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAllocateGammaMap");
alpha=1.0/(tau*sqrt(2.0*MagickPI));
beta=(-1.0/(2.0*tau*tau));
for (x=0; x <= 255; x++)
gamma[x]=0.0;
for (x=0; x <= 255; x++)
{
gamma[x]=exp((double) beta*x*x);
if (gamma[x] < MagickEpsilon)
break;
}
for (x=0; x <= 255; x++)
{
sum=0.0;
for (u=0; u <= 255; u++)
sum+=(double) histogram[u]*gamma[MagickAbsoluteValue(x-u)];
scale_histogram[x]=(MagickRealType) (alpha*sum);
}
gamma=(double *) RelinquishMagickMemory(gamma);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e g m e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SegmentImage() segment an image by analyzing the histograms of the color
% components and identifying units that are homogeneous with the fuzzy
% C-means technique.
%
% The format of the SegmentImage method is:
%
% MagickBooleanType SegmentImage(Image *image,
% const ColorspaceType colorspace,const MagickBooleanType verbose,
% const double cluster_threshold,const double smooth_threshold)
%
% A description of each parameter follows.
%
% o image: the image.
%
% o colorspace: Indicate the colorspace.
%
% o verbose: Set to MagickTrue to print detailed information about the
% identified classes.
%
% o cluster_threshold: This represents the minimum number of pixels
% contained in a hexahedra before it can be considered valid (expressed
% as a percentage).
%
% o smooth_threshold: the smoothing threshold eliminates noise in the second
% derivative of the histogram. As the value is increased, you can expect a
% smoother second derivative.
%
*/
MagickExport MagickBooleanType SegmentImage(Image *image,
const ColorspaceType colorspace,const MagickBooleanType verbose,
const double cluster_threshold,const double smooth_threshold)
{
ColorspaceType
previous_colorspace;
MagickBooleanType
status;
register ssize_t
i;
short
*extrema[MaxDimension];
ssize_t
*histogram[MaxDimension];
/*
Allocate histogram and extrema.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
for (i=0; i < MaxDimension; i++)
{
histogram[i]=(ssize_t *) AcquireQuantumMemory(256,sizeof(**histogram));
extrema[i]=(short *) AcquireQuantumMemory(256,sizeof(**extrema));
if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL))
{
for (i-- ; i >= 0; i--)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename)
}
}
/*
Initialize histogram.
*/
previous_colorspace=image->colorspace;
(void) TransformImageColorspace(image,colorspace);
InitializeHistogram(image,histogram,&image->exception);
(void) OptimalTau(histogram[Red],Tau,0.2,DeltaTau,
smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Red]);
(void) OptimalTau(histogram[Green],Tau,0.2,DeltaTau,
smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Green]);
(void) OptimalTau(histogram[Blue],Tau,0.2,DeltaTau,
smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Blue]);
/*
Classify using the fuzzy c-Means technique.
*/
status=Classify(image,extrema,cluster_threshold,WeightingExponent,verbose);
(void) TransformImageColorspace(image,previous_colorspace);
/*
Relinquish resources.
*/
for (i=0; i < MaxDimension; i++)
{
extrema[i]=(short *) RelinquishMagickMemory(extrema[i]);
histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]);
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ Z e r o C r o s s H i s t o g r a m %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ZeroCrossHistogram() find the zero crossings in a histogram and marks
% directions as: 1 is negative to positive; 0 is zero crossing; and -1
% is positive to negative.
%
% The format of the ZeroCrossHistogram method is:
%
% ZeroCrossHistogram(MagickRealType *second_derivative,
% const MagickRealType smooth_threshold,short *crossings)
%
% A description of each parameter follows.
%
% o second_derivative: Specifies an array of MagickRealTypes representing the
% second derivative of the histogram of a particular color component.
%
% o crossings: This array of integers is initialized with
% -1, 0, or 1 representing the slope of the first derivative of the
% of a particular color component.
%
*/
static void ZeroCrossHistogram(MagickRealType *second_derivative,
const MagickRealType smooth_threshold,short *crossings)
{
register ssize_t
i;
ssize_t
parity;
/*
Merge low numbers to zero to help prevent noise.
*/
for (i=0; i <= 255; i++)
if ((second_derivative[i] < smooth_threshold) &&
(second_derivative[i] >= -smooth_threshold))
second_derivative[i]=0.0;
/*
Mark zero crossings.
*/
parity=0;
for (i=0; i <= 255; i++)
{
crossings[i]=0;
if (second_derivative[i] < 0.0)
{
if (parity > 0)
crossings[i]=(-1);
parity=1;
}
else
if (second_derivative[i] > 0.0)
{
if (parity < 0)
crossings[i]=1;
parity=(-1);
}
}
}
|
3d7pt_var.c | /*
* Order-1, 3D 7 point stencil with variable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*7);
for(m=0; m<7;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 24;
tile_size[3] = 512;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<7; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#pragma scop
for (t = 0; t < Nt-1; t++) {
for (i = 1; i < Nz-1; i++) {
for (j = 1; j < Ny-1; j++) {
for (k = 1; k < Nx-1; k++) {
A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] +
coef[1][i][j][k] * A[t%2][i-1][j ][k ] +
coef[2][i][j][k] * A[t%2][i ][j-1][k ] +
coef[3][i][j][k] * A[t%2][i ][j ][k-1] +
coef[4][i][j][k] * A[t%2][i+1][j ][k ] +
coef[5][i][j][k] * A[t%2][i ][j+1][k ] +
coef[6][i][j][k] * A[t%2][i ][j ][k+1];
}
}
}
}
#pragma endscop
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = min(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(1, "variable no-symmetry")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<7;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
helloworld.c | #include <stdio.h>
#include <omp.h>
int main()
{
#pragma omp parallel
{
printf("Hello World !\n");
}
return 0;
}
|
GB_unaryop__lnot_int64_bool.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__lnot_int64_bool
// op(A') function: GB_tran__lnot_int64_bool
// C type: int64_t
// A type: bool
// cast: int64_t cij = (int64_t) aij
// unaryop: cij = !(aij != 0)
#define GB_ATYPE \
bool
#define GB_CTYPE \
int64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
bool aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = !(x != 0) ;
// casting
#define GB_CASTING(z, aij) \
int64_t z = (int64_t) aij ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (z, aij) ; \
GB_OP (GB_CX (pC), z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LNOT || GxB_NO_INT64 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__lnot_int64_bool
(
int64_t *Cx, // Cx and Ax may be aliased
bool *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__lnot_int64_bool
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
tp3 - save0.c |
/////////////////////////////// 8INF854 - ARCHITECTURES PARRALLELES - DEVOIR #3 ////////////////////////////////////////
///////////////////////////// tri tableau MPI - Corentin RAOULT - Adrien Cambillau /////////////////////////////////////
//http://www.cac.cornell.edu/vw/MPIoneSided/exercise.aspx
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <time.h>
#include <limits.h>
#define BLOCK_LOW(id,p,n) ((id)*(n)/(p))
#define BLOCK_HIGH(id,p,n) \
(BLOCK_LOW((id)+1,p,n)-1)
#define BLOCK_SIZE(id,p,n) \
(BLOCK_LOW((id)+1,p,n)-BLOCK_LOW(id,p,n))
#define BLOCK_OWNER(index,p,n) \
(((p)*(index)+1)-1)/(n))
struct tableau
{
int * tab;
int taille;
};
//variable globale sale accessible de partout
MPI_Win win;
MPI_Comm comm;
////////////////////// déclaration des fonctions ////////////////////////////////////////////////////////////////////
int demandeNombre();
void remplirTABrand( struct tableau T);
struct tableau TD_init(int n);
int TD_get(struct tableau T, int i, int *x);
int TD_put(struct tableau T, int i, int *x);
int TD_somme(struct tableau T); // Retourne la somme des éléments de T .
void TD_afficher(struct tableau T,int i, int j); // Affiche dans l’ordre les éléments i (i ≤ j) du tableau T .
void afficherNomMachine();
void triFusionParallele(int * TAB, int n);
void fusion(int * U, int taille_U, int * V, int taille_V , int * T);
void afficherTAB(int* TAB, int n);
void getPartTab(struct tableau T, int debut, int fin);
///////////////////// MAIN ///////////////////////////////////////////////////////////////////////////////////
int main (int argc, char **argv)
{
int n = atoi(argv[1]);
int rank, i,p;
//double time, max_time;
//time = -MPI_Wtime();
//Start up MPI...
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD, &p);
MPI_Group comm_group, group;
comm = MPI_COMM_WORLD;
struct tableau T;
if (rank == 0) {
/* Only rank 0 has a nonzero buffer at start */
T = TD_init(n);
}
else {
T.tab = calloc(n, sizeof(int));//Initialize all buffers to 0
/* Others only retrieve, so these windows can be size 0 */
MPI_Win_create(T.tab,n*sizeof(int)+5,sizeof(int),MPI_INFO_NULL,comm,&win);
}
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
getPartTab(T,BLOCK_LOW(rank-1,4,n),BLOCK_HIGH(rank-1,4,n)+1);
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
if(rank!=0)
{
//#pragma omp parallel
triFusionParallele(T.tab+(rank-1)*(n/4), n/4);
}
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
MPI_Win_fence(MPI_MODE_NOPRECEDE,win);
if(rank!=0){
for(i=BLOCK_LOW(rank-1,4,n);i<BLOCK_HIGH(rank-1,4,n)+1;i++)
{
//printf("%d ",T.tab[i] );
TD_put(T, i, &T.tab[i]);
}
}
MPI_Win_fence(MPI_MODE_NOSUCCEED,win);
getPartTab(T,0,n);
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
if(rank==0 || rank==1)
{
int * U = malloc((n/4+1)*sizeof(int));
int * V = malloc((n/4+1)*sizeof(int));
for(i=0; i<n/4;i++)
{
U[i]=T.tab[i+rank*(n/2)];
V[i]=T.tab[i+(n/4)+rank*(n/2)];
}
//*(U+n/2)=*(V+n/2)=INT_MAX;
fusion(U,n/4,V,n/4,T.tab+rank*(n/2));
//afficherTAB(T.tab, n);
free(U);
free(V);
}
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
MPI_Win_fence(MPI_MODE_NOPRECEDE,win);
if(rank==0 || rank==1)
{
for(i=rank*(n/2);i<(rank+1)*(n/2);i++)
{
TD_put(T, i, &T.tab[i]);
}
}
MPI_Win_fence(MPI_MODE_NOSUCCEED,win);
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
getPartTab(T,0,n);
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
if(rank==0){
int * leftTab = malloc((n/2)*sizeof(int));
int * rightTab = malloc((n/2)*sizeof(int));
for(i=0; i<n/2;i++)
{
leftTab[i]=T.tab[i];
rightTab[i]=T.tab[i+(n/2)];
}
fusion(leftTab, n/2, rightTab, n/2, T.tab);
free(leftTab);
free(rightTab);
}
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
MPI_Win_free(&win);
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
if(rank == 0)
{
TD_afficher(T,0,n);
}
//time += MPI_Wtime();
//MPI_Reduce (&time, &max_time, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
//if (!rank)
// printf ("tri: processus: %d, secondes: %6.2f \n",p, max_time);
MPI_Barrier(MPI_COMM_WORLD);///////////////////////////////barrier///////////////////////////////////////////////////////////////////////////////
free(T.tab);
//Shut down...
MPI_Finalize();
return(0);
}
/////////////////// développement des fonctions /////////////////////////////////////////////////////////////
int demandeNombre()
{
int i; char buf[128] = {0};
//tant que l'entrée n'est pas correcte on la redemande
while(scanf("%d", &i) != 1)
{
scanf("%s", &buf);
printf("Désolé, [%s] n'est pas un nombre, veuillez taper une valeur correcte : ", &buf);
}
return i;
}
void afficherNomMachine()
{
char hostname[256];
if (gethostname(hostname, sizeof(hostname)) == 0)
{
printf("%s\n", hostname);fflush(stdout);
}
else
fprintf(stderr, "La fonction gethostname a echoue.\n");
}
void remplirTABrand(struct tableau T)
{
int i;
srand(time(NULL));
for(i=0;i<T.taille;i++)
T.tab[i] = rand()%T.taille;
}
struct tableau TD_init(int n)
{
struct tableau T;
T.tab = malloc(n*sizeof(int));
T.taille=n;
remplirTABrand(T);
/* Everyone will retrieve from the buffer on root */
MPI_Win_create(T.tab,n*sizeof(int),sizeof(int),MPI_INFO_NULL,comm,&win);
printf("Tableau original\n");fflush(stdout);
TD_afficher(T,0, T.taille);fflush(stdout);
return T;
}
int TD_get(struct tableau T, int i, int *x)
{
if(i < T.taille)
{
MPI_Get(x,1,MPI_INT,0,i,1,MPI_INT,win);
return 1;
}
else
return 0;
}
int TD_put(struct tableau T, int i, int *x)
{
if(i < T.taille)
{
MPI_Put(x,1,MPI_INT,0,i,1,MPI_INT,win);
return 1;
}
else
return 0;
}
int TD_somme(struct tableau T)
{
int i;
int somme=0;
for(i=0;i<T.taille;i++)
somme+=T.tab[i];
return somme;
}
void TD_afficher(struct tableau T,int i, int j)
{
int c;
printf("tab: {");
for(c=i;c<j;c++)
{
printf(" %d ", T.tab[c]);
}
printf("}\n");
}
void triFusionParallele(int * TAB, int n)
{
int i;
int * U = malloc((n/2)*sizeof(int));
int * V = malloc((n/2)*sizeof(int));
for(i=0; i<n/2;i++)
{
U[i]=TAB[i];
V[i]=TAB[i+(n/2)];
}
if(n>=2)//si n==1 pas besoin de trier les tableaux
{
//#pragma omp single nowait
//{
//#pragma omp task
triFusionParallele(U,n/2);
//#pragma omp task
triFusionParallele(V,n/2);
//#pragma omp taskwait
fusion(U,n/2,V,n/2,TAB);
//}
}
free(U);
free(V);
}
void fusion(int * U, int taille_U, int * V, int taille_V , int * T)
{
int i=0,j=0;
int k;
*(U+taille_U)=INT_MAX;
*(V+taille_V)=INT_MAX;
for(k=0; k<(taille_U+taille_V);k++)
{
if (U[i]<V[j])
T[k]=U[i++];
else
T[k]=V[j++];
}
}
void afficherTAB(int* TAB, int n)
{
int j;
printf("TAB : { ");
for(j = 0; j < n; j++)
printf(" [%d] ",TAB[j]);
printf(" }\n");
}
void getPartTab(struct tableau T, int debut, int fin)
{
MPI_Win_fence(MPI_MODE_NOPRECEDE,win);
int i;
for(i=debut;i<fin;i++)
TD_get(T, i, &T.tab[i]);
MPI_Win_fence(MPI_MODE_NOSUCCEED,win);
}
|
raytracer.h | #pragma once
#include "resource.h"
#include <linalg.h>
#include <memory>
#include <omp.h>
#include <random>
#include <time.h>
using namespace linalg::aliases;
namespace cg::renderer
{
struct ray
{
ray(float3 position, float3 direction) : position(position)
{
this->direction = normalize(direction);
}
float3 position;
float3 direction;
};
struct payload
{
float t;
float3 bary;
cg::color color;
};
template<typename VB>
struct triangle
{
triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c);
float3 a;
float3 b;
float3 c;
float3 ba;
float3 ca;
float3 na;
float3 nb;
float3 nc;
float3 ambient;
float3 diffuse;
float3 emissive;
};
template<typename VB>
inline triangle<VB>::triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c)
{
a = float3{ vertex_a.x, vertex_a.y, vertex_a.z };
b = float3{ vertex_b.x, vertex_b.y, vertex_b.z };
c = float3{ vertex_c.x, vertex_c.y, vertex_c.z };
ba = b - a;
ca = c - a;
na = float3{ vertex_a.nx, vertex_a.ny, vertex_a.nz };
nb = float3{ vertex_b.nx, vertex_b.ny, vertex_b.nz };
nc = float3{ vertex_c.nx, vertex_c.ny, vertex_c.nz };
ambient = {
vertex_a.ambient_r,
vertex_a.ambient_g,
vertex_a.ambient_b,
};
diffuse = {
vertex_a.diffuse_r,
vertex_a.diffuse_g,
vertex_a.diffuse_b,
};
emissive = {
vertex_a.emissive_r,
vertex_a.emissive_g,
vertex_a.emissive_b,
};
}
template<typename VB>
class aabb
{
public:
void add_triangle(const triangle<VB> triangle);
const std::vector<triangle<VB>>& get_traingles() const;
bool aabb_test(const ray& ray) const;
protected:
std::vector<triangle<VB>> triangles;
float3 aabb_min;
float3 aabb_max;
};
struct light
{
float3 position;
float3 color;
};
template<typename VB, typename RT>
class raytracer
{
public:
raytracer(){};
~raytracer(){};
void set_render_target(std::shared_ptr<resource<RT>> in_render_target);
void clear_render_target(const RT& in_clear_value);
void set_viewport(size_t in_width, size_t in_height);
void set_per_shape_vertex_buffer(
std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer);
void build_acceleration_structure();
std::vector<aabb<VB>> acceleration_structures;
void ray_generation(float3 position, float3 direction, float3 right, float3 up);
payload trace_ray(const ray& ray, size_t depth, float max_t = 1000.f, float min_t = 0.001f) const;
payload intersection_shader(const triangle<VB>& triangle, const ray& ray) const;
std::function<payload(const ray& ray)> miss_shader = nullptr;
std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> closest_hit_shader =
nullptr;
std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> any_hit_shader =
nullptr;
protected:
std::shared_ptr<cg::resource<RT>> render_target;
std::vector<std::shared_ptr<cg::resource<VB>>> per_shape_vertex_buffer;
float get_random(const int thread_num, float range = 0.1f) const;
size_t width = 1920;
size_t height = 1080;
};
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_render_target(std::shared_ptr<resource<RT>> in_render_target)
{
render_target = in_render_target;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::clear_render_target(const RT& in_clear_value)
{
for (size_t i = 0; i < render_target->get_number_of_elements(); i++)
{
render_target->item(i) = in_clear_value;
}
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_per_shape_vertex_buffer(
std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer)
{
per_shape_vertex_buffer = in_per_shape_vertex_buffer;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::build_acceleration_structure()
{
for (auto& vertex_buffer : per_shape_vertex_buffer)
{
size_t vertex_id = 0;
aabb<VB> aabb;
while (vertex_id < vertex_buffer->get_number_of_elements())
{
triangle<VB> triangle(
vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++),
vertex_buffer->item(vertex_id++));
aabb.add_triangle(triangle);
}
acceleration_structures.push_back(aabb);
}
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::set_viewport(size_t in_width, size_t in_height)
{
width = in_width;
height = in_height;
}
template<typename VB, typename RT>
inline void raytracer<VB, RT>::ray_generation(
float3 position, float3 direction, float3 right, float3 up)
{
for (int x = 0; x < width; x++)
{
#pragma omp parallel for
for (int y = 0; y < height; y++)
{
// from [0, width-1] to [-1, 1]
float u = 2.f * x / static_cast<float>(width - 1) - 1.f;
u *= static_cast<float>(width) / static_cast<float>(height);
float v = 2.f * y / static_cast<float>(height - 1) - 1.f;
float3 ray_direction = direction + u * right - v * up;
ray ray(position, ray_direction);
payload payload = trace_ray(ray, 1);
render_target->item(x, y) = RT::from_color(payload.color);
}
}
}
template<typename VB, typename RT>
inline payload
raytracer<VB, RT>::trace_ray(const ray& ray, size_t depth, float max_t, float min_t) const
{
if (depth == 0)
{
return miss_shader(ray);
}
depth--;
payload closest_hit_payload = {};
closest_hit_payload.t = max_t;
const triangle<VB>* closest_triangle = nullptr;
for (auto& aabb : acceleration_structures)
{
if (!aabb.aabb_test(ray))
continue;
for (auto& triangle : aabb.get_traingles())
{
payload payload = intersection_shader(triangle, ray);
if (payload.t > min_t && payload.t < closest_hit_payload.t)
{
closest_hit_payload = payload;
closest_triangle = ▵
if (any_hit_shader)
return any_hit_shader(ray, payload, triangle);
}
}
}
if (closest_hit_payload.t < max_t)
{
if (closest_hit_shader)
{
return closest_hit_shader(ray, closest_hit_payload, *closest_triangle);
}
}
return miss_shader(ray);
}
template<typename VB, typename RT>
inline payload
raytracer<VB, RT>::intersection_shader(const triangle<VB>& triangle, const ray& ray) const
{
payload payload{};
payload.t = -1.f;
float3 pvec = cross(ray.direction, triangle.ca);
float det = dot(triangle.ba, pvec);
const float eps = 1e-8f;
if (abs(det) < eps)
{
return payload;
}
float inv_det = 1.f / det;
float3 tvec = ray.position - triangle.a;
float u = dot(tvec, pvec) * inv_det;
if (u < 0.f || u > 1.f)
{
return payload;
}
float3 qvec = cross(tvec, triangle.ba);
float v = dot(ray.direction, qvec) * inv_det;
if (v < 0.f || (u + v) > 1.f)
{
return payload;
}
payload.t = dot(triangle.ca, qvec) * inv_det;
payload.bary = float3{ 1.f - u - v, u, v };
return payload;
}
template<typename VB, typename RT>
inline float raytracer<VB, RT>::get_random(const int thread_num, const float range) const
{
static std::default_random_engine generator(thread_num);
static std::normal_distribution<float> distribution(0.f, range);
return distribution(generator);
}
template<typename VB>
inline void aabb<VB>::add_triangle(const triangle<VB> triangle)
{
if (triangles.empty())
aabb_max = aabb_min = triangle.a;
triangles.push_back(triangle);
aabb_max = max(triangle.a, aabb_max);
aabb_max = max(triangle.b, aabb_max);
aabb_max = max(triangle.c, aabb_max);
aabb_min = min(triangle.a, aabb_min);
aabb_min = min(triangle.b, aabb_min);
aabb_min = min(triangle.c, aabb_min);
}
template<typename VB>
inline const std::vector<triangle<VB>>& aabb<VB>::get_traingles() const
{
return triangles;
}
template<typename VB>
inline bool aabb<VB>::aabb_test(const ray& ray) const
{
float3 inv_ray_direction = float3(1.f) / ray.direction;
float3 t0 = (aabb_max - ray.position) * inv_ray_direction;
float3 t1 = (aabb_min - ray.position) * inv_ray_direction;
float3 tmin = min(t0, t1);
float3 tmax = max(t0, t1);
return maxelem(tmin) <= minelem(tmax);
}
} // namespace cg::renderer
|
memory_bench.c | #include "config.h"
#include <unistd.h>
#include <stdlib.h>
#include <CUnit/Basic.h>
#include <CUnit/Console.h>
#include <sys/time.h>
#include "mkl.h"
static double get_time() {
struct timeval t;
gettimeofday(&t, NULL);
return (double)t.tv_sec + t.tv_usec * 1e-6;
}
static void* host_malloc(size_t size) { return malloc(size); }
static void host_free(void* p) { if (p) free(p); }
static void* gpu_malloc(size_t size) { return mkl_malloc(size, 4096); }
static void gpu_free(void* p) { if (p) mkl_free(p); }
/* invalidate_cpu_l2c - may invalidate CPU-unified L2C */
static void invalidate_cpu_l2c()
{
int i;
const int NLOOPS = 10;
size_t j;
const size_t SIZE = 16 * 1024 * 1024;
int * volatile p = host_malloc(SIZE);
const size_t LEN = SIZE / sizeof(*p);
for (i = 0; i < NLOOPS; i ++) {
p[LEN - 1] = p[0];
for (j = 0; j < LEN - 1; j ++)
p[j] = p[j + 1];
}
host_free(p);
}
static float rand_float_in_range(float from, float to) {
return ((float)rand() / RAND_MAX) * (to - from) + from;
}
const size_t N = 1024 * 1024;
static float* gpu_src_memory = NULL;
static float* host_src_memory = NULL;
static float expected = 0;
static int setup_suite() {
srand(0xDEADBEEF);
gpu_src_memory = (float*)gpu_malloc(N * sizeof(float));
size_t i = 0;
#pragma omp parallel for private(i)
for (i = 0; i < N; ++i) gpu_src_memory[i] = rand_float_in_range(-1.0, 1.0);
host_src_memory = (float*)host_malloc(N*sizeof(float));
memcpy(host_src_memory, gpu_src_memory, N*sizeof(float));
for (i = 0; i < N; ++i)
expected += host_src_memory[i];
return 0;
}
static int teardown_suite() {
gpu_free(gpu_src_memory);
host_free(host_src_memory);
expected = 0;
return 0;
}
#define TEST_MEMCPY(FROM, TO) \
static void test_memcpy_##FROM##_to_##TO() { \
float* TO##_dst_memory = (float*)TO##_malloc(N*sizeof(float)); \
invalidate_cpu_l2c(); \
double start = get_time(); \
memcpy(TO##_dst_memory, FROM##_src_memory, N*sizeof(float)); \
double end = get_time(); \
float actual = 0; \
size_t i = 0; \
for (i = 0; i < N; ++i) { \
actual += TO##_dst_memory[i]; \
} \
printf("\nmemcpy(4MB): %lf sec (%lf)\n", \
end - start, \
N * sizeof(float) / (end - start) / 1024 / 1024 \
); \
CU_ASSERT_DOUBLE_EQUAL(actual, expected, 0.001); \
TO##_free(TO##_dst_memory); \
}
TEST_MEMCPY(host, host);
TEST_MEMCPY(host, gpu);
TEST_MEMCPY(gpu, host);
TEST_MEMCPY(gpu, gpu);
static void suite_memcpy() {
CU_pSuite suite = CU_add_suite(
"memcpy",
setup_suite,
teardown_suite
);
CU_add_test(suite, "Host -> Host", test_memcpy_host_to_host);
CU_add_test(suite, "Host -> GPU", test_memcpy_host_to_gpu);
CU_add_test(suite, "GPU -> Host", test_memcpy_gpu_to_host);
CU_add_test(suite, "GPU -> GPU", test_memcpy_gpu_to_gpu);
}
#define TEST_MEMSET(TO) \
static void test_memset_to_##TO() { \
float* TO##_dst_memory = (float*)TO##_malloc(N*sizeof(float)); \
invalidate_cpu_l2c(); \
double start = get_time(); \
memset(TO##_dst_memory, 0, N*sizeof(float)); \
double end = get_time(); \
float actual = 0; \
size_t i = 0; \
for (i = 0; i < N; ++i) { \
actual += TO##_dst_memory[i]; \
} \
printf("\nmemset(4MB): %lf sec (%lf)\n", \
end - start, \
N * sizeof(float) / (end - start) / 1024 / 1024 \
); \
CU_ASSERT_DOUBLE_EQUAL(actual, 0, 0.001); \
TO##_free(TO##_dst_memory); \
}
TEST_MEMSET(host);
TEST_MEMSET(gpu);
static void suite_memset() {
CU_pSuite suite = CU_add_suite(
"memset",
setup_suite,
teardown_suite
);
CU_add_test(suite, "0 -> Host", test_memset_to_host);
CU_add_test(suite, "0 -> GPU", test_memset_to_gpu);
}
#define TEST_SUMALL(FROM) \
static void test_sumall_##FROM() { \
invalidate_cpu_l2c(); \
double start = get_time(); \
float actual = 0; \
size_t i = 0; \
for (i = 0; i < N; ++i) { \
actual += FROM##_src_memory[i]; \
} \
double end = get_time(); \
printf("\nsumall(4MB): %lf sec (%lf)\n", \
end - start, \
N * sizeof(float) / (end - start) / 1024 / 1024 \
); \
CU_ASSERT_DOUBLE_EQUAL(actual, expected, 0.001); \
}
TEST_SUMALL(host);
TEST_SUMALL(gpu);
static void suite_sumall() {
CU_pSuite suite = CU_add_suite(
"sumall",
setup_suite,
teardown_suite
);
CU_add_test(suite, "Host -> x", test_sumall_host);
CU_add_test(suite, "GPU -> x", test_sumall_gpu);
}
int main() {
CU_initialize_registry();
suite_memcpy();
suite_memset();
suite_sumall();
isatty(fileno(stdout)) ? CU_console_run_tests() : CU_basic_run_tests();
const unsigned int result = CU_get_number_of_failures();
CU_cleanup_registry();
return (result ? 1 : 0);
}
|
pi-v13.c | /*
* Compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x)
* between 0 and 1.
*
* parallel version using OpenMP
*/
#include <stdio.h>
#include <stdlib.h>
#include <omp.h> /* OpenMP */
#if _DEBUG_
#define _DEBUG_ 1
#else
#define _DEBUG_ 0
#include "extrae_user_events.h"
#define PROGRAM 1000
#define PI_COMPUTATION 1
#define END 0
#endif
int main(int argc, char *argv[]) {
double x, sum=0.0, pi=0.0;
#if _DEBUG_
double start,end;
#endif
int i;
const char Usage[] = "Usage: pi <num_steps> (try 1000000000)\n";
if (argc < 2) {
fprintf(stderr, Usage);
exit(1);
}
int num_steps = atoi(argv[1]);
double step = 1.0/(double) num_steps;
#if _DEBUG_
start= omp_get_wtime();
#else
Extrae_event (PROGRAM, PI_COMPUTATION);
#endif
/* do computation -- using just two threads */
// WARNING : correct code
#pragma omp parallel private(i,x) reduction(+:sum)
{
#if _DEBUG_
int id = omp_get_thread_num();
#endif
#pragma omp for schedule(static, num_steps/4)
for (i=0; i < num_steps/2; i++) {
x = (i+0.5)*step;
sum += 4.0/(1.0+x*x);
#if _DEBUG_
printf("thread id:%d it:%d\n",id,i);
#endif
}
#pragma omp for schedule(static, num_steps/4)
for (i=num_steps/2; i < num_steps; i++) {
x = (i+0.5)*step;
sum += 4.0/(1.0+x*x);
#if _DEBUG_
printf("thread id:%d it:%d\n",id,i);
#endif
}
}
pi = step * sum;
#if _DEBUG_
end = omp_get_wtime();
printf("Wall clock execution time = %.9f seconds\n", end-start);
#else
Extrae_event (PROGRAM, END);
#endif
/* print results */
printf("Value of pi = %12.10f\n", pi);
return EXIT_SUCCESS;
}
|
GB_unop__identity_fp64_uint32.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__identity_fp64_uint32
// op(A') function: GB_unop_tran__identity_fp64_uint32
// C type: double
// A type: uint32_t
// cast: double cij = (double) aij
// unaryop: cij = aij
#define GB_ATYPE \
uint32_t
#define GB_CTYPE \
double
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
double z = (double) aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
double z = (double) aij ; \
Cx [pC] = z ; \
}
// true if operator is the identity op with no typecasting
#define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \
0
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FP64 || GxB_NO_UINT32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__identity_fp64_uint32
(
double *Cx, // Cx and Ax may be aliased
const uint32_t *Ax,
const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST )
GB_memcpy (Cx, Ax, anz * sizeof (uint32_t), nthreads) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint32_t aij = Ax [p] ;
double z = (double) aij ;
Cx [p] = z ;
}
#endif
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
uint32_t aij = Ax [p] ;
double z = (double) aij ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__identity_fp64_uint32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Workspaces,
const int64_t *GB_RESTRICT A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
NAS_FT.c | //---------------------------------------------------------------------
// program FT
//---------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#if !defined(CLASS_W) && !defined(CLASS_S) && !defined(CLASS_A) && !defined(CLASS_B) && !defined(CLASS_C) && !defined(CLASS_D) && !defined(CLASS_E)
# define CLASS_W
#endif
//----------
// Class S:
//----------
#ifdef CLASS_S
# define NX 64
# define NY 64
# define NZ 64
# define MAXDIM 64
# define NITER_DEFAULT 6
# define NXP 65
# define NYP 64
# define NTOTAL 262144
# define NTOTALP 266240
#endif
//----------
// Class W:
//----------
#ifdef CLASS_W
# define NX 128
# define NY 128
# define NZ 32
# define MAXDIM 128
# define NITER_DEFAULT 6
# define NXP 129
# define NYP 128
# define NTOTAL 524288
# define NTOTALP 528384
#endif
//----------
// Class A:
//----------
#ifdef CLASS_A
# define NX 256
# define NY 256
# define NZ 128
# define MAXDIM 256
# define NITER_DEFAULT 6
# define NXP 257
# define NYP 256
# define NTOTAL 8388608
# define NTOTALP 8421376
#endif
//----------
// Class B:
//----------
#ifdef CLASS_B
# define NX 512
# define NY 256
# define NZ 256
# define MAXDIM 512
# define NITER_DEFAULT 20
# define NXP 513
# define NYP 256
# define NTOTAL 33554432
# define NTOTALP 33619968
#endif
//----------
// Class C:
//----------
#ifdef CLASS_C
# define NX 512
# define NY 512
# define NZ 512
# define MAXDIM 512
# define NITER_DEFAULT 20
# define NXP 513
# define NYP 512
# define NTOTAL 134217728
# define NTOTALP 134479872
#endif
//----------
// Class D:
//----------
#ifdef CLASS_D
# define NX 2048
# define NY 1024
# define NZ 1024
# define MAXDIM 2048
# define NITER_DEFAULT 25
# define NXP 2049
# define NYP 1024
# define NTOTAL 2147483648
# define NTOTALP 2148532224
#endif
//----------
// Class E:
//----------
#ifdef CLASS_E
# define NX 4096
# define NY 2048
# define NZ 2048
# define MAXDIM 4096
# define NITER_DEFAULT 25
# define NXP 4097
# define NYP 2048
# define NTOTAL 17179869184
# define NTOTALP 17184063488
#endif
typedef struct
{
double real;
double imag;
} dcomplex;
#define min(x,y) ((x) < (y) ? (x) : (y))
#define max(x,y) ((x) > (y) ? (x) : (y))
#define FFTBLOCK_DEFAULT 16
#define FFTBLOCKPAD_DEFAULT 18
#define CACHESIZE 8192
#define BLOCKMAX 32
#define SEED 314159265.0
#define A 1220703125.0
#define PI 3.141592653589793238
#define ALPHA 1.0e-6
/* common /timerscomm/ */
dcomplex dcmplx_div(dcomplex z1, dcomplex z2)
{
double a = z1.real;
double b = z1.imag;
double c = z2.real;
double d = z2.imag;
double divisor = c * c + d * d;
double real = (a * c + b * d) / divisor;
double imag = (b * c - a * d) / divisor;
dcomplex result = (dcomplex) {real, imag};
return result;
}
#define dcmplx(r,i) (dcomplex){r, i}
#define dcmplx_add(a,b) (dcomplex){(a).real+(b).real, (a).imag+(b).imag}
#define dcmplx_sub(a,b) (dcomplex){(a).real-(b).real, (a).imag-(b).imag}
#define dcmplx_mul(a,b) (dcomplex){((a).real*(b).real)-((a).imag*(b).imag),\
((a).real*(b).imag)+((a).imag*(b).real)}
#define dcmplx_mul2(a,b) (dcomplex){(a).real*(b), (a).imag*(b)}
#define dcmplx_div2(a,b) (dcomplex){(a).real/(b), (a).imag/(b)}
#define dcmplx_abs(x) sqrt(((x).real*(x).real) + ((x).imag*(x).imag))
#define dconjg(x) (dcomplex){(x).real, -1.0*(x).imag}
/* common /blockinfo/ */
int fftblock;
/* common /workarr/ */
dcomplex plane[(BLOCKMAX + 1)*MAXDIM];
dcomplex scr[MAXDIM][BLOCKMAX + 1];
// for checksum data
/* common /sumcomm/ */
dcomplex sums[NITER_DEFAULT + 1];
/* common /mainarrays/ */
double twiddle[NZ][NY][NX + 1];
dcomplex xnt[NZ][NY][NX + 1];
dcomplex y[NZ][NY][NX + 1];
void appft(int niter, double *total_time, int *verified);
void CompExp(int n, dcomplex exponent[n]);
int ilog2(int n);
void CalculateChecksum(dcomplex *csum, int iterN, int d1, int d2, int d3,
dcomplex u[d3][d2][d1 + 1]);
void compute_initial_conditions(int d1, int d2, int d3,
dcomplex u0[d3][d2][d1 + 1]);
void evolve(int nx, int ny, int nz,
dcomplex x[nz][ny][nx + 1], dcomplex y[nz][ny][nx + 1],
double twiddle[nz][ny][nx + 1]);
void fftXYZ(int sign, int n1, int n2, int n3,
dcomplex x[n3][n2][n1 + 1], dcomplex xout[(n1 + 1)*n2 * n3],
dcomplex exp1[n1], dcomplex exp2[n2], dcomplex exp3[n3]);
void verify(int n1, int n2, int n3, int nt, dcomplex cksum[nt + 1],
int *verified);
double randlc( double *x, double a );
void vranlc( int n, double *x, double a, double y[] );
char getclass();
void print_results(char *name, char class, int n1, int n2, int n3, int niter,
double t, double mops, char *optype, int verified);
double start[64], elapsed[64];
double elapsed_time( void );
void timer_clear( int n );
void timer_start( int n );
void timer_stop( int n );
double timer_read( int n );
void wtime(double *t);
int main(int argc, char *argv[])
{
int niter;
char Class;
double total_time, mflops;
int verified;
niter = NITER_DEFAULT;
printf("\n\n NAS Parallel Benchmarks (NPB3.3-SER-C) - FT Benchmark\n\n");
printf(" Size : %4dx%4dx%4d\n", NX, NY, NZ);
printf(" Iterations : %10d\n", niter);
printf("\n");
Class = getclass();
appft(niter, &total_time, &verified);
if (total_time != 0.0)
{
mflops = 1.0e-6 * (double)NTOTAL *
(14.8157 + 7.19641 * log((double)NTOTAL)
+ (5.23518 + 7.21113 * log((double)NTOTAL)) * niter)
/ total_time;
}
else
{
mflops = 0.0;
}
print_results("FT", Class, NX, NY, NZ, niter,
total_time, mflops, " floating point", verified);
int exitValue = verified ? 0 : 1;
return exitValue;
}
char getclass()
{
if ((NX == 64) && (NY == 64) &&
(NZ == 64) && (NITER_DEFAULT == 6))
{
return 'S';
}
else if ((NX == 128) && (NY == 128) &&
(NZ == 32) && (NITER_DEFAULT == 6))
{
return 'W';
}
else if ((NX == 256) && (NY == 256) &&
(NZ == 128) && (NITER_DEFAULT == 6))
{
return 'A';
}
else if ((NX == 512) && (NY == 256) &&
(NZ == 256) && (NITER_DEFAULT == 20))
{
return 'B';
}
else if ((NX == 512) && (NY == 512) &&
(NZ == 512) && (NITER_DEFAULT == 20))
{
return 'C';
}
else if ((NX == 2048) && (NY == 1024) &&
(NZ == 1024) && (NITER_DEFAULT == 25))
{
return 'D';
}
else
{
return 'U';
}
}
void appft(int niter, double *total_time, int *verified)
{
int i, j, k, kt, n12, n22, n32, ii, jj, kk, ii2, ik2;
double ap;
dcomplex exp1[NX], exp2[NY], exp3[NZ];
for (i = 1; i <= 15; i++)
{
timer_clear(i);
}
timer_start(2);
compute_initial_conditions(NX, NY, NZ, xnt);
CompExp(NX, exp1);
CompExp(NY, exp2);
CompExp(NZ, exp3);
fftXYZ(1, NX, NY, NZ, xnt, (dcomplex *)y, exp1, exp2, exp3);
timer_stop(2);
timer_start(1);
n12 = NX / 2;
n22 = NY / 2;
n32 = NZ / 2;
ap = -4.0 * ALPHA * (PI * PI);
for (i = 0; i < NZ; i++)
{
ii = i - (i / n32) * NZ;
ii2 = ii * ii;
#pragma omp parallel for default(shared) private(k, j, kk, ik2, jj) firstprivate(n22, ii2, n12, ap, i)
for (k = 0; k < NY; k++)
{
kk = k - (k / n22) * NY;
ik2 = ii2 + kk * kk;
for (j = 0; j < NX; j++)
{
jj = j - (j / n12) * NX;
twiddle[i][k][j] = exp(ap * (double)(jj * jj + ik2));
}
}
}
compute_initial_conditions(NX, NY, NZ, xnt);
fftXYZ(1, NX, NY, NZ, xnt, (dcomplex *)y, exp1, exp2, exp3);
for (kt = 1; kt <= niter; kt++)
{
evolve(NX, NY, NZ, xnt, y, twiddle);
fftXYZ(-1, NX, NY, NZ, xnt, (dcomplex *)xnt, exp1, exp2, exp3);
CalculateChecksum(&sums[kt], kt, NX, NY, NZ, xnt);
}
// Verification test.
verify(NX, NY, NZ, niter, sums, verified);
timer_stop(1);
*total_time = timer_read(1);
}
//---------------------------------------------------------------------
// compute the roots-of-unity array that will be used for subsequent FFTs.
//---------------------------------------------------------------------
void CompExp(int n, dcomplex exponent[n])
{
int m, nu, ku, i, j, ln;
double t, ti;
const double pi = 3.141592653589793238;
nu = n;
m = ilog2(n);
exponent[0] = dcmplx(m, 0.0);
ku = 2;
ln = 1;
for (j = 1; j <= m; j++)
{
t = pi / ln;
#pragma omp parallel for default(shared) private(i, ti) firstprivate(ln, t, ku)
for (i = 0; i <= ln - 1; i++)
{
ti = i * t;
exponent[i + ku - 1] = dcmplx(cos(ti), sin(ti));
}
ku = ku + ln;
ln = 2 * ln;
}
}
int ilog2(int n)
{
int nn, lg;
if (n == 1) return 0;
lg = 1;
nn = 2;
while (nn < n)
{
nn = nn * 2;
lg = lg + 1;
}
return lg;
}
//---------------------------------------------------------------------
// compute a^exponent mod 2^46
//---------------------------------------------------------------------
double ipow46(double a, int exponent)
{
double result, dummy, q, r;
int n, n2;
//---------------------------------------------------------------------
// Use
// a^n = a^(n/2)*a^(n/2) if n even else
// a^n = a*a^(n-1) if n odd
//---------------------------------------------------------------------
result = 1;
if (exponent == 0) return result;
q = a;
r = 1;
n = exponent;
while (n > 1)
{
n2 = n / 2;
if (n2 * 2 == n)
{
dummy = randlc(&q, q);
n = n2;
}
else
{
dummy = randlc(&r, q);
n = n - 1;
}
}
dummy = randlc(&r, q);
result = r;
return result;
}
void CalculateChecksum(dcomplex *csum, int iterN, int d1, int d2, int d3,
dcomplex u[d3][d2][d1 + 1])
{
int i, i1, ii, ji, ki;
dcomplex csum_temp = dcmplx(0.0, 0.0);
for (i = 1; i <= 1024; i++)
{
i1 = i;
ii = i1 % d1;
ji = 3 * i1 % d2;
ki = 5 * i1 % d3;
csum_temp = dcmplx_add(csum_temp, u[ki][ji][ii]);
}
csum_temp = dcmplx_div2(csum_temp, (double)(d1 * d2 * d3));
printf(" T =%5d Checksum =%22.12E%22.12E\n",
iterN, csum_temp.real, csum_temp.imag);
*csum = csum_temp;
}
void compute_initial_conditions(int d1, int d2, int d3,
dcomplex u0[d3][d2][d1 + 1])
{
dcomplex tmp[MAXDIM];
double x0, start, an, dummy;
double RanStarts[MAXDIM];
int i, j, k;
const double seed = 314159265.0;
const double a = 1220703125.0;
start = seed;
//---------------------------------------------------------------------
// Jump to the starting element for our first plane.
//---------------------------------------------------------------------
an = ipow46(a, 0);
dummy = randlc(&start, an);
an = ipow46(a, 2 * d1 * d2);
//---------------------------------------------------------------------
// Go through by z planes filling in one square at a time.
//---------------------------------------------------------------------
RanStarts[0] = start;
for (k = 1; k < d3; k++)
{
dummy = randlc(&start, an);
RanStarts[k] = start;
}
for (k = 0; k < d3; k++)
{
x0 = RanStarts[k];
for (j = 0; j < d2; j++)
{
vranlc(2 * d1, &x0, a, (double *)tmp);
#pragma omp parallel for default(shared) private(i) firstprivate(d1, k, j, tmp)
for (i = 0; i < d1; i++)
{
u0[k][j][i] = tmp[i];
}
}
}
}
void evolve(int nx, int ny, int nz,
dcomplex x[nz][ny][nx + 1], dcomplex y[nz][ny][nx + 1],
double twiddle[nz][ny][nx + 1])
{
int i, j, k;
for (i = 0; i < nz; i++)
{
for (k = 0; k < ny; k++)
{
for (j = 0; j < nx; j++)
{
y[i][k][j] = dcmplx_mul2(y[i][k][j], twiddle[i][k][j]);
x[i][k][j] = y[i][k][j];
}
}
}
}
//---------------------------------------------------------------------
// Computes NY N-point complex-to-complex FFTs of X using an algorithm due
// to Swarztrauber. X is both the input and the output array, while Y is a
// scratch array. It is assumed that N = 2^M. Before calling
// Swarztrauber to
// perform FFTs
//---------------------------------------------------------------------
void Swarztrauber(int is, int m, int vlen, int n, int xd1,
void *ox, dcomplex exponent[n])
{
dcomplex (*x)[xd1] = (dcomplex (*)[xd1])ox;
int i, j, l;
dcomplex u1, x11, x21;
int k, n1, li, lj, lk, ku, i11, i12, i21, i22;
//---------------------------------------------------------------------
// Perform one variant of the Stockham FFT.
//---------------------------------------------------------------------
n1 = n / 2;
lj = 1;
li = 1 << m;
for (l = 1; l <= m; l += 2)
{
lk = lj;
lj = 2 * lk;
li = li / 2;
ku = li;
for (i = 0; i <= li - 1; i++)
{
i11 = i * lk;
i12 = i11 + n1;
i21 = i * lj;
i22 = i21 + lk;
if (is >= 1)
{
u1 = exponent[ku + i];
}
else
{
u1 = dconjg(exponent[ku + i]);
}
for (k = 0; k <= lk - 1; k++)
{
#pragma omp parallel for default(shared) private(j, x11, x21) firstprivate(vlen, i11, k, i12, i21, u1, i22, x)
for (j = 0; j < vlen; j++)
{
x11 = x[i11 + k][j];
x21 = x[i12 + k][j];
scr[i21 + k][j] = dcmplx_add(x11, x21);
scr[i22 + k][j] = dcmplx_mul(u1, dcmplx_sub(x11, x21));
}
}
}
if (l == m)
{
#pragma omp parallel for default(shared) private(k, j) firstprivate(n, vlen, scr)
for (k = 0; k < n; k++)
{
for (j = 0; j < vlen; j++)
{
x[k][j] = scr[k][j];
}
}
}
else
{
lk = lj;
lj = 2 * lk;
li = li / 2;
ku = li;
for (i = 0; i <= li - 1; i++)
{
i11 = i * lk;
i12 = i11 + n1;
i21 = i * lj;
i22 = i21 + lk;
if (is >= 1)
{
u1 = exponent[ku + i];
}
else
{
u1 = dconjg(exponent[ku + i]);
}
for (k = 0; k <= lk - 1; k++)
{
#pragma omp parallel for default(shared) private(j, x11, x21) firstprivate(vlen, i11, k, i12, i21, u1, i22, scr)
for (j = 0; j < vlen; j++)
{
x11 = scr[i11 + k][j];
x21 = scr[i12 + k][j];
x[i21 + k][j] = dcmplx_add(x11, x21);
x[i22 + k][j] = dcmplx_mul(u1, dcmplx_sub(x11, x21));
}
}
}
}
}
}
void fftXYZ(int sign, int n1, int n2, int n3,
dcomplex x[n3][n2][n1 + 1], dcomplex xout[(n1 + 1)*n2 * n3],
dcomplex exp1[n1], dcomplex exp2[n2], dcomplex exp3[n3])
{
int i, j, k, log;
int bls, ble;
int len;
int blkp;
fftblock = CACHESIZE / n1;
if (fftblock >= BLOCKMAX) fftblock = BLOCKMAX;
blkp = fftblock + 1;
log = ilog2(n1);
for (k = 0; k < n3; k++)
{
for (bls = 0; bls < n2; bls += fftblock)
{
ble = bls + fftblock - 1;
if (ble > n2) ble = n2 - 1;
len = ble - bls + 1;
#pragma omp parallel for default(shared) private(j, i) firstprivate(bls, ble, n1, blkp, k, x)
for (j = bls; j <= ble; j++)
{
for (i = 0; i < n1; i++)
{
plane[j - bls + blkp * i] = x[k][j][i];
}
}
Swarztrauber(sign, log, len, n1, blkp, plane, exp1);
#pragma omp parallel for default(shared) private(j, i) firstprivate(bls, ble, n1, blkp, k, plane)
for (j = bls; j <= ble; j++)
{
for (i = 0; i < n1; i++)
{
x[k][j][i] = plane[j - bls + blkp * i];
}
}
}
}
fftblock = CACHESIZE / n2;
if (fftblock >= BLOCKMAX) fftblock = BLOCKMAX;
blkp = fftblock + 1;
log = ilog2(n2);
for (k = 0; k < n3; k++)
{
for (bls = 0; bls < n1; bls += fftblock)
{
ble = bls + fftblock - 1;
if (ble > n1) ble = n1 - 1;
len = ble - bls + 1;
Swarztrauber(sign, log, len, n2, n1 + 1, &x[k][0][bls], exp2);
}
}
fftblock = CACHESIZE / n3;
if (fftblock >= BLOCKMAX) fftblock = BLOCKMAX;
blkp = fftblock + 1;
log = ilog2(n3);
for (k = 0; k < n2; k++)
{
for (bls = 0; bls < n1; bls += fftblock)
{
ble = bls + fftblock - 1;
if (ble > n1) ble = n1 - 1;
len = ble - bls + 1;
#pragma omp parallel for default(shared) private(i, j) firstprivate(n3, bls, ble, blkp, k, x)
for (i = 0; i < n3; i++)
{
for (j = bls; j <= ble; j++)
{
plane[j - bls + blkp * i] = x[i][k][j];
}
}
Swarztrauber(sign, log, len, n3, blkp, plane, exp3);
#pragma omp parallel for default(shared) private(i, j) firstprivate(n3, bls, ble, n2, n1, k, blkp, plane)
for (i = 0; i <= n3 - 1; i++)
{
for (j = bls; j <= ble; j++)
{
xout[j + (n1 + 1) * (k + n2 * i)] = plane[j - bls + blkp * i];
}
}
}
}
}
// FT verification routine.
void verify(int n1, int n2, int n3, int nt, dcomplex cksum[nt + 1],
int *verified)
{
// Local variables.
int kt;
dcomplex cexpd[25 + 1];
double epsilon, err;
// Initialize tolerance level and success flag.
epsilon = 1.0e-12;
*verified = 1;
if ((n1 == 64) && (n2 == 64) && (n3 == 64) && (nt == 6))
{
// Class S reference values.
cexpd[1] = dcmplx(554.6087004964, 484.5363331978);
cexpd[2] = dcmplx(554.6385409189, 486.5304269511);
cexpd[3] = dcmplx(554.6148406171, 488.3910722336);
cexpd[4] = dcmplx(554.5423607415, 490.1273169046);
cexpd[5] = dcmplx(554.4255039624, 491.7475857993);
cexpd[6] = dcmplx(554.2683411902, 493.2597244941);
}
else if ((n1 == 128) && (n2 == 128) && (n3 == 32) && (nt == 6))
{
// Class W reference values.
cexpd[1] = dcmplx(567.3612178944, 529.3246849175);
cexpd[2] = dcmplx(563.1436885271, 528.2149986629);
cexpd[3] = dcmplx(559.4024089970, 527.0996558037);
cexpd[4] = dcmplx(556.0698047020, 526.0027904925);
cexpd[5] = dcmplx(553.0898991250, 524.9400845633);
cexpd[6] = dcmplx(550.4159734538, 523.9212247086);
}
else if ((n1 == 256) && (n2 == 256) && (n3 == 128) && (nt == 6))
{
// Class A reference values.
cexpd[1] = dcmplx(504.6735008193, 511.4047905510);
cexpd[2] = dcmplx(505.9412319734, 509.8809666433);
cexpd[3] = dcmplx(506.9376896287, 509.8144042213);
cexpd[4] = dcmplx(507.7892868474, 510.1336130759);
cexpd[5] = dcmplx(508.5233095391, 510.4914655194);
cexpd[6] = dcmplx(509.1487099959, 510.7917842803);
}
else if ((n1 == 512) && (n2 == 256) && (n3 == 256) && (nt == 20))
{
// Class B reference values.
cexpd[1] = dcmplx(517.7643571579, 507.7803458597);
cexpd[2] = dcmplx(515.4521291263, 508.8249431599);
cexpd[3] = dcmplx(514.6409228649, 509.6208912659);
cexpd[4] = dcmplx(514.2378756213, 510.1023387619);
cexpd[5] = dcmplx(513.9626667737, 510.3976610617);
cexpd[6] = dcmplx(513.7423460082, 510.5948019802);
cexpd[7] = dcmplx(513.5547056878, 510.7404165783);
cexpd[8] = dcmplx(513.3910925466, 510.8576573661);
cexpd[9] = dcmplx(513.2470705390, 510.9577278523);
cexpd[10] = dcmplx(513.1197729984, 511.0460304483);
cexpd[11] = dcmplx(513.0070319283, 511.1252433800);
cexpd[12] = dcmplx(512.9070537032, 511.1968077718);
cexpd[13] = dcmplx(512.8182883502, 511.2616233064);
cexpd[14] = dcmplx(512.7393733383, 511.3203605551);
cexpd[15] = dcmplx(512.6691062020, 511.3735928093);
cexpd[16] = dcmplx(512.6064276004, 511.4218460548);
cexpd[17] = dcmplx(512.5504076570, 511.4656139760);
cexpd[18] = dcmplx(512.5002331720, 511.5053595966);
cexpd[19] = dcmplx(512.4551951846, 511.5415130407);
cexpd[20] = dcmplx(512.4146770029, 511.5744692211);
}
else if ((n1 == 512) && (n2 == 512) && (n3 == 512) && (nt == 20))
{
// Class C reference values.
cexpd[1] = dcmplx(519.5078707457, 514.9019699238);
cexpd[2] = dcmplx(515.5422171134, 512.7578201997);
cexpd[3] = dcmplx(514.4678022222, 512.2251847514);
cexpd[4] = dcmplx(514.0150594328, 512.1090289018);
cexpd[5] = dcmplx(513.7550426810, 512.1143685824);
cexpd[6] = dcmplx(513.5811056728, 512.1496764568);
cexpd[7] = dcmplx(513.4569343165, 512.1870921893);
cexpd[8] = dcmplx(513.3651975661, 512.2193250322);
cexpd[9] = dcmplx(513.2955192805, 512.2454735794);
cexpd[10] = dcmplx(513.2410471738, 512.2663649603);
cexpd[11] = dcmplx(513.1971141679, 512.2830879827);
cexpd[12] = dcmplx(513.1605205716, 512.2965869718);
cexpd[13] = dcmplx(513.1290734194, 512.3075927445);
cexpd[14] = dcmplx(513.1012720314, 512.3166486553);
cexpd[15] = dcmplx(513.0760908195, 512.3241541685);
cexpd[16] = dcmplx(513.0528295923, 512.3304037599);
cexpd[17] = dcmplx(513.0310107773, 512.3356167976);
cexpd[18] = dcmplx(513.0103090133, 512.3399592211);
cexpd[19] = dcmplx(512.9905029333, 512.3435588985);
cexpd[20] = dcmplx(512.9714421109, 512.3465164008);
}
else if ((n1 == 2048) && (n2 == 1024) && (n3 == 1024) && (nt == 25))
{
// Class D reference values.
cexpd[1] = dcmplx(512.2230065252, 511.8534037109);
cexpd[2] = dcmplx(512.0463975765, 511.7061181082);
cexpd[3] = dcmplx(511.9865766760, 511.7096364601);
cexpd[4] = dcmplx(511.9518799488, 511.7373863950);
cexpd[5] = dcmplx(511.9269088223, 511.7680347632);
cexpd[6] = dcmplx(511.9082416858, 511.7967875532);
cexpd[7] = dcmplx(511.8943814638, 511.8225281841);
cexpd[8] = dcmplx(511.8842385057, 511.8451629348);
cexpd[9] = dcmplx(511.8769435632, 511.8649119387);
cexpd[10] = dcmplx(511.8718203448, 511.8820803844);
cexpd[11] = dcmplx(511.8683569061, 511.8969781011);
cexpd[12] = dcmplx(511.8661708593, 511.9098918835);
cexpd[13] = dcmplx(511.8649768950, 511.9210777066);
cexpd[14] = dcmplx(511.8645605626, 511.9307604484);
cexpd[15] = dcmplx(511.8647586618, 511.9391362671);
cexpd[16] = dcmplx(511.8654451572, 511.9463757241);
cexpd[17] = dcmplx(511.8665212451, 511.9526269238);
cexpd[18] = dcmplx(511.8679083821, 511.9580184108);
cexpd[19] = dcmplx(511.8695433664, 511.9626617538);
cexpd[20] = dcmplx(511.8713748264, 511.9666538138);
cexpd[21] = dcmplx(511.8733606701, 511.9700787219);
cexpd[22] = dcmplx(511.8754661974, 511.9730095953);
cexpd[23] = dcmplx(511.8776626738, 511.9755100241);
cexpd[24] = dcmplx(511.8799262314, 511.9776353561);
cexpd[25] = dcmplx(511.8822370068, 511.9794338060);
}
else if ((n1 == 4096) && (n2 == 2048) && (n3 == 2048) && (nt == 25))
{
// Class E reference values.
cexpd[1] = dcmplx(512.1601045346, 511.7395998266);
cexpd[2] = dcmplx(512.0905403678, 511.8614716182);
cexpd[3] = dcmplx(512.0623229306, 511.9074203747);
cexpd[4] = dcmplx(512.0438418997, 511.9345900733);
cexpd[5] = dcmplx(512.0311521872, 511.9551325550);
cexpd[6] = dcmplx(512.0226088809, 511.9720179919);
cexpd[7] = dcmplx(512.0169296534, 511.9861371665);
cexpd[8] = dcmplx(512.0131225172, 511.9979364402);
cexpd[9] = dcmplx(512.0104767108, 512.0077674092);
cexpd[10] = dcmplx(512.0085127969, 512.0159443121);
cexpd[11] = dcmplx(512.0069224127, 512.0227453670);
cexpd[12] = dcmplx(512.0055158164, 512.0284096041);
cexpd[13] = dcmplx(512.0041820159, 512.0331373793);
cexpd[14] = dcmplx(512.0028605402, 512.0370938679);
cexpd[15] = dcmplx(512.0015223011, 512.0404138831);
cexpd[16] = dcmplx(512.0001570022, 512.0432068837);
cexpd[17] = dcmplx(511.9987650555, 512.0455615860);
cexpd[18] = dcmplx(511.9973525091, 512.0475499442);
cexpd[19] = dcmplx(511.9959279472, 512.0492304629);
cexpd[20] = dcmplx(511.9945006558, 512.0506508902);
cexpd[21] = dcmplx(511.9930795911, 512.0518503782);
cexpd[22] = dcmplx(511.9916728462, 512.0528612016);
cexpd[23] = dcmplx(511.9902874185, 512.0537101195);
cexpd[24] = dcmplx(511.9889291565, 512.0544194514);
cexpd[25] = dcmplx(511.9876028049, 512.0550079284);
}
else
{
printf(" Verification test for FT not performed\n");
*verified = 0;
}
// Verification test for results.
if (*verified)
{
for (kt = 1; kt <= nt; kt++)
{
err = dcmplx_abs(dcmplx_div(dcmplx_sub(cksum[kt], cexpd[kt]),
cexpd[kt]));
if (!(err <= epsilon))
{
*verified = 0;
break;
}
}
if (*verified)
{
printf(" Verification test for FT successful\n");
}
else
{
printf(" Verification test for FT failed\n");
}
}
}
void print_results(char *name, char class, int n1, int n2, int n3, int niter,
double t, double mops, char *optype, int verified)
{
char size[16];
int j;
printf( "\n\n %s Benchmark Completed.\n", name );
printf( " Class = %12c\n", class );
// If this is not a grid-based problem (EP, FT, CG), then
// we only print n1, which contains some measure of the
// problem size. In that case, n2 and n3 are both zero.
// Otherwise, we print the grid size n1xn2xn3
if ( ( n2 == 0 ) && ( n3 == 0 ) )
{
if ( ( name[0] == 'E' ) && ( name[1] == 'P' ) )
{
sprintf( size, "%15.0lf", pow(2.0, n1) );
j = 14;
if ( size[j] == '.' )
{
size[j] = ' ';
j--;
}
size[j + 1] = '\0';
printf( " Size = %15s\n", size );
}
else
{
printf( " Size = %12d\n", n1 );
}
}
else
{
printf( " Size = %4dx%4dx%4d\n", n1, n2, n3 );
}
printf( " Iterations = %12d\n", niter );
printf( " Time in seconds = %12.2lf\n", t );
printf( " Mop/s total = %15.2lf\n", mops );
printf( " Operation type = %24s\n", optype );
if ( verified )
printf( " Verification = %12s\n", "SUCCESSFUL" );
else
printf( " Verification = %12s\n", "UNSUCCESSFUL" );
}
double randlc( double *x, double a )
{
//--------------------------------------------------------------------
//
// This routine returns a uniform pseudorandom double precision number in the
// range (0, 1) by using the linear congruential generator
//
// x_{k+1} = a x_k (mod 2^46)
//
// where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers
// before repeating. The argument A is the same as 'a' in the above formula,
// and X is the same as x_0. A and X must be odd double precision integers
// in the range (1, 2^46). The returned value RANDLC is normalized to be
// between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain
// the new seed x_1, so that subsequent calls to RANDLC using the same
// arguments will generate a continuous sequence.
//
// This routine should produce the same results on any computer with at least
// 48 mantissa bits in double precision floating point data. On 64 bit
// systems, double precision should be disabled.
//
// David H. Bailey October 26, 1990
//
//--------------------------------------------------------------------
// r23 = pow(0.5, 23.0);
//// pow(0.5, 23.0) = 1.1920928955078125e-07
// r46 = r23 * r23;
// t23 = pow(2.0, 23.0);
//// pow(2.0, 23.0) = 8.388608e+06
// t46 = t23 * t23;
const double r23 = 1.1920928955078125e-07;
const double r46 = r23 * r23;
const double t23 = 8.388608e+06;
const double t46 = t23 * t23;
double t1, t2, t3, t4, a1, a2, x1, x2, z;
double r;
//--------------------------------------------------------------------
// Break A into two parts such that A = 2^23 * A1 + A2.
//--------------------------------------------------------------------
t1 = r23 * a;
a1 = (int) t1;
a2 = a - t23 * a1;
//--------------------------------------------------------------------
// Break X into two parts such that X = 2^23 * X1 + X2, compute
// Z = A1 * X2 + A2 * X1 (mod 2^23), and then
// X = 2^23 * Z + A2 * X2 (mod 2^46).
//--------------------------------------------------------------------
t1 = r23 * (*x);
x1 = (int) t1;
x2 = *x - t23 * x1;
t1 = a1 * x2 + a2 * x1;
t2 = (int) (r23 * t1);
z = t1 - t23 * t2;
t3 = t23 * z + a2 * x2;
t4 = (int) (r46 * t3);
*x = t3 - t46 * t4;
r = r46 * (*x);
return r;
}
void vranlc( int n, double *x, double a, double y[] )
{
//--------------------------------------------------------------------
//
// This routine generates N uniform pseudorandom double precision numbers in
// the range (0, 1) by using the linear congruential generator
//
// x_{k+1} = a x_k (mod 2^46)
//
// where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers
// before repeating. The argument A is the same as 'a' in the above formula,
// and X is the same as x_0. A and X must be odd double precision integers
// in the range (1, 2^46). The N results are placed in Y and are normalized
// to be between 0 and 1. X is updated to contain the new seed, so that
// subsequent calls to VRANLC using the same arguments will generate a
// continuous sequence. If N is zero, only initialization is performed, and
// the variables X, A and Y are ignored.
//
// This routine is the standard version designed for scalar or RISC systems.
// However, it should produce the same results on any single processor
// computer with at least 48 mantissa bits in double precision floating point
// data. On 64 bit systems, double precision should be disabled.
//
//--------------------------------------------------------------------
// r23 = pow(0.5, 23.0);
//// pow(0.5, 23.0) = 1.1920928955078125e-07
// r46 = r23 * r23;
// t23 = pow(2.0, 23.0);
//// pow(2.0, 23.0) = 8.388608e+06
// t46 = t23 * t23;
const double r23 = 1.1920928955078125e-07;
const double r46 = r23 * r23;
const double t23 = 8.388608e+06;
const double t46 = t23 * t23;
double t1, t2, t3, t4, a1, a2, x1, x2, z;
int i;
//--------------------------------------------------------------------
// Break A into two parts such that A = 2^23 * A1 + A2.
//--------------------------------------------------------------------
t1 = r23 * a;
a1 = (int) t1;
a2 = a - t23 * a1;
//--------------------------------------------------------------------
// Generate N results. This loop is not vectorizable.
//--------------------------------------------------------------------
for ( i = 0; i < n; i++ )
{
//--------------------------------------------------------------------
// Break X into two parts such that X = 2^23 * X1 + X2, compute
// Z = A1 * X2 + A2 * X1 (mod 2^23), and then
// X = 2^23 * Z + A2 * X2 (mod 2^46).
//--------------------------------------------------------------------
t1 = r23 * (*x);
x1 = (int) t1;
x2 = *x - t23 * x1;
t1 = a1 * x2 + a2 * x1;
t2 = (int) (r23 * t1);
z = t1 - t23 * t2;
t3 = t23 * z + a2 * x2;
t4 = (int) (r46 * t3) ;
*x = t3 - t46 * t4;
y[i] = r46 * (*x);
}
return;
}
void wtime(double *t)
{
static int sec = -1;
struct timeval tv;
gettimeofday(&tv, (void *)0);
if (sec < 0) sec = tv.tv_sec;
*t = (tv.tv_sec - sec) + 1.0e-6 * tv.tv_usec;
}
/*****************************************************************/
/****** E L A P S E D _ T I M E ******/
/*****************************************************************/
double elapsed_time( void )
{
double t;
wtime( &t );
return ( t );
}
/*****************************************************************/
/****** T I M E R _ C L E A R ******/
/*****************************************************************/
void timer_clear( int n )
{
elapsed[n] = 0.0;
}
/*****************************************************************/
/****** T I M E R _ S T A R T ******/
/*****************************************************************/
void timer_start( int n )
{
start[n] = elapsed_time();
}
/*****************************************************************/
/****** T I M E R _ S T O P ******/
/*****************************************************************/
void timer_stop( int n )
{
double t, now;
now = elapsed_time();
t = now - start[n];
elapsed[n] += t;
}
/*****************************************************************/
/****** T I M E R _ R E A D ******/
/*****************************************************************/
double timer_read( int n )
{
return ( elapsed[n] );
}
|
GB_unop__minv_uint64_uint64.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__minv_uint64_uint64
// op(A') function: GB_unop_tran__minv_uint64_uint64
// C type: uint64_t
// A type: uint64_t
// cast: uint64_t cij = aij
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 64)
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_UNSIGNED (x, 64) ;
// casting
#define GB_CAST(z, aij) \
uint64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint64_t z = aij ; \
Cx [pC] = GB_IMINV_UNSIGNED (z, 64) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__minv_uint64_uint64
(
uint64_t *Cx, // Cx and Ax may be aliased
const uint64_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++)
{
uint64_t aij = Ax [p] ;
uint64_t z = aij ;
Cx [p] = GB_IMINV_UNSIGNED (z, 64) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__minv_uint64_uint64
(
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
|
l1c2l2.c | /*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
/*
GRACE L1B to L1C & L2
Version: 20 Dec 2011
fixed and stochastic constraint solution
Copyright (c) 2011 Kun Shang (shang.34@osu.edu) All Right Reserved
*/
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
#ifndef __OMP_H__
#include <omp.h>
#endif
//#include "l1b2l1c.h"
#include "grvts.h"
#include "coord.h"
#include "numrs.h"
//#define LFIX 4
int GPS_S, GPS_E, NDATA, DT;
double GMA[2];
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
int main (int argc, char *argv[])
{
FILE *fp_stdin, *fpin_l1c, *fpout_adj, *fpout_coef;
int i, n, nmax, mmax, slvls, l_old, ndat_max, factor_b1, factor_b2,
m, l, k, ind, num, *num_arc, *gps_arc, narc_max, *ind_m,
LFIX = 0, ifix[4000], LSTK = 0, istk[4000],
nply, ncpr, nemp, ndt, narc, npd, *gpst, *gps_eph,
solvefor, solvegrv, solveemp;
short int year, month, day;
double *tp1, *csr, *gfz, *jpl,
*obs, GMR2, r2R, *coefcsr, hour,
*coefjpl, *coefgfz, *coefggm, JD0, t, Tprd,
*pt1, *pt2, *ai, *coefa, *coefe, *coefaam, factor_n,
*lambda, *lambdam, *ksiupd, *ksiupdm, *k0, *aksi, *l1cf,
*factor_a, *factor_b, factor_p, factor_r,
*ksi, *ksim, *dksi, *dksiupd, r0[1], sigma0, pweight, *p0, *p0b0,
*knk0, *knk, *kksi, *id, *kfix, *kfixt,*kn, *nk, *nkknk,
*atpa, *atpy, *cest, zero = 0.0,
omega, etpe, c, s, vfix[4000], vstk[4000],
*llr1, *llr2, *l1c_eph, *l1ct, vb1, vb2;
char line[500], card[20],
f_aam[2][200]={"\0", "\0"},
stdname[200], l1cfile[400];
time_t s0, s1, s2, s3, s4, s5, s6;
long nl, solveforN, solvegrvN, solvefor2, ns, is, in;
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
// read input cards
LFIX = 0;
if (argc == 1 || argc == 2)
{
printf ("input file name: ");
scanf ("%s%s", stdname, l1cfile);
}
else if (argc == 3)
{
sscanf (argv[1], "%s", stdname);
sscanf (argv[2], "%s", l1cfile);
}
else
{
printf ("input argument error!\n");
exit (0);
}
if ( (fp_stdin = fopen (stdname,"r")) == NULL)
{
printf ("Cannot open stdin file!\n");
exit (0);
}
// printf ("reading input file \"%s\"...\n", stdname);
s0 = time(NULL);
while (feof(fp_stdin) == 0)
{
card[1] = '\0';
if (fgets (line, 500, fp_stdin) == NULL) break;
sscanf (line, "%s", card);
if (strcmp (card,"AAM") ==0)
{
sscanf (line, "%*s%s%s", f_aam[0], f_aam[1]);
}
if (strcmp (card, "DT") ==0)
{
sscanf (line, "%*s%d", &DT);
}
if (strcmp (card, "NMAX") ==0)
{
sscanf (line, "%*s%d%d", &nmax, &mmax);
}
if (strcmp (card, "EMPR") ==0)
{
sscanf (line, "%*s%d%d%d", &nply, &ncpr, &ndt);
}
if (strcmp (card, "SOLVE") ==0)
{
sscanf (line, "%*s%d", &slvls);
}
if (strcmp (card, "FIX") ==0)
{
sscanf (line, "%*s%d%d%lf%lf", &n, &m, &c, &s);
if (m == 0)
{
ifix[LFIX] = n;
vfix[LFIX] = c;
LFIX = LFIX + 1;
}
else
{
l = nmax - m + 1;
ind = nmax + 1 + (2 * nmax - m + 2) * (m - 1);
ifix[LFIX] = ind + n - m;
ifix[LFIX + 1] = ind + n - m + l;
vfix[LFIX] = c;
vfix[LFIX + 1] = s;
LFIX = LFIX + 2;
}
}
if (strcmp (card, "STK") ==0)
{
sscanf (line, "%*s%d%d%lf%lf", &n, &m, &c, &s);
if (m == 0)
{
istk[LSTK] = n;
vstk[LSTK] = c;
LSTK = LSTK + 1;
}
else
{
l = nmax - m + 1;
ind = nmax + 1 + (2 * nmax - m + 2) * (m - 1);
istk[LSTK] = ind + n - m;
istk[LSTK + 1] = ind + n - m + l;
vstk[LSTK] = c;
vstk[LSTK + 1] = s;
LSTK = LSTK + 2;
}
}
if (strcmp (card, "FCT_P") ==0)
{
sscanf (line, "%*s%lf", &factor_p);
}
if (strcmp (card, "FCT_B") ==0)
{
sscanf (line, "%*s%d%d", &factor_b1, &factor_b2);
}
if (strcmp (card, "FCT_R") ==0)
{
sscanf (line, "%*s%lf", &factor_r);
}
if (strcmp (card, "FCT_N") ==0)
{
sscanf (line, "%*s%lf", &factor_n);
}
if (strcmp (card, "PWEIGHT") ==0)
{
sscanf (line, "%*s%lf", &pweight);
}
}
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
// open output files
if ( (fpin_l1c = fopen (l1cfile,"r")) == NULL)
{
printf ("Cannot open fpout_a file!\n");
exit (0);
}
if ( (fpout_coef = fopen ("COEF.txt","w")) == NULL)
{
printf ("Cannot open fpout_coef file!\n");
exit (0);
}
if ( (fpout_adj = fopen ("adj.txt","w")) == NULL)
{
printf ("Cannot open fpout_adj file!\n");
exit (0);
}
if (fgets(line,400, fpin_l1c) ==NULL) exit(0);
sscanf (line, "%d", &GPS_S);
NDATA = 1;
while (1)
{
if (fgets(line,400, fpin_l1c) ==NULL) break;
NDATA ++;
}
sscanf (line, "%d", &GPS_E);
rewind(fpin_l1c);
// NDATA = days * 86400 / DT;
printf ("NDATA = %d\n", NDATA);
l1c_eph = (double *) calloc (11 * NDATA, sizeof(double));
gps_eph = (int *) calloc ( NDATA, sizeof(int));
llr1 = (double *) calloc (3 * NDATA, sizeof(double));
llr2 = (double *) calloc (3 * NDATA, sizeof(double));
l1ct = (double *) calloc ( NDATA, sizeof(double));
obs = (double *) calloc ( NDATA, sizeof(double));
gpst = (int *) calloc ( NDATA, sizeof(int));
tp1 = (double *) calloc ( NDATA, sizeof(double));
csr = (double *) calloc ( NDATA, sizeof(double));
jpl = (double *) calloc ( NDATA, sizeof(double));
gfz = (double *) calloc ( NDATA, sizeof(double));
// if (fgets(line,400, fpin_l1c) ==NULL) exit(0);
// sscanf (line, "%d", &GPS_S);
// rewind(fpin_l1c);
printf("GPS_S = %d\n", GPS_S);
JD0 = GPS_S / 86400.0 + T0;
cal_date (JD0, &year, &month, &day, &hour);
JD0 = julian_date (year,month,day,0);
GPS_S = (int)((JD0 - T0) * 86400 + 0.5);
printf("GPS_S = %d\tyear = %d\tmonth = %d\tday = %d\n", GPS_S, year, month, day);
printf("GPS_E = %d\n", GPS_E);
JD0 = GPS_E / 86400.0 + T0;
cal_date (JD0, &year, &month, &day, &hour);
day = day + 1;
JD0 = julian_date (year,month,day,0);
GPS_E = (int)((JD0 - T0) * 86400 + 0.5);
printf("GPS_E = %d\tyear = %d\tmonth = %d\tday = %d\n", GPS_E, year, month, day);
i = 0;
while (1)
{
if (fgets(line,400, fpin_l1c) ==NULL) break;
sscanf (line, "%d%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%*f%*f%*f%lf",
&gps_eph[i], &l1c_eph[i * 11], &l1c_eph[i * 11 + 1], &l1c_eph[i * 11 + 2],
&l1c_eph[i * 11 + 3], &l1c_eph[i * 11 + 4], &l1c_eph[i * 11 + 5], &l1c_eph[i * 11 + 6],
&l1c_eph[i * 11 + 7], &l1c_eph[i * 11 + 8], &l1c_eph[i * 11 + 9], &l1c_eph[i * 11 + 10]);
i ++;
}
printf ("NDATA = %d\t i = %d\n", NDATA, i);
solveemp = 0;
nemp = nply + ncpr;
if (nemp == 0)
{
n = 0;
for (i = 0; i < NDATA; i ++)
{
if ((gps_eph[i] - GPS_S) % DT == 0)
{
gpst[n] = gps_eph[i];
llr1[n * 3] = l1c_eph[i * 11];
llr1[n * 3 + 1] = l1c_eph[i * 11 + 1];
llr1[n * 3 + 2] = l1c_eph[i * 11 + 2];
llr2[n * 3] = l1c_eph[i * 11 + 3];
llr2[n * 3 + 1] = l1c_eph[i * 11 + 4];
llr2[n * 3 + 2] = l1c_eph[i * 11 + 5];
l1ct[n] = l1c_eph[i * 11 + 6];
csr[n] = l1c_eph[i * 11 + 7];
gfz[n] = l1c_eph[i * 11 + 8];
jpl[n] = l1c_eph[i * 11 + 9];
tp1[n] = l1c_eph[i * 11 + 10];
n++;
}
}
NDATA = n;
printf ("NDATA = %d where nemp == 0\n", NDATA);
}
if (nemp != 0)
{
npd = (int)(86400/ndt);
narc_max = npd * (int)((GPS_E - GPS_S) / 86400.0);
num_arc = (int *) calloc ( narc_max, sizeof(int));
gps_arc = (int *) calloc ( narc_max, sizeof(int));
ndat_max = (int)(ndt / DT);
ind_m = (int *) calloc (ndat_max, sizeof(int));
n = 0;
m = 0;
narc = 0;
l_old = 0;
for (i = 0; i < NDATA - 1; i ++)
{
if ((gps_eph[i] - GPS_S) % DT == 0)
{
ind_m[m] = i;
m ++;
l = (int)((gps_eph[i + 1] - GPS_S)/ndt);
if (l < 0) l = 0;
if (l > narc_max - 1) l = narc_max - 1;
if (l == l_old)
{
l_old = l;
}
else if (l > l_old)
{
// JD0 = gps_eph[i] / 86400.0 + T0;
// cal_date (JD0, &year, &month, &day, &hour);
// printf ("l = %d\t l_old = %d\t year = %d month = %d day = %d hour = %f\t m = %d\n",
// l, l_old, year, month, day, hour, m);
// l_old = l_old + 1;
if (m > ndat_max * 0.5 && m <= ndat_max)
{
num = m;
// m = 0;
// l = (int)((gps_eph[i] - GPS_S)/ndt);
// if (l < 0)
// { printf ("l = %d\n"); l = 0;}
// if (l > narc_max - 1)
// { printf ("l = %d\n"); l = narc_max - 1;}
num_arc[l_old] = narc;
gps_arc[l_old] = gps_eph[i];
narc ++;
for (k = 0; k < num; k ++)
{
ind = ind_m[k];
gpst[n] = gps_eph[ind];
llr1[n * 3] = l1c_eph[ind * 11];
llr1[n * 3 + 1] = l1c_eph[ind * 11 + 1];
llr1[n * 3 + 2] = l1c_eph[ind * 11 + 2];
llr2[n * 3] = l1c_eph[ind * 11 + 3];
llr2[n * 3 + 1] = l1c_eph[ind * 11 + 4];
llr2[n * 3 + 2] = l1c_eph[ind * 11 + 5];
l1ct[n] = l1c_eph[ind * 11 + 6];
csr[n] = l1c_eph[ind * 11 + 7];
gfz[n] = l1c_eph[ind * 11 + 8];
jpl[n] = l1c_eph[ind * 11 + 9];
tp1[n] = l1c_eph[ind * 11 + 10];
n++;
}
}
m = 0;
l_old = l_old + 1;
}
}
}
NDATA = n;
// narc = narc - 1;
solveemp = nemp * narc;
printf ("NDATA = %d where nemp == %d\n", NDATA, nemp);
printf ("narc = %d where narc_max == %d\n", narc, narc_max);
}
solvegrv = (nmax + 1) * (nmax + 1);
solvefor = solvegrv + solveemp;
coefaam = (double *) calloc (solvegrv, sizeof(double));
printf ("nmax = %d\n", nmax);
printf ("solvefor = %d\n", solvefor);
printf ("solvegrv = %d\n", solvegrv);
solveforN = (long)(1.0 * solvefor * NDATA);
solvegrvN = (long)(1.0 * solvegrv * NDATA);
solvefor2 = (long)(1.0 * solvefor * solvefor);
printf ("solveforN = %ld\t%fG\n", solveforN, solveforN /1024.0/1024.0/1024.0);
printf ("solvegrvN = %ld\t%fG\n", solvegrvN, solvegrvN /1024.0/1024.0/1024.0);
printf ("solvefor2 = %ld\t%fG\n", solvefor2, solvefor2 /1024.0/1024.0/1024.0);
if (solveforN /1024.0/1024.0/1024.0 > 2) printf ("warning: solveforN > INT LIMIT!!!\n");
if (solvegrvN /1024.0/1024.0/1024.0 > 2) printf ("warning: solvegrvN > INT LIMIT!!!\n");
if (solvefor2 /1024.0/1024.0/1024.0 > 2) printf ("warning: solvefor2 > INT LIMIT!!!\n");
GMA[0] = 398600.44150E+09;
GMA[1] = 6378136.3;
// opengrav (f_aam, coefaam, GMA, nmax, mmax, 0);
grv_open (f_aam[0], f_aam[1], nmax, mmax, coefaam);
zero0zero1 (coefaam, nmax);
// printf ("succeed!\n");
// fflush(stdout);
atpy = (double *) calloc ( solvefor, sizeof(double));
atpa = (double *) calloc ( solvefor2, sizeof(double));
for (n = 0; n < solvefor; n++)
atpy[n] = 0;
for (nl = 0; nl < solvefor2; nl++)
atpa[nl] = 0;
// printf ("succeed!\n");
// fflush(stdout);
ai = (double *) calloc ( solveforN, sizeof(double));
for (nl = 0; nl < solveforN; nl++)
ai[nl] = 0;
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
// open gravity field file
// printf ("succeed!\n");
// fflush(stdout);
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
// calibrate accelerometer data
s1 = time(NULL);
printf("\n%5ld: seconds of reading L1C data\n", s1-s0);
fflush(stdout);
#pragma omp parallel private(pt1, pt2, i, n, m, vb1, vb2, t, l, Tprd, in)
{
pt1 = (double *) calloc ( solvegrv, sizeof(double));
pt2 = (double *) calloc ( solvegrv, sizeof(double));
#pragma omp for
for (i = 0; i < NDATA; i ++)
{
cs2gp_pt (&llr1[i * 3], coefaam, GMA[0], GMA[1], nmax, &vb1, pt1);
cs2gp_pt (&llr2[i * 3], coefaam, GMA[0], GMA[1], nmax, &vb2, pt2);
// obs[i]= vb2 - vb1; // background model n=0~60
obs[i]= l1ct[i]; // background model n=0~60
// printf ("obs = %e\n", obs[i]);
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
//y=Ax+e; form A; add bias & trend estimation or not
/////////////////////////////////////////
//all the index should be long int
//
////////////////////////////////////////
for(n = 0; n < solvegrv; n++)
{
in = (long)(1.0 * i * solvefor + n);
// a1i[i * solvegrv + n] = pt2[n] - pt1[n];
ai[in] = pt2[n] - pt1[n];
}
if (nemp != 0)
{
l = (int)((gpst[i] - GPS_S)/ndt);
if (l < 0) l = 0;
if (l > narc_max - 1) l = narc_max - 1;
t = (gpst[i] - gps_arc[l]) / 86400.0;
for (n = 0; n < nply; n++)
{
in = (long)(1.0 * i * solvefor + solvegrv + num_arc[l] * nemp + n);
ai[in] = pow(t, n);
}
Tprd = tp1[i] / 86400.0;
for (n = 0; n < ncpr; n = n + 2)
{
in = (long)(1.0 * i * solvefor + solvegrv + num_arc[l] * nemp + nply + n);
ai[in] = sin (TWOPI / Tprd * t);
in = (long)(1.0 * i * solvefor + solvegrv + num_arc[l] * nemp + nply + n + 1);
ai[in] = cos (TWOPI / Tprd * t);
Tprd = Tprd / 2.0;
}
}
}
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
free(pt1);
free(pt2);
}
s2 = time(NULL);
printf("\n%5ld: seconds of processing earth gravity and partial\n", s2-s1);
fflush(stdout);
// mt(ai, NDATA, solvefor, at);
// brmul(at, ai, solvefor,NDATA,solvefor, atpa);
// brmul(at,lhs,solvefor,NDATA,1,atpy);
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
// HARD CODE!!!!!! least-squre algorithm
// HARD CODE!!!!!! least-squre algorithm
// HARD CODE!!!!!! least-squre algorithm
p0 = (double *) calloc ( solvefor, sizeof(double));
p0b0 = (double *) calloc ( solvefor, sizeof(double));
///////////////////////////////////////////////////////////////
// start regularization
//
factor_a = (double *) calloc ( nmax + 1, sizeof(double));
factor_b = (double *) calloc ( nmax + 1, sizeof(double));
// pweight = 1/0.0001;
// pweight = 1;
GMR2 = 4e15;
r2R = 6850/6378.136;
/////////////// parameter w.r.t degree n: factor_a
for (n = 0; n <= nmax; n++)
{
factor_a[n] = pow(r2R, factor_p * (n+1));
}
//////////////// parameter w.r.t. order m: factor_b
// for (m = 0; m <= nmax; m++)
for (m = factor_b1; m <= factor_b2; m++)
{
// factor_b[m] = m*m;
factor_b[m] = pow (m, factor_n);
}
// for (m = factor_b1; m <= factor_b2; m++)
// {
// factor_b[m] = 1;
// }
// factor_b[14] = 1; factor_b[15] = 1; factor_b[16] = 1;
// factor_b[29] = 1; factor_b[30] = 1; factor_b[31] = 1;
// factor_b[45] = 1; factor_b[46] = 1; factor_b[47] = 1;
LSTK = 0;
for (n = 0; n <= nmax; n++)
{
for (m = 0; m <= n; m++)
{
if (m == 0 && factor_b[m] !=0)
{
istk[LSTK] = n;
vstk[LSTK] = GMR2 * factor_a[n] * factor_b[m] * factor_r;
// vstk[LSTK] = vstk[LSTK] * fnlgdr (0, n, m) * fnlgdr (0, n, m);
LSTK = LSTK + 1;
}
else if (m != 0 && factor_b[m] !=0)
{
l = nmax - m + 1;
ind = nmax + 1 + (2 * nmax - m + 2) * (m - 1);
istk[LSTK] = ind + n - m;
istk[LSTK + 1] = ind + n - m + l;
vstk[LSTK] = GMR2 * factor_a[n] * factor_b[m] * factor_r;
vstk[LSTK + 1] = GMR2 * factor_a[n] * factor_b[m] * factor_r;
// vstk[LSTK] = vstk[LSTK] * fnlgdr (0, n, m) * fnlgdr (0, n, m);
// vstk[LSTK + 1] = vstk[LSTK + 1] * fnlgdr (0, n, m) * fnlgdr (0, n, m);
// if (m<=n-2)
// {
// vstk[LSTK] = 0;
// vstk[LSTK + 1] = 0;
// }
LSTK = LSTK + 2;
}
}
}
// printf("LSTK = %d\t from degree %d to %d\n", LSTK, factor_b1, factor_b2);
for (n = 0; n<LSTK; n++)
{
// printf("istk = %d vstk = %e\n", istk[n], vstk[n]);
}
for (n = 0; n < solvefor; n++)
{
p0[n] = 0;
}
for (n=0; n<LSTK; n++)
{
p0[istk[n]] = vstk[n];
}
#pragma omp parallel for private(i,m,ns,is)
for (n = 0; n < solvefor; n++)
{
p0b0[n] = p0[n] * coefaam[n];
ns = (long)(1.0 * n * solvefor);
for (i = 0; i < NDATA; i ++)
{
is = (long)(1.0 * i * solvefor);
for (m = 0; m < solvefor; m++)
{
atpa[ns + m] += ai[is + n] * ai[is + m] * pweight;
}
atpy[n] += ai[is + n] * obs[i] * pweight;
}
atpa[ns + n] += p0[n];
atpy[n] += p0b0[n];
}
s3 = time(NULL);
printf("\n%5ld: seconds of finish ATPA&ATPY\n", s3-s2);
fflush(stdout);
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
// for (n = 0; n < solvefor; n++)
// {
// atpa[n * solvefor + n] = atpa[n * solvefor + n] + 1e-12;
// }
cest = (double *) calloc ( solvefor, sizeof(double));
ksi = (double *) calloc ( solvefor, sizeof(double));
// brinv (atpa,solvefor);
/////////////////////////////////////////
// inversion may not work for n > 215
/////////////////////////////////////////
if (slvls == 1)
{
printf ("Cholesky Decomposition is used\n");
solvels_chol(atpa, solvefor, atpy, ksi, 0);
}
if (slvls == 2)
{
printf ("Gauss Elimination is used\n");
solvegaus(atpa, solvefor, atpy, ksi);
}
s4 = time(NULL);
printf("\n%5ld: seconds of inverting N\n", s4-s3);
fflush(stdout);
// brmul (atpa,atpy,solvefor,solvefor,1,ksi);
/*
if (slvls == 1)
solvels_chol(BTrB, MSOL, BTry, dx, 0);
if (slvls == 2)
solvegaus(BTrB, MSOL, BTry, dx);
*/
////////////////////////////////////////////////
//estimate sigma0
//
/*
brmul(atpy, ksi, 1, solvefor, 1, ctksi);
brmul(obs, obs, 1, NDATA, 1, ytpy);
brmul(coefaam, p0b0, 1, solvefor, 1, btpb);
ytpy[0] = ytpy[0] * pweight;
omega = ytpy[0] + btpb[0]- ctksi[0];
// printf("omega = %30.20e\t%30.20e\t%30.20e\t%30.20e\n", ytpy[0], btpb[0], ctksi[0], omega);
*/
aksi = (double *) calloc ( NDATA, sizeof(double));
// aks1i = (double *) calloc ( NDATA, sizeof(double));
// brmul (ai,ksi,NDATA,solvefor,1,aksi);
for (i = 0; i < NDATA; i++)
{
aksi[i] = 0;
for (n = 0; n < solvefor; n++)
{
in = (long)(1.0 * i * solvefor + n);
aksi[i] = aksi[i] + ai[in] * ksi[n];
}
}
// brmul (a1i,ksi,NDATA,solvegrv,1,aks1i);
etpe = 0;
for (n=0; n<NDATA; n++)
{
etpe = etpe + (obs[n] - aksi[n]) * (obs[n] - aksi[n]);
}
etpe = etpe * pweight;
/*
e0p0e0 = 0;
for (n=0; n<solvefor; n++)
{
e0p0e0 = e0p0e0 + (ksi[n]-coefaam[n]) * (ksi[n]-coefaam[n]) * p0[n];
}
omega = etpe + e0p0e0;
sigma0 = (etpe + e0p0e0 ) / (NDATA - solvefor + solvefor);
*/
omega = etpe;
sigma0 = (etpe) / (NDATA - solvefor);
sigma0 = sqrt(sigma0);
// printf("etpe = %30.20e\t%30.20e\t%30.20e\n",
// etpe, e0p0e0, sigma0);
// printf("omega = %30.20e\t%30.20e\t%30.20e\t%30.20e\t%30.20e\n",
// ytpy[0], btpb[0], ctksi[0], omega, sigma0);
//////////////////////////////////////////////////////////
// printf("LFIX = %d\n", LFIX);
// fixed constrant
// *kifx, *kfixt, *kn, *knt, *nk, *kcest, *nkknk, *cupd,
kfix = (double *) calloc ( solvefor * LFIX, sizeof(double));
kfixt = (double *) calloc ( solvefor * LFIX, sizeof(double));
kn = (double *) calloc ( solvefor * LFIX, sizeof(double));
nk = (double *) calloc ( solvefor * LFIX, sizeof(double));
nkknk = (double *) calloc ( solvefor * LFIX, sizeof(double));
ksiupd = (double *) calloc ( solvefor, sizeof(double));
knk = (double *) calloc ( LFIX*LFIX, sizeof(double));
knk0 = (double *) calloc ( LFIX*LFIX, sizeof(double));
id = (double *) calloc ( LFIX*LFIX, sizeof(double));
kksi = (double *) calloc ( LFIX, sizeof(double));
lambda = (double *) calloc ( LFIX, sizeof(double));
k0 = (double *) calloc ( LFIX, sizeof(double));
for (n=0; n<LFIX; n++)
{
kfix[solvefor * n + ifix[n]] = 1.0;
k0[n] = vfix[n];
}
// kfix[solvefor + 1] = 1.0;
// kfix[solvefor * 2 + nmax + 1] = 1.0;
// kfix[solvefor * 3 + nmax + 1 + nmax] = 1.0;
mt(kfix, LFIX, solvefor, kfixt);
brmul (kfix,atpa,LFIX,solvefor,solvefor,kn);
mt(kn, LFIX, solvefor, nk);
brmul (kn,kfixt,LFIX,solvefor,LFIX,knk);
for (n=0; n<LFIX*LFIX; n++)
{
knk0[n] = knk[n];
}
// brinv (knk,LFIX);
// solvels_chol(atpa, solvefor, atpy, ksi, 0);
// brmul (atpa,kfixt,solvefor,solvefor,LFIX,nk);
brmul (kfix,ksi,LFIX,solvefor,1,kksi);
for (n=0; n<LFIX; n++)
{
kksi[n] = k0[n] - kksi[n]; //k0=[1 0 0 0]
}
// solvels_chol(knk, LFIX, kksi, lambda, 0);
if (slvls == 1)
solvels_chol(knk, LFIX, kksi, lambda, 0);
if (slvls == 2)
solvegaus(knk, LFIX, kksi, lambda);
// solvegaus(atpa, solvefor, atpy, ksi);
// brmul (knk,kksi, LFIX,LFIX,1,lambda);
brmul(knk, knk0, LFIX, LFIX, LFIX, id);
// for (n=0; n<LFIX; n++)
// {
// for (m=0; m<LFIX; m++)
// {
// printf("%10.5e ", id[n*LFIX + m]);
// }
// printf("\n");
// }
brmul (nk,lambda,solvefor,LFIX,1,ksiupd);
for (n = 0; n < solvefor; n++)
{
cest[n] = ksi[n] + ksiupd[n];
// cest[n] = ksi[n];
}
// brmul (ai,cest,NDATA,solvefor,1,aksi);
for (i = 0; i < NDATA; i++)
{
aksi[i] = 0;
for (n = 0; n < solvefor; n++)
{
in = (long)(1.0 * i * solvefor + n);
aksi[i] = aksi[i] + ai[in] * cest[n];
}
}
l1cf = (double *) calloc ( NDATA, sizeof(double));
// brmul (a1i,cest,NDATA,solvegrv,1,aks1i);
for (i = 0; i < NDATA; i++)
{
l1cf[i] = 0;
for (n = 0; n < solvegrv; n++)
{
in = (long)(1.0 * i * solvefor + n);
l1cf[i] = l1cf[i] + ai[in] * cest[n];
}
}
// printf("cest done\n");
/////////////////////////////////////////////
//estimate sigma0
//
dksiupd = (double *) calloc ( solvefor * solvefor, sizeof(double));
dksi = (double *) calloc ( solvefor * solvefor, sizeof(double));
brmul (nk,knk,solvefor,LFIX,LFIX,nkknk);
brmul (nkknk,kn,solvefor,LFIX,solvefor,dksiupd);
for (n = 0; n < solvefor; n++)
{
for (m = 0; m < solvefor; m++)
{
dksi[n * solvefor + m] = atpa[n * solvefor + m] - dksiupd[n * solvefor + m];
if (dksi[n * solvefor + m] < 0)
dksi[n * solvefor + m] = 0;
}
}
brmul (kksi,lambda,1,LFIX,1,r0);
// sigma0 = (omega + r0[0] ) / (NDATA - solvefor + LFIX);
sigma0 = sqrt ((omega + r0[0] ) / (NDATA - solvefor + LFIX));
// printf("simga0 = %e\t omega = %e\t r0 = %e\t nml = %d\n", sigma0, omega, r0[0], NDATA - solvefor + LFIX );
////////////////////////////////////////////////////////
//
//
s5 = time(NULL);
printf("\n%5ld: seconds of inverting CONSTRAINT\n", s5-s4);
fflush(stdout);
/*
dksi = (double *) calloc ( solvefor * solvefor, sizeof(double));
for (n = 0; n < solvefor; n++)
{
cest[n] = ksi[n];
}
for (n = 0; n < solvefor; n++)
{
for (m = 0; m < solvefor; m++)
{
dksi[n * solvefor + m] = atpa[n * solvefor + m];
}
}
*/
/*
if (bias == 2)
{
efbias = cest[solvefor - 1];
efbdot = cest[solvefor - 2];
}
else if (bias == 1)
{
efbias = cest[solvefor - 1];
efbdot = zero;
}
else if (bias == 0)
{
efbias = zero;
efbdot = zero;
}
*/
for (m = 0; m <= nmax; m ++)
{
l = nmax - m + 1;
for (k = 0; k < l; k++)
{
if (m==0)
{
n = k + m;
fprintf(fpout_coef,
"%4d %4d %23.13e %23.13e %23.13e %23.13e\n",
n, m, cest[k], zero,
sigma0 * sqrt(dksi[k * solvefor + k]), zero);
}
else
{
ind = nmax + 1 + (2 * nmax - m + 2) * (m - 1);
n = k + m;
fprintf(fpout_coef,
"%4d %4d %23.13e %23.13e %23.13e %23.13e\n",
n, m,
cest[ind + n - m],
cest[ind + n - m + l],
sigma0 * sqrt(dksi[(ind + n - m) * solvefor + ind + n - m]),
sigma0 * sqrt(dksi[(ind + n - m + l) * solvefor + ind + n - m + l]));
}
}
}
// for (n = solvegrv; n < solvefor; n ++)
// {
// printf ("%e\n", cest[n]);
// }
for (i = 0; i < NDATA; i++)
{
fprintf (fpout_adj,
"%d\t%20.10e\t%20.10e\t%20.10e\t%20.10e\t%20.10e\t%20.10e\t%20.10e\t%20.10e\n",
gpst[i], obs[i] - aksi[i], obs[i], aksi[i], l1cf[i],
obs[i] - aksi[i] + l1cf[i], csr[i], gfz[i], jpl[i]);
}
s6 = time(NULL);
printf("\n%5ld: seconds of output data\n", s6-s4);
fflush(stdout);
exit(0);
// fflush(0);
free (gpst);
free (ksi);
free (ksim);
free (lambda);
free (lambdam);
free (ksiupd);
free (ksiupdm);
free (dksi);
free (dksiupd);
free (ai);
free (atpa);
free (atpy);
free (cest);
free (coefa);
free (coefe);
free (coefaam);
free (coefjpl);
free (coefcsr);
free (coefgfz);
free (coefggm);
free (obs);
fclose(fpin_l1c);
fclose(fpout_coef);
fclose(fpout_adj);
ephem_close(); /* remove this line for use with solsys version 2 */
printf ("\nNormal end of ECHO!\n\npress any key to finish...\n");
exit(0);
}
/*--+----1----+----2----+----3----+----4----+----5----+----6----+----7----+--*/
|
mxEvaluate.c | /**
* \file Evaluate Lax–Friedrichs numerical flux function
* \details
* For more details, please see Giraldo et al. (2002).
*
* [1] Giraldo FX, Hesthaven JS, Warburton T. Nodal High-Order Discontinuous
* Galerkin Methods for the Spherical Shallow Water Equations. Journal of
* Computational Physics 2002;181:499–525.
*/
#include "../../SWEAbstractNumFluxSolver2d/private/SWENumFlux2d.h"
void evaluateLocalJacobian(
const double hmin, ///< wet depth threshold
const double gra, ///< gravity acceleration
const double h, ///< depth
const double hu, ///< flux
const double hv, ///< flux
double *Eh, ///< flux term
double *Ehu, ///< flux term
double *Ehv, ///< flux term
double *lambda ///< maximum eigenvalues of flux Jacobian
) {
double u, v;
if (h > hmin) {
u = hu / h;
v = hv / h;
// evaluate local eigenvalues of the flux Jacobian
*lambda = sqrt(u * u + v * v) + sqrt(gra * h);
} else {
u = 0.0;
v = 0.0;
*lambda = 0.0;
}
const double huv = h * u * v;
const double h2 = h * h;
*Eh = hu;
*Ehu = h * u * u + 0.5 * gra * h2;
*Ehv = huv;
return;
}
void evaluateLFFlux(const double hmin, ///< water threshold
const double gra, ///< gravity acceleration
const double hM, ///< local water depth
const double qnM, ///< local flux variable
const double qvM, ///< local flux variable
const double hP, ///< adjacent water depth
const double qnP, ///< adjacent flux
const double qvP, ///< adjacent flux
double *Fhn, ///< numerical flux term
double *Fqxn, ///< numerical flux term
double *Fqyn ///< numerical flux term
) {
double lambM, lambP, EM[3], EP[3];
evaluateLocalJacobian(hmin, gra, hM, qnM, qvM, EM + 0, EM + 1, EM + 2,
&lambM);
evaluateLocalJacobian(hmin, gra, hP, qnP, qvP, EP + 0, EP + 1, EP + 2,
&lambP);
double lambda = max(lambM, lambP);
*Fhn = 0.5 * (EM[0] + EP[0] - lambda * (hP - hM));
*Fqxn = 0.5 * (EM[1] + EP[1] - lambda * (qnP - qnM));
*Fqyn = 0.5 * (EM[2] + EP[2] - lambda * (qvP - qvM));
return;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
FluxSolver solver = ConvertInputMexVariable2d(nlhs, nrhs, plhs, prhs);
const size_t NdimOut = 3;
const mwSize dimOut[3] = {solver.TNfp, solver.K, 3};
plhs[0] = mxCreateNumericArray(NdimOut, dimOut, mxDOUBLE_CLASS, mxREAL);
double *Fh = mxGetPr(plhs[0]);
double *Fqx = Fh + solver.TNfp * solver.K;
double *Fqy = Fh + 2 * solver.TNfp * solver.K;
#ifdef _OPENMP
#pragma omp parallel for num_threads(DG_THREADS)
#endif
for (int k = 0; k < solver.K; k++) {
for (int n = 0; n < solver.TNfp; n++) {
const size_t sk = k * solver.TNfp + n;
const double nx = solver.nx[sk];
const double ny = solver.ny[sk];
double qnM, qnP, qvM, qvP;
RotateFluxToNormal2d(solver.huM[sk], solver.hvM[sk], nx, ny, &qnM, &qvM);
RotateFluxToNormal2d(solver.huP[sk], solver.hvP[sk], nx, ny, &qnP, &qvP);
double Fqns, Fqvs;
evaluateLFFlux(solver.hmin, solver.gra, solver.hM[sk], qnM, qvM,
solver.hP[sk], qnP, qvP, Fh + sk, &Fqns, &Fqvs);
RotateNormalFluxToCoordinate2d(Fqns, Fqvs, nx, ny, Fqx + sk, Fqy + sk);
}
}
return;
} |
keystore_fmt_plug.c | /* Java KeyStore cracker. Written by Dhiru Kholia <dhiru at openwall.com> and
* Narendra Kangralkar <narendrakangralkar at gmail.com>.
*
* Input Format: $keystore$target$data_length$data$hash$nkeys$keylength$keydata$keylength$keydata...
*
* This software is Copyright (c) 2013, Dhiru Kholia <dhiru.kholia at gmail.com>
* and Narendra Kangralkar <narendrakangralkar at gmail.com> and it is hereby
* released to the general public under the following terms: *
* Redistribution and use in source and binary forms, with or without modification,
* are permitted.
*
* major re-write - JimF, Feb, 2016.
* Added SIMD and prebuild all salt data for SIMD.
* made a common code module (for sharing code with GPU)
*/
#if FMT_EXTERNS_H
extern struct fmt_main fmt_keystore;
#elif FMT_REGISTERS_H
john_register_one(&fmt_keystore);
#else
#include <string.h>
#include <assert.h>
#include <errno.h>
#include "arch.h"
#include "simd-intrinsics.h"
//#undef SIMD_COEF_32
#include "sha.h"
#include "misc.h"
#include "common.h"
#include "formats.h"
#include "params.h"
#include "options.h"
#include "dyna_salt.h"
#include "johnswap.h"
#include "keystore_common.h"
#ifdef _OPENMP
static int omp_t = 1;
#include <omp.h>
#ifndef OMP_SCALE
#if SIMD_COEF_32
#define OMP_SCALE 1024
#else
#define OMP_SCALE 64
#endif
#endif
#elif SIMD_COEF_32
#define OMP_SCALE 128
#endif
#include "memdbg.h"
#ifdef SIMD_COEF_32
#define NBKEYS (SIMD_COEF_32 * SIMD_PARA_SHA1)
#endif
#define FORMAT_LABEL "keystore"
#define FORMAT_NAME "Java KeyStore"
#ifdef SIMD_COEF_32
#define ALGORITHM_NAME "SHA1 " SHA1_ALGORITHM_NAME
#else
#define ALGORITHM_NAME "SHA1 32/" ARCH_BITS_STR
#endif
#define BENCHMARK_COMMENT ""
#define BENCHMARK_LENGTH 0
#define PLAINTEXT_LENGTH 125
#define SALT_SIZE sizeof(struct keystore_salt *)
#define SALT_ALIGN sizeof(struct keystore_salt *)
#ifdef SIMD_COEF_32
#define MIN_KEYS_PER_CRYPT NBKEYS
#define MAX_KEYS_PER_CRYPT NBKEYS
#else
#define MIN_KEYS_PER_CRYPT 1
#define MAX_KEYS_PER_CRYPT 1
#endif
static char (*saved_key)[PLAINTEXT_LENGTH + 1];
static int (*saved_len);
static SHA_CTX (*saved_ctx);
static int dirty;
static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)];
static int *MixOrder, MixOrderLen;
#ifdef SIMD_COEF_32
#define GETPOS(i, index) ((index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + (3-((i)&3)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*4*SIMD_COEF_32)
static unsigned salt_mem_total;
typedef struct preload_t {
// Only handle password lengths of 4 to 24 (21 elements) in this code.
// passwords of other lengths are handled by oSSL CTX method.
ARCH_WORD_32 (*first_blk)[21][SHA_BUF_SIZ*NBKEYS];
ARCH_WORD_32 *ex_data[21];
int n_ex[21]; // number of sha blocks in ex_data.
unsigned char data_hash[20]; // to find if this one loaded before.
struct preload_t *next;
} preload;
static preload *salt_preload; // this is our linked list.
static preload *cursimd; // set_salt points this to the current salt.
#endif
typedef struct keystore_salt_t {
dyna_salt dsalt;
int target;
int data_length;
int count;
int keysize;
unsigned char data_hash[20]; // this is the SHA of the data block.
unsigned char *data;
unsigned char *keydata;
void *ptr; // points to a pre-built salt record (only SIMD)
} keystore_salt;
static keystore_salt *keystore_cur_salt;
/* To guard against tampering with the keystore, we append a keyed
* hash with a bit of whitener. */
static inline void getPreKeyedHash(int idx)
{
int i, j;
unsigned char passwdBytes[PLAINTEXT_LENGTH * 2];
const char *magic = "Mighty Aphrodite";
char *password = saved_key[idx];
SHA_CTX *ctxp = &saved_ctx[idx];
for (i=0, j=0; i < strlen(password); i++) {
// should this be proper LE UTF16 encoded??? NOPE. We now have
// a utf-8 encoded test hash, and the below method works.
// actually tried utf8_to_utf16_be, and the ascii passwords
// work fine, but the utf8 hash FAILS.
//passwdBytes[j++] = (password[i] >> 8);
passwdBytes[j++] = 0;
passwdBytes[j++] = password[i];
}
SHA1_Init(ctxp);
SHA1_Update(ctxp, passwdBytes, saved_len[idx] * 2);
SHA1_Update(ctxp, magic, 16);
}
static void init(struct fmt_main *self)
{
#ifdef _OPENMP
omp_t = omp_get_max_threads();
self->params.min_keys_per_crypt *= omp_t;
omp_t *= OMP_SCALE;
self->params.max_keys_per_crypt *= omp_t;
#elif SIMD_COEF_32
self->params.max_keys_per_crypt *= OMP_SCALE;
#endif
// we need 1 more saved_key than is 'used'. This extra key is used
// in SIMD code, for all part full grouped blocks.
saved_key = mem_calloc(sizeof(*saved_key), self->params.max_keys_per_crypt + 1);
saved_len = mem_calloc(sizeof(*saved_len), self->params.max_keys_per_crypt + 1);
crypt_out = mem_calloc(sizeof(*crypt_out), self->params.max_keys_per_crypt);
saved_ctx = mem_calloc(sizeof(*saved_ctx), self->params.max_keys_per_crypt);
MixOrderLen = self->params.max_keys_per_crypt*MAX_KEYS_PER_CRYPT+MAX_KEYS_PER_CRYPT;
MixOrder = mem_calloc(MixOrderLen, sizeof(int));
}
static void done(void)
{
MEM_FREE(MixOrder);
MEM_FREE(saved_ctx);
MEM_FREE(crypt_out);
MEM_FREE(saved_len);
MEM_FREE(saved_key);
#ifdef SIMD_COEF_32
while (salt_preload) {
int i;
for (i = 20; i >= 0; --i)
MEM_FREE(salt_preload->ex_data[i]);
MEM_FREE(salt_preload->first_blk);
salt_preload = salt_preload->next;
}
#endif
}
#ifdef SIMD_COEF_32
static
void link_salt(keystore_salt *ps) {
const unsigned char *magic = (const unsigned char*)"Mighty Aphrodite";
const unsigned char *cpm;
unsigned char *cpo;
int threads=1;
int j,k,t,idx;
preload *p = salt_preload;
#ifdef _OPENMP
threads = omp_get_max_threads();
#endif
while (p) {
if (!memcmp(p->data_hash, ps->data_hash, 20)) {
ps->ptr = p;
return;
}
p = p->next;
}
p = (preload *)mem_alloc_tiny(sizeof(preload), 16);
memset(p, 0, sizeof(preload));
memcpy(p->data_hash, ps->data_hash, 20);
// make sure this salt was not already loaded. IF it is loaded, then
// adjust the pointer in the salt-db record.
p->first_blk = mem_calloc_align(threads, sizeof(*p->first_blk), MEM_ALIGN_SIMD);
salt_mem_total += threads*sizeof(*p->first_blk);
for (t = 0; t < threads; ++t) { // t is threads
for (j = 0; j < 21; ++j) { // j is length-4 of candidate password
// actual length of this full string to SHA1.
unsigned bits, len = (j+4)*2+16+ps->data_length;
cpo = (unsigned char*)p->first_blk[t][j];
for (idx = 0; idx < NBKEYS; ++idx) {
cpm = magic;
for (k = (j+4)*2; *cpm; ++k) {
cpo[GETPOS(k, idx)] = *cpm++;
}
cpm = ps->data;
while (k < 64) {
cpo[GETPOS(k, idx)] = *cpm++;
++k;
}
}
if (t==0) {
// we only add 1 instance of the ex_data. for each
// password length, since this data is read only.
// All threads can share it.
p->ex_data[j] = mem_calloc_align((len+8)/64+1,
64*NBKEYS, MEM_ALIGN_SIMD);
salt_mem_total += ((len+8)/64+1)*64*NBKEYS;
for (idx = 0; idx < NBKEYS; ++idx) {
int x, z=64-((j+4)*2+16), x_full=0;
cpm = ps->data;
cpm += z;
cpo = (unsigned char*)p->ex_data[j];
for (x=0; x+z < ps->data_length; ++x) {
cpo[GETPOS(x, idx)] = *cpm++;
if (x == 63) {
x -= 64;
cpo += 64*NBKEYS;
z += 64;
x_full += 64;
}
}
cpo[GETPOS(x, idx)] = 0x80;
x += x_full;
p->n_ex[j] = x/64+1;
if (x%64 > 55) {
++p->n_ex[j];
cpo += 64*NBKEYS;
}
// now put bit length;
bits = len<<3;
x = 63;
while (bits) {
cpo[GETPOS(x, idx)] = bits&0xFF;
bits >>= 8;
--x;
}
}
}
}
}
// link this preload record into our list.
p->next = salt_preload;
salt_preload = p;
// Adjust salt record.
ps->ptr = p;
}
#endif
static void *get_salt(char *ciphertext)
{
char *ctcopy = strdup(ciphertext);
char *keeptr = ctcopy;
char *p;
int i;
SHA_CTX ctx;
static void *ptr;
keystore_salt cs;
memset(&cs, 0, sizeof(keystore_salt));
ctcopy += FORMAT_TAG_LEN; /* skip over "$keystore$" */
p = strtokm(ctcopy, "$");
cs.target = atoi(p);
p = strtokm(NULL, "$");
cs.data_length = atoi(p);
p = strtokm(NULL, "$");
cs.data = mem_alloc_tiny(cs.data_length, 1);
for (i = 0; i < cs.data_length; i++) {
cs.data[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
}
// used as a way to later compare salts. It is ALSO the
// hash for a 0 byte password for this salt.
SHA1_Init(&ctx);
SHA1_Update(&ctx, "Mighty Aphrodite", 16);
SHA1_Update(&ctx, cs.data, cs.data_length);
SHA1_Final(cs.data_hash, &ctx);
#ifdef SIMD_COEF_32
link_salt(&cs);
#endif
p = strtokm(NULL, "$"); /* skip hash */
p = strtokm(NULL, "$");
cs.count = atoi(p);
p = strtokm(NULL, "$");
cs.keysize = atoi(p);
cs.keydata = mem_alloc_tiny(cs.keysize, 1);
for (i = 0; i < cs.keysize; i++)
cs.keydata[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16
+ atoi16[ARCH_INDEX(p[i * 2 + 1])];
MEM_FREE(keeptr);
// setup the dyna_salt stuff.
cs.dsalt.salt_cmp_offset = SALT_CMP_OFF(keystore_salt, data_length);
cs.dsalt.salt_cmp_size = SALT_CMP_SIZE(keystore_salt, data_length, data, 0);
cs.dsalt.salt_alloc_needs_free = 0;
ptr = mem_alloc_tiny(sizeof(keystore_salt), MEM_ALIGN_WORD);
memcpy(ptr, &cs, sizeof(keystore_salt));
return (void *) &ptr;
}
static void set_salt(void *salt)
{
keystore_cur_salt = *(keystore_salt **) salt;
#ifdef SIMD_COEF_32
cursimd = (preload*)keystore_cur_salt->ptr;
#endif
}
static int crypt_all(int *pcount, struct db_salt *salt)
{
const int count = *pcount;
int index, tot_todo;
#ifdef SIMD_COEF_32
// in SIMD code, we need to sort by password length. NOTE, 0-3 and +24
// byte passwords 'all' group into the final group. Those are run 1 at
// a time through CTX based code.
int j, tot=0;
tot_todo = 0;
saved_len[count] = 0; // point all 'tail' MMX buffer elements to this location.
for (j = 0; j < 21 && tot<count; ++j) {
for (index = 0; index < count; ++index) {
if (saved_len[index] == j+4) {
MixOrder[tot_todo++] = index;
++tot;
}
}
while (tot_todo % MAX_KEYS_PER_CRYPT)
MixOrder[tot_todo++] = count;
}
if (tot < count) {
// these do not get SIMD usage.
for (index = 0; index < count; ++index) {
if (saved_len[index] < 4 || saved_len[index] > 24) {
MixOrder[tot_todo] = index;
++tot;
// we only want to do ONE password CTX mode
// per loop through the thread.
tot_todo += MAX_KEYS_PER_CRYPT;
}
}
}
#else
// no need to mix. just run them one after the next, in any order.
for (index = 0; index < count; ++index)
MixOrder[index] = index;
tot_todo = count;
#endif
index = 0;
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (index = 0; index < tot_todo; index += MAX_KEYS_PER_CRYPT)
{
SHA_CTX ctx;
#ifdef SIMD_COEF_32
int x, tid=0, len, idx;
char tmp_sse_out[20*MAX_KEYS_PER_CRYPT+MEM_ALIGN_SIMD];
ARCH_WORD_32 *sse_out;
sse_out = (ARCH_WORD_32 *)mem_align(tmp_sse_out, MEM_ALIGN_SIMD);
#ifdef _OPENMP
tid = omp_get_thread_num();
#endif
len = saved_len[MixOrder[index]];
if (len >= 4 && len <= 24) {
unsigned char *po;
po = (unsigned char*)cursimd->first_blk[tid][len-4];
for (x = 0; x < MAX_KEYS_PER_CRYPT; ++x) {
int j;
unsigned char *p;
idx = MixOrder[index+x];
p = (unsigned char*)saved_key[idx];
for (j = 0; j < len; ++j)
po[GETPOS(j*2+1,x)] = p[j];
}
SIMDSHA1body(po, sse_out, NULL, SSEi_MIXED_IN);
po = (unsigned char*)cursimd->ex_data[len-4];
for (x = 0; x < cursimd->n_ex[len-4]; ++x) {
SIMDSHA1body(po, sse_out, sse_out, SSEi_MIXED_IN|SSEi_RELOAD);
po += 64*MAX_KEYS_PER_CRYPT;
}
#ifdef SIMD_COEF_32
// we have to 'marshal' the data back into the SIMD output buf.
// but we only marshal the first 4 bytes.
for (x = 0; x < MAX_KEYS_PER_CRYPT; ++x) {
idx = MixOrder[index+x];
if (idx < count)
crypt_out[idx][0] = JOHNSWAP(sse_out[5*SIMD_COEF_32*(x/SIMD_COEF_32)+x%SIMD_COEF_32]);
}
#endif
// we do NOT want to fall through. We handled this
// SIMD block of data already.
continue;
}
#endif
if (dirty)
getPreKeyedHash(MixOrder[index]);
if (saved_len[MixOrder[index]] == 0)
memcpy(crypt_out[MixOrder[index]], keystore_cur_salt->data_hash, 20);
else {
memcpy(&ctx, &saved_ctx[MixOrder[index]], sizeof(ctx));
SHA1_Update(&ctx, keystore_cur_salt->data, keystore_cur_salt->data_length);
SHA1_Final((unsigned char*)crypt_out[MixOrder[index]], &ctx);
}
}
dirty = 0;
return count;
}
static int cmp_all(void *binary, int count)
{
int index = 0;
#if defined(_OPENMP) || MAX_KEYS_PER_CRYPT > 1
for (; index < count; index++)
#endif
if (((ARCH_WORD_32*)binary)[0] == crypt_out[index][0])
return 1;
return 0;
}
static int cmp_one(void *binary, int index)
{
if (((ARCH_WORD_32*)binary)[0] == crypt_out[index][0])
return 1;
return 0;
}
static int cmp_exact(char *source, int index)
{
unsigned char *binary = (unsigned char *)keystore_common_get_binary(source);
#ifdef SIMD_COEF_32
// in SIMD, we only have the first 4 bytes copied into the binary buffer.
// to for a cmp_one, so we do a full CTX type check
SHA_CTX ctx;
getPreKeyedHash(index);
memcpy(&ctx, &saved_ctx[index], sizeof(ctx));
SHA1_Update(&ctx, keystore_cur_salt->data, keystore_cur_salt->data_length);
SHA1_Final((unsigned char*)crypt_out[index], &ctx);
#endif
return !memcmp(binary, crypt_out[index], BINARY_SIZE);
}
static void keystore_set_key(char *key, int index)
{
saved_len[index] = strlen(key);
strcpy(saved_key[index], key);
dirty = 1;
}
static char *get_key(int index)
{
return saved_key[index];
}
struct fmt_main fmt_keystore = {
{
FORMAT_LABEL,
FORMAT_NAME,
ALGORITHM_NAME,
BENCHMARK_COMMENT,
BENCHMARK_LENGTH,
0,
PLAINTEXT_LENGTH,
BINARY_SIZE,
BINARY_ALIGN,
SALT_SIZE,
SALT_ALIGN,
MIN_KEYS_PER_CRYPT,
MAX_KEYS_PER_CRYPT,
FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_DYNA_SALT,
/* FIXME: report keystore_cur_salt->data_length as tunable cost? */
{ NULL },
{ FORMAT_TAG },
keystore_common_tests
}, {
init,
done,
fmt_default_reset,
fmt_default_prepare,
keystore_common_valid_cpu,
fmt_default_split,
keystore_common_get_binary,
get_salt,
{ NULL },
fmt_default_source,
{
fmt_default_binary_hash /* Not usable with $SOURCE_HASH$ */
},
fmt_default_salt_hash,
NULL,
set_salt,
keystore_set_key,
get_key,
fmt_default_clear_keys,
crypt_all,
{
fmt_default_get_hash /* Not usable with $SOURCE_HASH$ */
},
cmp_all,
cmp_one,
cmp_exact
}
};
#endif /* plugin stanza */
|
declare2.c | /* Example of the linear and uniform clauses on the
declare simd directive
The SIMD variant of the cosScaled function may assume that ptr
and scale are loop invariant and that idx is incremented by 1
each time through the loop from where the function is called.
*/
#include <math.h>
#pragma omp declare simd uniform(ptr, scale) linear(idx:1)
double cosScaled(double *ptr, double scale, int idx)
{
return (cos(ptr[idx]) * scale);
}
void simd_loop_uniform_linear(double *a, double *b, double c,
int n)
{
int i;
#pragma omp simd
for (int i=0; i<n; i++) {
a[i] = cosScaled(b, c, i);
}
// End simd region
}
|
GB_binop__bshift_int16.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the 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__bshift_int16)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__bshift_int16)
// A.*B function (eWiseMult): GB (_AemultB_03__bshift_int16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_int16)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((node))
// C+=B function (dense accum): GB (_Cdense_accumB__bshift_int16)
// C+=b function (dense accum): GB (_Cdense_accumb__bshift_int16)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_int16)
// C=scalar+B GB (_bind1st__bshift_int16)
// C=scalar+B' GB (_bind1st_tran__bshift_int16)
// C=A+scalar GB (_bind2nd__bshift_int16)
// C=A'+scalar GB (_bind2nd_tran__bshift_int16)
// C type: int16_t
// A type: int16_t
// B,b type: int8_t
// BinaryOp: cij = GB_bitshift_int16 (aij, bij)
#define GB_ATYPE \
int16_t
#define GB_BTYPE \
int8_t
#define GB_CTYPE \
int16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
0
// 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 \
0
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
int16_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
int8_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = GB_bitshift_int16 (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_BSHIFT || GxB_NO_INT16 || GxB_NO_BSHIFT_INT16)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
#if 0
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
#endif
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__bshift_int16)
(
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__bshift_int16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bshift_int16)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type 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
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((node))
(
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
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bshift_int16)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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__bshift_int16)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bshift_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__bshift_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__bshift_int16)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bshift_int16)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *Cx = (int16_t *) Cx_output ;
int16_t x = (*((int16_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 < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
int8_t bij = Bx [p] ;
Cx [p] = GB_bitshift_int16 (x, bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bshift_int16)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int16_t *Cx = (int16_t *) Cx_output ;
int16_t *Ax = (int16_t *) Ax_input ;
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 ;
int16_t aij = Ax [p] ;
Cx [p] = GB_bitshift_int16 (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 = Ax [pA] ; \
Cx [pC] = GB_bitshift_int16 (x, aij) ; \
}
GrB_Info GB (_bind1st_tran__bshift_int16)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t x = (*((const int16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = Ax [pA] ; \
Cx [pC] = GB_bitshift_int16 (aij, y) ; \
}
GrB_Info GB (_bind2nd_tran__bshift_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GxB_BinaryOp_xtype.c | //------------------------------------------------------------------------------
// GxB_BinaryOp_xtype: return the type of x for z=f(x,y)
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// NOTE: this function is historical. Use GxB_BinaryOp_xtype_name instead.
#include "GB.h"
GrB_Info GxB_BinaryOp_xtype // type of x
(
GrB_Type *xtype, // return type of input x
GrB_BinaryOp binaryop // binary operator to query
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GB_WHERE1 ("GxB_BinaryOp_xtype (&xtype, binaryop)") ;
GB_RETURN_IF_NULL (xtype) ;
GB_RETURN_IF_NULL_OR_FAULTY (binaryop) ;
ASSERT_BINARYOP_OK (binaryop, "binaryop for xtype", GB0) ;
//--------------------------------------------------------------------------
// return the xtype
//--------------------------------------------------------------------------
(*xtype) = binaryop->xtype ;
#pragma omp flush
return (GrB_SUCCESS) ;
}
|
cholesky_omp.c | /**
* This version is stamped on May 10, 2016
*
* Contact:
* Louis-Noel Pouchet <pouchet.ohio-state.edu>
* Tomofumi Yuki <tomofumi.yuki.fr>
*
* Web address: http://polybench.sourceforge.net
*/
/* cholesky.c: this file is part of PolyBench/C */
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <omp.h>
#include "util.h"
#include "papi.h"
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
#include "cholesky.h"
double **I, **O;
double **Aux;
int size;
int nthreads;
int opt;
/* Array initialization. */
static void init_array(int n, DATA_TYPE POLYBENCH_2D(A,N,N,n,n)){
I = (double **)malloc(n * sizeof(double));
O = (double **)calloc(n, sizeof(double));
Aux = (double **)malloc(n * sizeof(double));
int i, j;
for (i = 0; i < n; i++){
I[i] = (double*)malloc(n * sizeof(double));
O[i] = (double*)calloc(n, sizeof(double));
Aux[i] = (double*)malloc(n * sizeof(double));
for (j = 0; j <= i; j++){
A[i][j] = (DATA_TYPE)(-j % n) / n + 1;
I[i][j] = (DATA_TYPE)(-j % n) / n + 1;
// O[i][j] = (DATA_TYPE)(-j % n) / n + 1;
}
for (j = i+1; j < n; j++) {
A[i][j] = 0;
I[i][j] = A[i][j];
}
A[i][i] = 1;
I[i][i] = A[i][i];
}
/* Make the matrix positive semi-definite. */
int r,s,t;
for (r = 0; r < n; ++r)
for (s = 0; s < n; ++s)
Aux[r][s] = 0;
for (t = 0; t < n; ++t)
for (r = 0; r < n; ++r)
for (s = 0; s < n; ++s)
Aux[r][s] += I[r][t] * I[s][t];
for (r = 0; r < n; ++r)
for (s = 0; s < n; ++s){
I[r][s] = Aux[r][s];
}
free2D(Aux);
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static void print_array(int n, DATA_TYPE POLYBENCH_2D(A,N,N,n,n)){
int i, j;
POLYBENCH_DUMP_START;
POLYBENCH_DUMP_BEGIN("A");
for (i = 0; i < n; i++)
for (j = 0; j <= i; j++) {
if ((i * n + j) % 20 == 0) fprintf (POLYBENCH_DUMP_TARGET, "\n");
fprintf (POLYBENCH_DUMP_TARGET, DATA_PRINTF_MODIFIER, A[i][j]);
}
POLYBENCH_DUMP_END("A");
POLYBENCH_DUMP_FINISH;
}
static void cholesky_row_lower(){
int i, j, k;
for(k = 0; k < size; k++){
I[k][k] = sqrtf(I[k][k]);
for(j = (k + 1); j < size; j++){
I[k][j] /= I[k][k];
I[j][k] = I[k][j];
}
#pragma omp parallel for shared(I) private(i,j) num_threads(nthreads)
for(i = (k + 1); i < size; i++){
for(j = i; j < size; j++){
I[i][j] -= I[k][i] * I[k][j];
I[j][i] = I[i][j];
}
}
}
for(i = 0; i < size; i++){
for(j = i + 1; j < size; j++){
I[i][j] = 0.0;
}
}
}
static void cholesky_crout(){
int i, j, k;
double sum;
#pragma scop
for (j = 0; j < size; j++) {
sum = 0;
for (k = 0; k < j; k++) {
sum += O[j][k] * O[j][k];
}
O[j][j] = SQRT_FUN(I[j][j] - sum);
#pragma omp parallel for private(i, k, sum) shared(I, O, j) num_threads(nthreads)
for (i = j + 1; i < size; i++) {
sum = 0;
for (k = 0; k < j; k++) {
sum += O[i][k] * O[j][k];
}
O[i][j] = (1.0 / O[j][j] * (I[i][j] - sum));
}
}
#pragma endscop
}
int main(int argc, char** argv){
if(argc < 2){
printf("The program must have an argument to be executed. ./cholesky_omp.out $nthreads\n");
return -1;
}
nthreads = atoi(argv[1]);
opt = atoi(argv[2]);
/* Retrieve problem size. */
size = N;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, N, N, size, size);
/* Initialize array(s). */
init_array(size, POLYBENCH_ARRAY(A));
/* Start timer. */
polybench_start_instruments;
// printMatrix(I, size);
int ret;
int c1[3] = {PAPI_L1_TCM, PAPI_L2_TCM, PAPI_L3_TCM};
int c2[2] = {PAPI_TOT_CYC, PAPI_TOT_INS};
long long v1[3], v2[2];
// int counters[2] = {PAPI_TOT_CYC, PAPI_TOT_INS}, ret;
if(opt == 1){
if ((ret = PAPI_start_counters(c1, 3)) != PAPI_OK) {
fprintf(stderr, "PAPI failed to start counters: %s\n", PAPI_strerror(ret));
exit(1);
}
}
else{
if ((ret = PAPI_start_counters(c2, 2)) != PAPI_OK) {
fprintf(stderr, "PAPI failed to start counters: %s\n", PAPI_strerror(ret));
exit(1);
}
}
BEGINTIME();
/* Run kernel. */
cholesky_row_lower();
// kernel_cholesky (n, POLYBENCH_ARRAY(A));
printf("ELAPSED TIME: ");
ENDTIME();
// printMatrix(I, size);
if(opt == 1){
if ((ret = PAPI_read_counters(v1, 3)) != PAPI_OK) {
fprintf(stderr, "PAPI failed to read counters: %s\n", PAPI_strerror(ret));
exit(1);
}
printf("TOTAL L1 MISS: %lld\n", v1[0]);
printf("TOTAL L2 MISS: %lld\n", v1[1]);
printf("TOTAL L3 MISS: %lld\n", v1[2]);
}
else{
if ((ret = PAPI_read_counters(v2, 2)) != PAPI_OK) {
fprintf(stderr, "PAPI failed to read counters: %s\n", PAPI_strerror(ret));
exit(1);
}
printf("TOTAL CLOCK CYCLES: %lld\n", v2[0]);
printf("TOTAL INSTRUCTIONS: %lld\n", v2[1]);
}
printf("--------------------------------------\n");
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(size, POLYBENCH_ARRAY(A)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(A);
free2D(I);
free2D(O);
return 0;
}
|
Worker.h | //########################################################################
//## Copyright 2019 Da Yan http://www.cs.uab.edu/yanda
//##
//## Licensed under the Apache License, Version 2.0 (the "License");
//## you may not use this file except in compliance with the License.
//## You may obtain a copy of the License at
//##
//## //http://www.apache.org/licenses/LICENSE-2.0
//##
//## Unless required by applicable law or agreed to in writing, software
//## distributed under the License is distributed on an "AS IS" BASIS,
//## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//## See the License for the specific language governing permissions and
//## limitations under the License.
//########################################################################
//########################################################################
//## Contributors
//## CHOWDHURY, Md Mashiur Rahman (Mashiur)
//## YAN, Da (Daniel)
//########################################################################
#ifndef WORKER_H_
#define WORKER_H_
#include <iostream>
#include <atomic>
#include <cassert>
#include <algorithm>
#include <queue>
#include "../ydhdfs.h"
#include "../put.h"
#include "ReqServer.h"
#include "RespServer.h"
#include "ReqQueue.h"
#include "tree_msgs.h"
#include "conque_p.h"
#include "deque_p.h"
#include "conque.h"
#include "master/MasterRecver.h"
#include "conmap2t.h"
#include "slave/comper.h"
#include "slave/SlaveSender.h"
#include "master/PlanQueue.h"
using namespace std;
const int MODE_ALL_COLUMNS = 20; //a column is in every machine
const int MODE_REPLICATE = 21; //replication factor k: a column is in k machines
struct WorkerParams {
// configuration parameters
string job_file_path = "";
string tree_file_path = "";
string test_file_path = "";
string test_meta_file = "";
int column_assignment;
int replicate;
};
struct min_heap_entry //for MODE_REPLICATE
{
size_t count;
int rank;
bool operator<(const min_heap_entry& o) const
{
return count > o.count;
}
};
class Worker
{
public:
Matrix test_set; // per job 1 test data file for now
//### for debug
void print_mac_map()
{
for(size_t i=0; i<mac_map.size(); i++)
{
cout<<"col "<<i<<": ";
vector<int> & macs = mac_map[i];
for(size_t j=0; j<macs.size(); j++) cout<<macs[j]<<" ";
cout<<endl;
}
}
Worker()
{
init_worker(NULL, NULL);
if(_my_rank == MASTER_RANK) {
init_load_matrix();
}
}
~Worker()
{
#ifdef DEBUG_LOG
fout.close();// todo debug remove later
#endif
worker_finalize();
}
//only called by master
void load_tree_configs(const WorkerParams & params, vector<TreeConfig> & configList) {
load_config(params.tree_file_path.c_str(), configList); //then load tree configs
_mkdir(job_dir.c_str());
#ifdef DEBUG_LOG
string log_dir = job_dir + "/logs";
_mkdir(log_dir.c_str());
string log_file_path = log_dir + "/worker_" + to_string(_my_rank) + ".log";
fout.open(log_file_path.c_str());
print_job_config();
fout<<configList.size()<<" tree-configs loaded"<<endl;
fout<<endl;
#endif
}
// for master start ////////////////////////////
subtree_plan* create_subtree_plan(TreeConfig & plan_config, TreeNode* & root, vector<int> & column_indices) {
subtree_plan* p_plan = new subtree_plan(root);
int task_id = ++task_id_counter;
p_plan->task_id = task_id;
p_plan->tree_config = plan_config;
// for slave to fetch rows from parent node's slave
p_plan->parent_task_id = -1;
p_plan->parent_slave_id = -1;
//p_plan->is_left = is_left;
p_plan->size = _n_samples;
p_plan->level = 0;
p_plan->column_indices = column_indices;
return p_plan;
}
void create_root_subtree_plans(queue<plan*> & root_plan_buffer, vector<TreeConfig> & configList) {
for(size_t index = 0; index < configList.size(); index++) {
TreeConfig & treeConfig = configList[index];
if(treeConfig.type == DECISION_TREE) {
TreeConfig p_config;
set_config(treeConfig, p_config, 0);
subtree_plan* subtreePlan = create_subtree_plan(p_config, treeConfig.rootList[0],
treeConfig.column_distribution[0]);
subtreePlan->root_task_id = subtreePlan->task_id;
root_plan_buffer.push(subtreePlan);
} else if (treeConfig.type == RANDOM_FOREST || treeConfig.type == EXTRA_TREES) {
int n_plans = treeConfig.column_distribution.size();
for(int k = 0; k < n_plans; k++) {
TreeConfig p_config;
set_config(treeConfig, p_config, k);
subtree_plan* subtreePlan = create_subtree_plan(p_config, treeConfig.rootList[k],
treeConfig.column_distribution[k]);
subtreePlan->root_task_id = subtreePlan->task_id;
root_plan_buffer.push(subtreePlan);
}
} else {
cout << "ERROR: wrong type, File = " << __FILE__ << ", Line = " << __LINE__ << endl;
exit(-1);
}
}
}
column_split_plan* create_empty_plan(TreeConfig & plan_config, TreeNode* & root, vector<int> & column_indices) {
column_split_plan* empty_plan = new column_split_plan(root);
int new_task_id = ++task_id_counter;
empty_plan->task_id = new_task_id;
empty_plan->tree_config = plan_config;
empty_plan->level = 0;
empty_plan->parent_slave_id = -1;
empty_plan->parent_task_id = -1;
empty_plan->column_indices = column_indices;
//c_plan->is_left = 3;
empty_plan->size = _n_samples;
return empty_plan;
}
void create_root_col_split_plan(queue<plan*> & root_plan_buffer, vector<TreeConfig> & configList) {
//todo:: right now just 1 root to build a tree, later need to load a list of roots (those of random/deep forest) from config-file
for(size_t i = 0; i < configList.size(); i++) {
TreeConfig & treeConfig = configList[i];
if(treeConfig.type == DECISION_TREE) {
TreeConfig p_config;
set_config(treeConfig, p_config, 0);
column_split_plan* empty_plan = create_empty_plan(p_config, treeConfig.rootList[0],
treeConfig.column_distribution[0]);
empty_plan->root_task_id = empty_plan->task_id;
root_plan_buffer.push(empty_plan);
} else if (treeConfig.type == RANDOM_FOREST || treeConfig.type == EXTRA_TREES) {
int n_plans = treeConfig.column_distribution.size();
for(int k = 0; k < n_plans; k++) {
TreeConfig p_config;
set_config(treeConfig, p_config, k);
column_split_plan* empty_plan = create_empty_plan(p_config, treeConfig.rootList[k],
treeConfig.column_distribution[k]);
empty_plan->root_task_id = empty_plan->task_id;
root_plan_buffer.push(empty_plan);
}
} else {
cout << "ERROR: wrong type, type found = " << treeConfig.type << " File = " << __FILE__
<< ", Line = " << __LINE__ << endl;
exit(-1);
}
}
}
void send_end_plan(PlanQueue & planQueue) {
for(int i = 0; i < _num_workers; i++) {
if(i != MASTER_RANK) {
plan * end_plan = new plan(dummy);
end_plan->message_type = END_PLAN;
end_plan->dest_id = i;
planQueue.add(end_plan);
}
}
for(int i = 0; i < _num_workers; i++) {
if(i != MASTER_RANK) {
bool local_end; // temp container
recv_data<bool>(i, STATUS_CHANNEL, local_end);
}
}
global_end_label = true; // terminate all the threads of master, ReqServer, RespQueue, MasterRecver
}
void create_col_plans(Task_Master_Col_Split* task_master, column_split_plan* empty_plan,
PlanQueue & planQueue) {
vector<vector<int>> mac2colList;
mac2colList.resize(_num_workers);
vector<int> & cols = empty_plan->column_indices;
set_col_split_assignment(empty_plan->size, mac2colList, cols,
empty_plan->parent_slave_id, task_master->task_load);
for(size_t worker_id = 0; worker_id < mac2colList.size(); worker_id++) {
if (mac2colList[worker_id].size() > 0) {
// to track the assigned slave for processing the task
task_master->slave_ids.push_back(worker_id);
}
}
//create cplans from "mac2colList"
for(size_t worker_id = 0; worker_id < mac2colList.size(); worker_id++) {
if(mac2colList[worker_id].size() > 0) {
column_split_plan* c_plan = new column_split_plan(dummy);
c_plan->task_id = empty_plan->task_id;
c_plan->tree_config = empty_plan->tree_config;
c_plan->level = empty_plan->level;
c_plan->parent_slave_id = empty_plan->parent_slave_id;
c_plan->parent_task_id = empty_plan->parent_task_id;
c_plan->is_left = empty_plan->is_left; // ignore this field for root_plan
c_plan->size = empty_plan->size;
c_plan->dest_id = worker_id;
c_plan->column_indices = mac2colList[worker_id];
c_plan->total_parent_req = empty_plan->total_parent_req;
planQueue.add(c_plan);
}
}
}
// creating or updating task object (for this plan) in master-task-table
// note that a task may generate many cplans
// updating means to append slaveID for tracking response progress
void update_task_master(plan* tree_plan, conmap2t<int, Task_Master*> & task_table,
PlanQueue & planQueue) { //tree_plan rename to the_plan
// get the task object from task table, using the plan
conmap2t_bucket<int, Task_Master*> & bkt = task_table.get_bucket(tree_plan->task_id);
bkt.lock();
if(tree_plan->message_type == SUB_TREE_PLAN) {
//plan's fields has been set outside
subtree_plan* s_plan = (subtree_plan*) tree_plan;
Task_Master* task_master = new Task_Master(s_plan->node); //relay the node ref from plan
task_master->task_id = s_plan->task_id;
task_master->root_task_id = s_plan->root_task_id;
task_master->tree_config = s_plan->tree_config;
task_master->size = s_plan->size;
task_master->level = s_plan->level;
if(s_plan->tree_config.sample_col_each_node) {
s_plan->column_indices.clear();
//random_shuffle(s_plan->tree_config.n_columns, s_plan->column_indices); //wrong, should including all columns to sample from
for(int i=0; i<_num_columns; i++)
if(i != y_index) s_plan->column_indices.push_back(i);
}
task_master->column_indices = s_plan->column_indices;
// load balancing inside
set_subtree_assignment(s_plan, task_master->task_load);
bkt.insert(s_plan->task_id, task_master);
bkt.unlock();
planQueue.add(s_plan);
} else if (tree_plan->message_type == COL_SPLIT_PLAN) { // COL_SPLIT_PLAN
column_split_plan* empty_plan = (column_split_plan*) tree_plan;
Task_Master_Col_Split* task_master_col_split = new Task_Master_Col_Split(empty_plan->node); //to take plan's treeNode ref
task_master_col_split->task_id = empty_plan->task_id;
task_master_col_split->root_task_id = empty_plan->root_task_id;
task_master_col_split->tree_config = empty_plan->tree_config;
task_master_col_split->size = empty_plan->size;
task_master_col_split->level = empty_plan->level;
task_master_col_split->n_met = 0;
if(empty_plan->tree_config.sample_col_each_node) {
empty_plan->column_indices.clear();
random_shuffle(empty_plan->tree_config.n_columns, empty_plan->column_indices);
}
task_master_col_split->column_indices = empty_plan->column_indices;
// inserting to task_table
bkt.insert(empty_plan->task_id, task_master_col_split);
bkt.unlock();
create_col_plans(task_master_col_split, empty_plan, planQueue);
delete empty_plan;
} else if (tree_plan->message_type == LABEL_FETCH_PLAN) {
plan_m2s_label* plan = (plan_m2s_label*) tree_plan;
Leaf_Task* task = new Leaf_Task(plan->node);
task->task_id = plan->task_id;
task->root_task_id = plan->root_task_id;
task->size = plan->size;
task->level = plan->level;
bkt.insert(task->task_id, task);
bkt.unlock();
// adding load to load_matrix
add_leaf_load(task->task_load, plan);
planQueue.add(plan);
}
}
void run_master(PlanQueue & planQueue, queue<plan*> & root_plan_buffer, deque_p<plan> & plan_buffer,
conmap2t<int, Task_Master*> & task_table) {
plan* temp_plan = plan_buffer.pop_front();
while (temp_plan != NULL || tree_progress.active_trees() != 0
|| !root_plan_buffer.empty()) {
if(tree_progress.active_trees() < ACTIVE_TREES_THRESHOLD && !root_plan_buffer.empty()) {
plan* temp_root_plan = root_plan_buffer.front();
root_plan_buffer.pop();
tree_progress.increment(temp_root_plan->root_task_id);
if(temp_root_plan->size < BFS_PRIORITY_THRESHOLD) {
plan_buffer.push_front(temp_root_plan);
} else {
plan_buffer.push_back(temp_root_plan);
}
}
#ifdef DEBUG_LOG
if(tree_progress.active_trees() > ACTIVE_TREES_THRESHOLD) {
cout << "######################################################"<< endl;
cout << "[ERROR] active_trees_count = " << tree_progress.active_trees() << endl;
tree_progress.print_table();
cout << "######################################################"<< endl;
}
#endif
#ifdef ASSERT
assert(tree_progress.active_trees() <= ACTIVE_TREES_THRESHOLD);
#endif
if(temp_plan == NULL) {
temp_plan = plan_buffer.pop_front();
}
if(temp_plan == NULL) {
usleep(WAIT_TIME_WHEN_IDLE);
} else {
//todo:: make it two conditions:
//todo:: for SUB_TREE_PLAN, just compute 2-level slave assignments, and then call planQueue.add(temp_plan, dest_ID); (also need to add task)
#ifdef ASSERT
assert(temp_plan->message_type == SUB_TREE_PLAN
|| temp_plan->message_type == COL_SPLIT_PLAN
|| temp_plan->message_type == LABEL_FETCH_PLAN);
#endif
#ifdef DEBUG_LOG
cout << "[MASTER] main-thread: pop task |" << temp_plan->task_id
<< "| (p="<<temp_plan->parent_task_id<<") from plan_buffer "
<< ", level = " << temp_plan->level
<< ", root_task_id = " << temp_plan->root_task_id
<< ", File " << __FILE__ << ", Line = " << __LINE__ << endl;
fout << "[MASTER] main-thread: pop task |" << temp_plan->task_id
<< "| (p="<<temp_plan->parent_task_id<<") from plan_buffer "
<< ", level = " << temp_plan->level
<< ", root_task_id = " << temp_plan->root_task_id
<< ", File " << __FILE__ << ", Line = " << __LINE__ << endl;
#endif
// creating or updating task object (for this plan) in master-task-table
// note that a task may generate many cplans
// updating means to append slaveID for tracking response progress
update_task_master(temp_plan, task_table, planQueue);
}
temp_plan = plan_buffer.pop_front();
}
cout << "MASTER_END, All result found here, Now would send end plan, file = "
<< __FILE__ << ", Line = " << __LINE__ << endl;
send_end_plan(planQueue);
}
// for master end ////////////////////////////
// for slave start ////////////////////////////
void process_end_plan_slave() {
bool end_flag = true;
ibinstream m;
m << end_flag;
send_ibinstream(m, MASTER_RANK, STATUS_CHANNEL);
global_end_label = true;
}
// data has been obtained, now create task into task buffer (for compers to find "best")
void process_col_split_task(conque_p<Task_Slave> & task_buf, Candidate_Rows & candidate_rows,
column_split_plan & c_plan) {
Task_Slave_Col_Split* task = new Task_Slave_Col_Split;
task->is_root_task = (c_plan.parent_slave_id == -1);
task->task_id = c_plan.task_id;
task->tree_config = c_plan.tree_config;
task->candidate_rows = candidate_rows;
task->column_indices.swap(c_plan.column_indices);
task_buf.enqueue(task);
}
bool run_slave(ReqQueue & req_queue, conmap2t<int, Task_Slave*> & task_table,
conque_p<Task_Slave> & task_buf, conque_p<resp2master> & send_buffer) {
int has_msg;
MPI_Status status;
MPI_Iprobe(MASTER_RANK, PLAN_CHANNEL, MPI_COMM_WORLD, &has_msg, &status);
if(!has_msg) {
return false; // sleep
}
int size;
MPI_Get_count(&status, MPI_CHAR, &size); // get size of the msg-batch (# of bytes)
char * buf = new char[size]; //space for receiving this msg-batch, space will be released by obinstream in thread_func(.)
MPI_Recv(buf, size, MPI_CHAR, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
obinstream m(buf, size);
char msg_type;
while (m.end() == false) {
m >> msg_type;
if(msg_type == SUB_TREE_PLAN) { // on arrival of sub_tree plan
subtree_plan p_plan(dummy);
m >> p_plan;
Task_Slave_Subtree* subtree_task = new Task_Slave_Subtree;
subtree_task->task_id = p_plan.task_id;
subtree_task->tree_config = p_plan.tree_config;
subtree_task->level = p_plan.level;
subtree_task->matrix->col.resize(_num_columns);
subtree_task->mac2colList.swap(p_plan.mac2colList);
vector<vector<int>> & mac_cols = subtree_task->mac2colList; // destination map (index/mac_id, list_of_col_indices)
int num_slaves = 0;
vector<int> & columns_to_consider = subtree_task->column_indices;
for(size_t i = 0; i < mac_cols.size(); i++) {
if(mac_cols[i].size() > 0) {
num_slaves++;
for(size_t col_idx = 0; col_idx < mac_cols[i].size(); col_idx++) {
columns_to_consider.push_back(mac_cols[i][col_idx]);
}
}
}
subtree_task->n_req = num_slaves + 1; // extra 1 for parent row_indices
conmap2t_bucket<int, Task_Slave*> & bucket = task_table.get_bucket(p_plan.task_id);
bucket.lock();
unordered_map<int, Task_Slave*> & kvmap = bucket.get_map();
#ifdef ASSERT
auto it = kvmap.find(p_plan.task_id);
assert(it == kvmap.end());
#endif
bucket.insert(p_plan.task_id, subtree_task);
if (p_plan.parent_slave_id != -1 && p_plan.parent_slave_id != _my_rank) {
req_s2s_row_indices* req = new req_s2s_row_indices;
req->task_id = p_plan.task_id;
req->parent_task_id = p_plan.parent_task_id;
req->is_left = p_plan.is_left;
req->parent_req = p_plan.total_parent_req;
if(mac_cols[_my_rank].size() > 0) {
req->n_local_cols += mac_cols[_my_rank].size() + 1;
} else { // extra request of parent_sub_tree_task
req->n_local_cols += 1;
}
req_queue.add(req, p_plan.parent_slave_id);
bucket.unlock();
} else { // (p_plan.parent_slave_id == _my_rank || p_plan.parent_slave_id == -1)
Candidate_Rows & parent_rows = subtree_task->candidate_rows;
if(p_plan.parent_slave_id == -1) {
for(size_t i = 0; i < _n_samples; i++) {
parent_rows.indexes.push_back(i);
}
} else { // p_plan.parent_slave_id == _my_rank
conmap2t_bucket<int, Task_Slave*> & bkt = task_table.get_bucket(p_plan.parent_task_id);
if(!(task_table.bucket_hash(p_plan.task_id) == task_table.bucket_hash(p_plan.parent_task_id))) {
bkt.lock();
}
unordered_map<int, Task_Slave*> & kvmap = bkt.get_map();
auto it2 = kvmap.find(p_plan.parent_task_id);
#ifdef ASSERT
assert(it2 != kvmap.end());
#endif
Task_Slave_Col_Split* parent_task = (Task_Slave_Col_Split*) it2->second;
parent_task->parent_request = p_plan.total_parent_req;
if(p_plan.is_left) {
parent_rows = parent_task->best_left_rows;
} else {
parent_rows = parent_task->best_right_rows;
}
if(parent_rows.stop_splitting) { // KS ->master, no need to fetch remote columns
for(size_t count = 0; count < mac_cols.size(); count++) {
parent_task->n_cols += mac_cols[count].size();
}
parent_task->n_cols += 1;
} else {
if(mac_cols[_my_rank].size() > 0) {
parent_task->n_cols += mac_cols[_my_rank].size() + 1;
} else {
parent_task->n_cols += 1;
}
}
if(parent_task->n_cols == parent_task->parent_request) {
if(parent_task->best_column_idx >= 0) {
delete_best_split(parent_task->best_column_idx, parent_task->best_split); //garbage collect parent task's best-split
}
delete parent_task;
kvmap.erase(it2);
}
if(!(task_table.bucket_hash(p_plan.task_id) == task_table.bucket_hash(p_plan.parent_task_id))) {
bkt.unlock();
}
}
subtree_task->n_met++; // extra one request for parent_sub_tree_task rows
if(mac_cols[_my_rank].size() > 0) {
for(size_t j = 0; j < mac_cols[_my_rank].size(); j++) {
Column* column = getColumn(mac_cols[_my_rank][j], parent_rows.indexes);
subtree_task->matrix->col[mac_cols[_my_rank][j]] = column;
}
subtree_task->n_met++;
}
if((subtree_task->n_met == subtree_task->n_req) || parent_rows.stop_splitting) {
auto it2 = kvmap.find(subtree_task->task_id);
kvmap.erase(it2);
task_buf.enqueue(subtree_task);
bucket.unlock();
continue;
}
bucket.unlock();
}
// "main_thread_slave" sending the data fetch request for sub_tree_task
for(size_t i = 0; i < mac_cols.size(); i++) {
if(i != _my_rank && mac_cols[i].size() > 0) {
req_s2s_columns* req = new req_s2s_columns;
req->task_id = p_plan.task_id;
req->column_indices = mac_cols[i];
req->parent_slave_id = p_plan.parent_slave_id;
req->parent_task_id = p_plan.parent_task_id;
req->is_left = p_plan.is_left;
req->parent_req = p_plan.total_parent_req;
req_queue.add(req, i);
}
}
} else if (msg_type == COL_SPLIT_PLAN) { // on arrival of col_split_plan
column_split_plan c_plan(dummy);
m >> c_plan;
if(c_plan.parent_slave_id == _my_rank) { // parent_slave is local, no need to rowID fetching
//this is a slave that master gives a few columns (rows to be obtained from parent task)
//get rowIDs from parent task (which is in this slave!!!)
conmap2t_bucket<int, Task_Slave*> & bucket = task_table.get_bucket(c_plan.parent_task_id);
bucket.lock();
unordered_map<int, Task_Slave*> & kvmap = bucket.get_map();
auto it = kvmap.find(c_plan.parent_task_id);
#ifdef ASSERT
if(it == kvmap.end()) {
cout << "task = "<<c_plan.task_id<<", parent task id = " << c_plan.parent_task_id << " not found, task_id = "
<< c_plan.task_id << ", rank = " << _my_rank << " File = " << __FILE__
<< ", Line = " << __LINE__ << endl;
}
assert(it != kvmap.end());
#endif
Task_Slave_Col_Split* parent_task = (Task_Slave_Col_Split*) it->second;
parent_task->parent_request = c_plan.total_parent_req;
// from parent task (myself), get the child rowIDs
Candidate_Rows rows;
if(c_plan.is_left) {
rows = parent_task->best_left_rows;
} else {
rows = parent_task->best_right_rows;
}
//parent task updates progress
parent_task->n_cols += c_plan.column_indices.size();
if(parent_task->n_cols == parent_task->parent_request) {
kvmap.erase(it);
if(parent_task->best_column_idx >= 0) {
delete_best_split(parent_task->best_column_idx, parent_task->best_split);
}
delete parent_task;
}
bucket.unlock();
// local data has been obtained, now create task into task buffer (for compers to find "best")
process_col_split_task(task_buf, rows, c_plan);
} else if (c_plan.parent_slave_id == -1) { // entire column
//root node, no parent task
Candidate_Rows candidate_rows;
vector<size_t> & row_indices = candidate_rows.indexes;
for(size_t i = 0; i < _n_samples; i++) {
row_indices.push_back(i);
}
process_col_split_task(task_buf, candidate_rows, c_plan);
} else { // fetch row_indices from remote, create entry task_table
conmap2t_bucket<int, Task_Slave*> & bucket = task_table.get_bucket(c_plan.task_id);
bucket.lock();
Task_Slave_Col_Split* task = new Task_Slave_Col_Split;
task->task_id = c_plan.task_id;
task->tree_config = c_plan.tree_config;
task->column_indices.swap(c_plan.column_indices);
bucket.insert(task->task_id, task);
bucket.unlock();
req_s2s_row_indices* req = new req_s2s_row_indices;
req->task_id = task->task_id;
req->parent_task_id = c_plan.parent_task_id;
req->is_left = c_plan.is_left;
req->n_local_cols += task->column_indices.size();
req->parent_req = c_plan.total_parent_req;
req_queue.add(req, c_plan.parent_slave_id);
}
} else if (msg_type == TASK_DELETE_PLAN) {
plan delete_plan(dummy);
delete_plan.message_type = TASK_DELETE_PLAN; //todo:: may delete
m >> delete_plan; //just to get the task ID
conmap2t_bucket<int, Task_Slave*> & bucket = task_table.get_bucket(delete_plan.task_id);
bucket.lock();
unordered_map<int, Task_Slave*> & kvmap = bucket.get_map();
auto it = kvmap.find(delete_plan.task_id);
#ifdef ASSERT
assert(it != kvmap.end());
#endif
Task_Slave_Col_Split* task_slave_col_split = (Task_Slave_Col_Split*) it->second;
//do the deletion
kvmap.erase(it); //delete entry
bucket.unlock();
if(task_slave_col_split->best_column_idx >= 0) {
delete_best_split(task_slave_col_split->best_column_idx, task_slave_col_split->best_split);
}
delete task_slave_col_split;//delete task
} else if (msg_type == END_PLAN) {
plan p_plan(dummy);
p_plan.message_type = END_PLAN;
m >> p_plan;
process_end_plan_slave();
} else if (msg_type == LABEL_FETCH_PLAN) {
plan_m2s_label plan(dummy);
m >> plan;
conmap2t_bucket<int, Task_Slave*> & bucket = task_table.get_bucket(plan.parent_task_id);
bucket.lock();
unordered_map<int, Task_Slave*> & kvmap = bucket.get_map();
auto it = kvmap.find(plan.parent_task_id);
#ifdef ASSERT
assert(it != kvmap.end());
#endif
Task_Slave_Col_Split* parent_task = (Task_Slave_Col_Split*) it->second;
parent_task->parent_request = plan.total_parent_req;
string label;
vector<double> class_vector;
TreeConfig & treeConfig = parent_task->tree_config;
if (plan.is_left) {
vector<size_t> & rows = parent_task->best_left_rows.indexes;
set_node_label(cserver.X, rows, treeConfig, label, class_vector);
} else {
vector<size_t> & rows = parent_task->best_right_rows.indexes;
set_node_label(cserver.X, rows, treeConfig, label, class_vector);
}
parent_task->n_cols += plan.n_local_cols;
if(parent_task->n_cols == parent_task->parent_request) {
if(parent_task->best_column_idx >= 0) {
delete_best_split(parent_task->best_column_idx, parent_task->best_split);
}
delete parent_task;
kvmap.erase(it);
}
bucket.unlock();
resp_s2m_label* resp = new resp_s2m_label;
resp->task_id = plan.task_id;
resp->node_label = label;
resp->class_vector.swap(class_vector);
send_buffer.enqueue(resp);
} else {
cout << "ERROR: File = " << __FILE__ << ", Line = " << __LINE__ << endl;
exit(-1);
}
}
return true;
}
//program entry point
void run_MGS(const WorkerParams ¶ms, int win_side, int col_factor, const char* hdfs_tree_dir) {
assert(params.replicate < _num_workers); //otherwise, a machine will keep a column more than once
//note that only n-1 slaves are partitioning the data
vector<TreeConfig> configList; //only used my master
load_job_config(params.job_file_path.c_str()); //every worker loads job-config
if (_my_rank == MASTER_RANK)
load_tree_configs(params, configList);
//========== load metadata
vector<data_source> sources;
cserver.append_meta(train_file.c_str(), sources); // HDFS path
_num_columns = cserver.X.col.size();
data_source & dsrc = sources[0];
//========== initialize dsrc
dsrc.set_params(win_side, win_side, col_factor);
init_column_group(sources, dsrc);
//========== init treeConfigs
// get all non-y column IDs into "all_columns" //@@@@@@@@@@@@@@@@@
for (int j = 0; j < _num_columns; j++) {
if (j == y_index) {
continue;
}
all_columns.push_back(j);
}
if (_my_rank == MASTER_RANK) {
// initialize columns of tree-configs
for (size_t i = 0; i < configList.size(); i++) {
TreeConfig &config = configList[i];
if (config.type == DECISION_TREE) {
config.column_distribution.resize(1);
config.rootList.resize(1);
config.column_distribution[0] = all_columns;
} else if (config.type == RANDOM_FOREST || config.type == EXTRA_TREES) {
config.column_distribution.resize(config.num_trees);
config.rootList.resize(config.num_trees);
int num_columns;
if(config.column_sample == 0) { // default setting with sqrt(_num_columns - 1)
num_columns = sqrt(_num_columns - 1);
} else if (config.column_sample < 0) {
num_columns = - config.column_sample;
assert(num_columns < _num_columns);
} else { // still a ratio
num_columns = (_num_columns - 1) * config.column_sample;
assert(num_columns > 0);
}
for (int tree_index = 0; tree_index < config.num_trees;
tree_index++) {
//config.column_distribution[tree_index].clear();
random_shuffle(num_columns,
config.column_distribution[tree_index]);
}
} else {
cout << "ERROR : Wrong type, type = " << config.type
<< ", File " << __FILE__ << ", Line " << __LINE__
<< endl;
exit(-1);
}
}
}
//========== check path + init
if (_my_rank == MASTER_RANK) {
// if (dirCheck(meta_file.c_str()) == -1) return; //deep forest is not using it
if (dirCheck(train_file.c_str()) == -1)
return;
}
//========== build mac_map
if (_my_rank == MASTER_RANK) {
mac_map.resize(GROUP_OF_COLUMNS);
if (params.column_assignment == MODE_ALL_COLUMNS) {
for (int i = 0; i < GROUP_OF_COLUMNS; i++) {
for (int j = 0; j < _num_workers; j++) {
if (j == MASTER_RANK) {
continue;
}
mac_map[i].push_back(j);
}
}
} else if (params.column_assignment == MODE_REPLICATE) {
//init min-heap
priority_queue<min_heap_entry> min_heap;
for (int i = 0; i < _num_workers; i++) {
if (i == MASTER_RANK) { //master is not serving data, to save bandwidth for control msgs
continue;
}
min_heap_entry en;
en.count = 0;
en.rank = i;
min_heap.push(en);
}
//assign:
//algo: each time assign k replicates of a column to lightest-loaded machines
for (int i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
vector<min_heap_entry> mins;
for (int j = 0; j < params.replicate; j++) {
mins.push_back(min_heap.top());
min_heap.pop();
}
for (size_t j = 0; j < mins.size(); j++) {
mac_map[i].push_back(mins[j].rank);
mins[j].count += group_size[i];
min_heap.push(mins[j]);
}
}
} else {
cout << "ERROR:: File = " << __FILE__ << ", Line = " << __LINE__
<< ": this column-assignment mode is not implemented yet"
<< endl;
exit(-1);
}
//bcast-send
masterBcast(mac_map); // blocking operation
} else {
slaveBcast(mac_map); // blocking operation
}
//========== load columns
if (_my_rank != MASTER_RANK) {
for (size_t i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
vector<int> &macs = mac_map[i];
auto it = find(macs.begin(), macs.end(), _my_rank);
if (it == macs.end()) { // can happen, column 'i' does not need to be loaded in _my_rank
continue;
}
cserver.load_column_group(group_in_src[i], * group_src[i]);
}
cserver.load_y_group(dsrc); //load y from the first data_src
}
//==========
if (_my_rank == MASTER_RANK) {
deque_p<plan> plan_buffer;
queue<plan*> root_plan_buffer;
conmap2t<int, Task_Master*> task_table; // only for master
PlanQueue planQueue;
MasterRecver master_receiver(task_table, planQueue, plan_buffer);
if (_n_samples < subtree_D) {
create_root_subtree_plans(root_plan_buffer, configList);
} else {
create_root_col_split_plan(root_plan_buffer, configList);
}
auto start = chrono::system_clock::now();
run_master(planQueue, root_plan_buffer, plan_buffer, task_table);
auto end = chrono::system_clock::now();
auto train_time = chrono::duration_cast < chrono::milliseconds
> (end - start).count();
cout
<< "Training done... Now printing and deleting the tree, File = "
<< __FILE__ << ", Line = " << __LINE__ << endl;
//load test data (if specified)
if (!params.test_file_path.empty()) {
// loading test_set.csv and test_meta.csv
load_csv(params.test_file_path.c_str(),
params.test_meta_file.c_str(), test_set);
}
if (SAVE_TREE_HDFS) {
dirCheck(hdfs_tree_dir, true); //enable force
}
// print tree configs + accuracy results
for (size_t i = 0; i < configList.size(); i++) {
TreeConfig &treeConfig = configList[i];
cout << i << ": " << treeConfig.type
<< " (testing and) saving ... " << endl;
if (!params.test_file_path.empty()) {
if (treeConfig.IMPURITY_FUNC == IMPURITY_VARIANCE) {
double RMSE = calculate_RMSE(treeConfig.rootList,
test_set, y_index, INT_MAX);
cout << "RMSE found for Task " << i << " is : " << RMSE
<< endl << endl;
} else if (treeConfig.IMPURITY_FUNC == IMPURITY_ENTROPY
|| treeConfig.IMPURITY_FUNC == IMPURITY_GINI
|| treeConfig.IMPURITY_FUNC
== IMPURITY_CLASSIFICATION_ERROR) {
cout << "Accuracy found for Task " << i << " is : "
<< get_accuracy(test_set, treeConfig.rootList,
y_index, INT_MAX) << endl << endl;
} else {
cout << "ERROR : File = " << __FILE__ << ", Line = "
<< __LINE__ << endl;
exit(-1);
}
}
vector<TreeNode*> &rootList = treeConfig.rootList;
string tree_dir = job_dir;
if (SAVE_TREE) {
string tree_path = tree_dir + "/model_" + to_string(i);
save_forest(tree_path.c_str(), rootList);
}
if (SAVE_TREE_HDFS) {
string tree_path = hdfs_tree_dir;
tree_path += "/model_" + to_string(i);
save_forest_hdfs(tree_path.c_str(), rootList);
}
vector<vector<int>> &column_distribution =
treeConfig.column_distribution;
for (size_t root_idx = 0; root_idx < rootList.size();
root_idx++) {
if (PRINT_TREE) {
cout
<< "##################################################"
<< endl;
cout << "config : " << treeConfig.type
<< ", tree index = " << root_idx << endl;
cout
<< "##################################################"
<< endl;
cout << "Candidate Columns = ";
for (size_t columns_index = 0;
columns_index
< column_distribution[root_idx].size();
columns_index++) {
cout << column_distribution[root_idx][columns_index]
<< ", ";
}
cout << endl;
cout
<< "##################################################"
<< endl;
print_tree(rootList[root_idx]);
cout << endl << endl;
}
free_tree(rootList[root_idx], y_index, cserver.X);
}
}
cout
<< "...................................................................."
<< endl;
cout << "total train time = " << train_time << " milliseconds "
<< endl;
} else { // slaves
conque_p<Task_Slave> task_buf; // use by slave compers
conque_p<resp2master> send_buffer;
conmap2t<int, Task_Slave*> task_table;
RespQueue resp_queue;
ReqQueue req_queue;
ReqServer req_server(task_table, resp_queue, req_queue); // run on master, slave, serving remote data for sub_tree, row_indices (subtree and col_split)
SlaveSender slaveSender(send_buffer);
RespServer resp_server(task_table, task_buf, resp_queue);
// would run only on slaves
// since RespServer is the recv-side of data serving
vector<Comper*> compers(num_compers);
for (int i = 0; i < num_compers; i++) {
compers[i] = new Comper(task_buf, send_buffer, task_table);
}
while (global_end_label == false) {
bool computing = run_slave(req_queue, task_table, task_buf,
send_buffer);
if (!computing) {
usleep(STATUS_SYNC_TIME_GAP);
}
}
for (size_t i = 0; i < compers.size(); i++) {
delete compers[i];
}
}
#ifdef ASSERT
if (_my_rank == MASTER_RANK) {
bool isOk = true;
for (size_t i = 0; i < load_matrix.size(); i++) {
for (size_t j = 0; j < load_matrix[i].size(); j++) {
isOk = isOk && (load_matrix[i][j] == 0);
}
}
if (!isOk) {
for (size_t i = 0; i < load_matrix.size(); i++) {
for (size_t j = 0; j < load_matrix[i].size(); j++) {
cout << load_matrix[i][j] << ", ";
}
cout << endl;
}
}
assert(isOk); // todo
assert(tree_progress.active_trees() == 0);
}
#endif
// cout << "DEBUG: Terminating worker " << _my_rank << endl;
}
//program entry point
void run(const WorkerParams ¶ms) {
assert(params.replicate < _num_workers); //otherwise, a machine will keep a column more than once
//note that only n-1 slaves are partitioning the data
vector<TreeConfig> configList; //only used my master
load_job_config(params.job_file_path.c_str()); //every worker loads job-config
if (_my_rank == MASTER_RANK)
load_tree_configs(params, configList);
//========== load metadata
cserver.load_meta(meta_file.c_str()); // HDFS path
_num_columns = cserver.X.col.size();
// get all non-y column IDs into "all_columns" //@@@@@@@@@@@@@@@@@
for (int j = 0; j < _num_columns; j++) {
if (j == y_index) {
continue;
}
all_columns.push_back(j);
}
if (_my_rank == MASTER_RANK) {
// initialize columns of tree-configs
for (size_t i = 0; i < configList.size(); i++) {
TreeConfig &config = configList[i];
if (config.type == DECISION_TREE) {
config.column_distribution.resize(1);
config.rootList.resize(1);
config.column_distribution[0] = all_columns;
} else if (config.type == RANDOM_FOREST || config.type == EXTRA_TREES) {
config.column_distribution.resize(config.num_trees);
config.rootList.resize(config.num_trees);
int num_columns;
if(config.column_sample == 0) { // default setting with sqrt(_num_columns - 1)
num_columns = sqrt(_num_columns - 1);
} else if (config.column_sample < 0) {
num_columns = - config.column_sample;
assert(num_columns < _num_columns);
} else { // still a ratio
num_columns = (_num_columns - 1) * config.column_sample;
assert(num_columns > 0);
}
for (int tree_index = 0; tree_index < config.num_trees;
tree_index++) {
//config.column_distribution[tree_index].clear();
random_shuffle(num_columns,
config.column_distribution[tree_index]);
}
} else {
cout << "ERROR : Wrong type, type = " << config.type
<< ", File " << __FILE__ << ", Line " << __LINE__
<< endl;
exit(-1);
}
}
}
//========== check path + init
if (_my_rank == MASTER_RANK) {
if (dirCheck(meta_file.c_str()) == -1)
return;
if (dirCheck(train_file.c_str()) == -1)
return;
}
//========== build mac_map
if (_my_rank == MASTER_RANK) {
mac_map.resize(_num_columns);
if (params.column_assignment == MODE_ALL_COLUMNS) {
for (int i = 0; i < _num_columns; i++) {
for (int j = 0; j < _num_workers; j++) {
if (j == MASTER_RANK) {
continue;
}
mac_map[i].push_back(j);
}
}
} else if (params.column_assignment == MODE_REPLICATE) {
//init min-heap
priority_queue<min_heap_entry> min_heap;
for (int i = 0; i < _num_workers; i++) {
if (i == MASTER_RANK) { //master is not serving data, to save bandwidth for control msgs
continue;
}
min_heap_entry en;
en.count = 0;
en.rank = i;
min_heap.push(en);
}
//assign:
//algo: each time assign k replicates of a column to lightest-loaded machines
for (int i = 0; i < _num_columns; i++) {
if (i == y_index) { //y
for (int j = 0; j < _num_workers; j++) {
if (j == MASTER_RANK) {
continue;
}
mac_map[i].push_back(j);
}
} else { //Xi
vector<min_heap_entry> mins;
for (int j = 0; j < params.replicate; j++) {
mins.push_back(min_heap.top());
min_heap.pop();
}
for (size_t j = 0; j < mins.size(); j++) {
mac_map[i].push_back(mins[j].rank);
mins[j].count++;
min_heap.push(mins[j]);
}
}
}
} else {
cout << "ERROR:: File = " << __FILE__ << ", Line = " << __LINE__
<< ": this column-assignment mode is not implemented yet"
<< endl;
exit(-1);
}
//bcast-send
masterBcast(mac_map); // blocking operation
} else {
slaveBcast(mac_map); // blocking operation
}
//========== load columns
if (_my_rank != MASTER_RANK) {
for (size_t i = 0; i < mac_map.size(); i++) {
vector<int> &macs = mac_map[i];
auto it = find(macs.begin(), macs.end(), _my_rank);
if (it == macs.end()) { // can happen, column 'i' does not need to be loaded in _my_rank
continue;
}
cserver.load_column(train_file.c_str(), i);
}
}
if (_my_rank == MASTER_RANK) {
deque_p<plan> plan_buffer;
queue<plan*> root_plan_buffer;
conmap2t<int, Task_Master*> task_table; // only for master
PlanQueue planQueue;
MasterRecver master_receiver(task_table, planQueue, plan_buffer);
if (_n_samples < subtree_D) {
create_root_subtree_plans(root_plan_buffer, configList);
} else {
create_root_col_split_plan(root_plan_buffer, configList);
}
auto start = chrono::system_clock::now();
run_master(planQueue, root_plan_buffer, plan_buffer, task_table);
auto end = chrono::system_clock::now();
auto train_time = chrono::duration_cast < chrono::milliseconds
> (end - start).count();
cout
<< "Training done... Now printing and deleting the tree, File = "
<< __FILE__ << ", Line = " << __LINE__ << endl;
//load test data (if specified)
if (!params.test_file_path.empty()) {
// loading test_set.csv and test_meta.csv
load_csv(params.test_file_path.c_str(),
params.test_meta_file.c_str(), test_set);
}
// print tree configs + accuracy results
for (size_t i = 0; i < configList.size(); i++) {
TreeConfig &treeConfig = configList[i];
cout << i << ": " << treeConfig.type
<< " (testing and) saving ... " << endl;
if (!params.test_file_path.empty()) {
if (treeConfig.IMPURITY_FUNC == IMPURITY_VARIANCE) {
double RMSE = calculate_RMSE(treeConfig.rootList,
test_set, y_index, INT_MAX);
cout << "RMSE found for Task " << i << " is : " << RMSE
<< endl << endl;
} else if (treeConfig.IMPURITY_FUNC == IMPURITY_ENTROPY
|| treeConfig.IMPURITY_FUNC == IMPURITY_GINI
|| treeConfig.IMPURITY_FUNC
== IMPURITY_CLASSIFICATION_ERROR) {
cout << "Accuracy found for Task " << i << " is : "
<< get_accuracy(test_set, treeConfig.rootList,
y_index, INT_MAX) << endl << endl;
} else {
cout << "ERROR : File = " << __FILE__ << ", Line = "
<< __LINE__ << endl;
exit(-1);
}
}
vector<TreeNode*> &rootList = treeConfig.rootList;
string tree_dir = job_dir;
if (SAVE_TREE) {
string tree_path = tree_dir + "/model_" + to_string(i);
save_forest(tree_path.c_str(), rootList);
}
vector<vector<int>> &column_distribution =
treeConfig.column_distribution;
for (size_t root_idx = 0; root_idx < rootList.size();
root_idx++) {
if (PRINT_TREE) {
cout
<< "##################################################"
<< endl;
cout << "config : " << treeConfig.type
<< ", tree index = " << root_idx << endl;
cout
<< "##################################################"
<< endl;
cout << "Candidate Columns = ";
for (size_t columns_index = 0;
columns_index
< column_distribution[root_idx].size();
columns_index++) {
cout << column_distribution[root_idx][columns_index]
<< ", ";
}
cout << endl;
cout
<< "##################################################"
<< endl;
print_tree(rootList[root_idx], 0, "");
cout << endl << endl;
}
#ifdef DEBUG_LOG
cout << "trying to delete index = " << root_idx << endl;
#endif
free_tree(rootList[root_idx], y_index, cserver.X);
#ifdef DEBUG_LOG
cout << "deleted tree index = " << root_idx << endl;
#endif
}
}
cout
<< "...................................................................."
<< endl;
cout << "total train time = " << train_time << " milliseconds "
<< endl;
} else { // slaves
conque_p<Task_Slave> task_buf; // use by slave compers
conque_p<resp2master> send_buffer;
conmap2t<int, Task_Slave*> task_table;
RespQueue resp_queue;
ReqQueue req_queue;
ReqServer req_server(task_table, resp_queue, req_queue); // run on master, slave, serving remote data for sub_tree, row_indices (subtree and col_split)
SlaveSender slaveSender(send_buffer);
RespServer resp_server(task_table, task_buf, resp_queue);
// would run only on slaves
// since RespServer is the recv-side of data serving
vector<Comper*> compers(num_compers);
for (int i = 0; i < num_compers; i++) {
compers[i] = new Comper(task_buf, send_buffer, task_table);
}
while (global_end_label == false) {
bool computing = run_slave(req_queue, task_table, task_buf,
send_buffer);
if (!computing) {
usleep(STATUS_SYNC_TIME_GAP);
}
}
for (size_t i = 0; i < compers.size(); i++) {
delete compers[i];
}
}
#ifdef ASSERT
if (_my_rank == MASTER_RANK) {
bool isOk = true;
for (size_t i = 0; i < load_matrix.size(); i++) {
for (size_t j = 0; j < load_matrix[i].size(); j++) {
isOk = isOk && (load_matrix[i][j] == 0);
}
}
if (!isOk) {
for (size_t i = 0; i < load_matrix.size(); i++) {
for (size_t j = 0; j < load_matrix[i].size(); j++) {
cout << load_matrix[i][j] << ", ";
}
cout << endl;
}
}
assert(isOk); // todo
assert(tree_progress.active_trees() == 0);
}
#endif
//cout << "DEBUG: Terminating worker " << _my_rank << endl;
}
void free_forest(vector<TreeNode*> rootList)
{
Matrix & data_set = cserver.X;
for(size_t root_idx = 0; root_idx < rootList.size(); root_idx++) {
free_tree(rootList[root_idx], y_index, data_set);
}
}
/* //deprecated: model_dir should be isolated
//program entry point
void convert_MGS(int win_side, int width, int height, int RF_num, int ET_num, char* data_dir, int input_col_factor,
int output_col_factor, const char* output_hdfs_dir, int n_threads) {
//========== check path + init
if (_my_rank == MASTER_RANK) {
// if (dirCheck(meta_file.c_str()) == -1) return; //deep forest is not using it
if (dirCheck(data_dir, output_hdfs_dir, true, true) == -1)
return;
}
WIDTH = width;
HEIGHT = height;
int batch_size = (width - win_side + 1) * (height - win_side + 1);
string model_dir = data_dir;
model_dir += "/models";
string job_config_file = data_dir;
job_config_file += "/job.config";
load_job_config(job_config_file.c_str());
//========== load metadata
vector<data_source> sources;
cserver.append_meta(data_dir, sources); // HDFS path
_num_columns = cserver.X.col.size();
data_source & dsrc = sources[0];
//========== initialize dsrc
sources[0].set_params(win_side, win_side, input_col_factor);
init_column_group(sources, sources[0]);
//========== load columns
for (size_t i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
cserver.load_column_group_row_i(i, dsrc);
}
cserver.load_y_group_row_i(dsrc); //load y from the first data_src
//==========
Matrix & data_set = cserver.X;
int N = data_set.col[0]->size;
vector<vector<TreeNode*> > RF;
vector<vector<TreeNode*> > ET;
RF.resize(RF_num);
ET.resize(ET_num);
int model_id = 0;
for(int i=0; i<RF_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
RF[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
for(int i=0; i<ET_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
ET[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
//----------------------------------------------------------------
//one classVec list for each model
vector<vector<vector<double> > > RF_probVecs;
vector<vector<vector<double> > > ET_probVecs;
RF_probVecs.resize(RF_num);
for(int i=0; i<RF_num; i++)
{
RF_probVecs[i].resize(N);
}
ET_probVecs.resize(ET_num);
for(int i=0; i<ET_num; i++)
{
ET_probVecs[i].resize(N);
}
#pragma omp parallel for num_threads(n_threads)
for(int row_idx = 0; row_idx < N; row_idx++)
{
for(int i=0; i<RF_num; i++)
{
vector<TreeNode*> rootList = RF[i];
vector<double> & output_vector = RF_probVecs[i][row_idx];
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
}
for(int i=0; i<ET_num; i++)
{
vector<TreeNode*> rootList = ET[i];
vector<double> & output_vector = ET_probVecs[i][row_idx];
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
}
}
//batching merge
int B = N / batch_size;
Column* y = data_set.col.back();
vector<vector<double> > merged_probVecs(B); //features are the same as in the paper, but their order is different
vector<string> merged_ylabels;
for(int i=0; i<B; i++)
{
vector<double> & cur = merged_probVecs[i];
// for simplicity, outer loop is connecting vectors from different slided segments:
for(int j=0; j<batch_size; j++)
{
int row_idx = i * batch_size + j;
for(int k=0; k<RF_num; k++)
{
vector<vector<double> > & vecs = RF_probVecs[k];
vector<double> & vec = vecs[row_idx];
// for simplicity, inner loop is connecting vectors from different models:
cur.insert(cur.end(), vec.begin(), vec.end());
}
for(int k=0; k<ET_num; k++)
{
vector<vector<double> > & vecs = ET_probVecs[k];
vector<double> & vec = vecs[row_idx];
// for simplicity, inner loop is connecting vectors from different models:
cur.insert(cur.end(), vec.begin(), vec.end());
}
}
string ytmp;
y->get(i * batch_size, &ytmp);
merged_ylabels.push_back(ytmp);
}
// output to HDFS
string row_file = output_hdfs_dir;
row_file += "/rows_" + to_string(_my_rank);
//put_rows(row_file.c_str(), merged_probVecs, merged_ylabels); //no need as using models also reads columns like training models
put_cols(row_file.c_str(), merged_probVecs, merged_ylabels, output_col_factor);
// meta
if(_my_rank == 0)
{
string meta_file = output_hdfs_dir;
meta_file += "/meta.csv";
put_meta(meta_file.c_str(), merged_probVecs[0].size(), true);
}
// free models
for(int i=0; i<RF_num; i++) free_forest(RF[i]);
for(int i=0; i<ET_num; i++) free_forest(ET[i]);
}
*/
//program entry point
void convert_MGS(int win_side, int width, int height, int RF_num, int ET_num, char* data_dir, int input_col_factor,
int output_col_factor, const char* output_hdfs_dir, int n_threads, char* model_dir) {
//========== check path + init
if (_my_rank == MASTER_RANK) {
// if (dirCheck(meta_file.c_str()) == -1) return; //deep forest is not using it
if (dirCheck(data_dir, output_hdfs_dir, true, true) == -1)
return;
}
WIDTH = width;
HEIGHT = height;
int batch_size = (width - win_side + 1) * (height - win_side + 1);
string job_config_file = data_dir;
job_config_file += "/job.config";
load_job_config(job_config_file.c_str());
//========== load metadata
vector<data_source> sources;
cserver.append_meta(data_dir, sources); // HDFS path
_num_columns = cserver.X.col.size();
data_source & dsrc = sources[0];
//========== initialize dsrc
sources[0].set_params(win_side, win_side, input_col_factor);
init_column_group(sources, sources[0]);
//========== load columns
for (size_t i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
cserver.load_column_group_row_i(i, dsrc);
}
cserver.load_y_group_row_i(dsrc); //load y from the first data_src
//==========
Matrix & data_set = cserver.X;
int N = data_set.col[0]->size;
vector<vector<TreeNode*> > RF;
vector<vector<TreeNode*> > ET;
RF.resize(RF_num);
ET.resize(ET_num);
int model_id = 0;
for(int i=0; i<RF_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
RF[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
for(int i=0; i<ET_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
ET[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
//----------------------------------------------------------------
//one classVec list for each model
vector<vector<vector<double> > > RF_probVecs;
vector<vector<vector<double> > > ET_probVecs;
RF_probVecs.resize(RF_num);
for(int i=0; i<RF_num; i++)
{
RF_probVecs[i].resize(N);
}
ET_probVecs.resize(ET_num);
for(int i=0; i<ET_num; i++)
{
ET_probVecs[i].resize(N);
}
#pragma omp parallel for num_threads(n_threads)
for(int row_idx = 0; row_idx < N; row_idx++)
{
for(int i=0; i<RF_num; i++)
{
vector<TreeNode*> rootList = RF[i];
vector<double> & output_vector = RF_probVecs[i][row_idx];
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
}
for(int i=0; i<ET_num; i++)
{
vector<TreeNode*> rootList = ET[i];
vector<double> & output_vector = ET_probVecs[i][row_idx];
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
}
}
//batching merge
int B = N / batch_size;
Column* y = data_set.col.back();
vector<vector<double> > merged_probVecs(B); //features are the same as in the paper, but their order is different
vector<string> merged_ylabels;
for(int i=0; i<B; i++)
{
vector<double> & cur = merged_probVecs[i];
// for simplicity, outer loop is connecting vectors from different slided segments:
for(int j=0; j<batch_size; j++)
{
int row_idx = i * batch_size + j;
for(int k=0; k<RF_num; k++)
{
vector<vector<double> > & vecs = RF_probVecs[k];
vector<double> & vec = vecs[row_idx];
// for simplicity, inner loop is connecting vectors from different models:
cur.insert(cur.end(), vec.begin(), vec.end());
}
for(int k=0; k<ET_num; k++)
{
vector<vector<double> > & vecs = ET_probVecs[k];
vector<double> & vec = vecs[row_idx];
// for simplicity, inner loop is connecting vectors from different models:
cur.insert(cur.end(), vec.begin(), vec.end());
}
}
string ytmp;
y->get(i * batch_size, &ytmp);
merged_ylabels.push_back(ytmp);
}
// output to HDFS
string row_file = output_hdfs_dir;
row_file += "/rows_" + to_string(_my_rank);
//put_rows(row_file.c_str(), merged_probVecs, merged_ylabels); //no need as using models also reads columns like training models
put_cols(row_file.c_str(), merged_probVecs, merged_ylabels, output_col_factor);
// meta
if(_my_rank == 0)
{
string meta_file = output_hdfs_dir;
meta_file += "/meta.csv";
put_meta(meta_file.c_str(), merged_probVecs[0].size(), true);
}
// free models
for(int i=0; i<RF_num; i++) free_forest(RF[i]);
for(int i=0; i<ET_num; i++) free_forest(ET[i]);
}
/* //deprecated
void convert_MGS_noOMP(int win_side, int width, int height, int RF_num, int ET_num, char* data_dir, int input_col_factor,
int output_col_factor, const char* output_hdfs_dir) {
//========== check path + init
if (_my_rank == MASTER_RANK) {
// if (dirCheck(meta_file.c_str()) == -1) return; //deep forest is not using it
if (dirCheck(data_dir, output_hdfs_dir, true, true) == -1)
return;
}
WIDTH = width;
HEIGHT = height;
int batch_size = (width - win_side + 1) * (height - win_side + 1);
string model_dir = data_dir;
model_dir += "/models";
string job_config_file = data_dir;
job_config_file += "/job.config";
load_job_config(job_config_file.c_str());
//========== load metadata
vector<data_source> sources;
cserver.append_meta(data_dir, sources); // HDFS path
_num_columns = cserver.X.col.size();
data_source & dsrc = sources[0];
//========== initialize dsrc
sources[0].set_params(win_side, win_side, input_col_factor);
init_column_group(sources, sources[0]);
//========== load columns
for (size_t i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
cserver.load_column_group_row_i(i, dsrc);
}
cserver.load_y_group_row_i(dsrc); //load y from the first data_src
//==========
Matrix & data_set = cserver.X;
int N = data_set.col[0]->size;
vector<vector<TreeNode*> > RF;
vector<vector<TreeNode*> > ET;
RF.resize(RF_num);
ET.resize(ET_num);
int model_id = 0;
for(int i=0; i<RF_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
RF[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
for(int i=0; i<ET_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
ET[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
//----------------------------------------------------------------
//one classVec list for each model
vector<vector<vector<double> > > RF_probVecs;
vector<vector<vector<double> > > ET_probVecs;
RF_probVecs.resize(RF_num);
ET_probVecs.resize(ET_num);
for(int row_idx = 0; row_idx < N; row_idx++)
{
for(int i=0; i<RF_num; i++)
{
vector<TreeNode*> rootList = RF[i];
vector<double> output_vector;
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
RF_probVecs[i].push_back(output_vector);
}
for(int i=0; i<ET_num; i++)
{
vector<TreeNode*> rootList = ET[i];
vector<double> output_vector;
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
ET_probVecs[i].push_back(output_vector);
}
}
//batching merge
int B = N / batch_size;
Column* y = data_set.col.back();
vector<vector<double> > merged_probVecs(B); //features are the same as in the paper, but their order is different
vector<string> merged_ylabels;
for(int i=0; i<B; i++)
{
vector<double> & cur = merged_probVecs[i];
// for simplicity, outer loop is connecting vectors from different slided segments:
for(int j=0; j<batch_size; j++)
{
int row_idx = i * batch_size + j;
for(int k=0; k<RF_num; k++)
{
vector<vector<double> > & vecs = RF_probVecs[k];
vector<double> & vec = vecs[row_idx];
// for simplicity, inner loop is connecting vectors from different models:
cur.insert(cur.end(), vec.begin(), vec.end());
}
for(int k=0; k<ET_num; k++)
{
vector<vector<double> > & vecs = ET_probVecs[k];
vector<double> & vec = vecs[row_idx];
// for simplicity, inner loop is connecting vectors from different models:
cur.insert(cur.end(), vec.begin(), vec.end());
}
}
string ytmp;
y->get(i * batch_size, &ytmp);
merged_ylabels.push_back(ytmp);
}
// output to HDFS
string row_file = output_hdfs_dir;
row_file += "/rows_" + to_string(_my_rank);
//put_rows(row_file.c_str(), merged_probVecs, merged_ylabels); //no need as using models also reads columns like training models
put_cols(row_file.c_str(), merged_probVecs, merged_ylabels, output_col_factor);
// meta
if(_my_rank == 0)
{
string meta_file = output_hdfs_dir;
meta_file += "/meta.csv";
put_meta(meta_file.c_str(), merged_probVecs[0].size(), true);
}
// free models
for(int i=0; i<RF_num; i++) free_forest(RF[i]);
for(int i=0; i<ET_num; i++) free_forest(ET[i]);
}
*/
void run_CF0(const WorkerParams ¶ms, int num_cols, int col_factor, const char* hdfs_tree_dir) {
assert(params.replicate < _num_workers); //otherwise, a machine will keep a column more than once
//note that only n-1 slaves are partitioning the data
vector<TreeConfig> configList; //only used my master
load_job_config(params.job_file_path.c_str()); //every worker loads job-config
if (_my_rank == MASTER_RANK)
load_tree_configs(params, configList);
//========== load metadata
vector<data_source> sources;
cserver.append_meta(train_file.c_str(), sources); // HDFS path
_num_columns = cserver.X.col.size();
data_source & dsrc = sources[0];
//========== initialize dsrc
dsrc.set_params(num_cols, col_factor);
init_column_group(sources, dsrc);
//========== init treeConfigs
// get all non-y column IDs into "all_columns" //@@@@@@@@@@@@@@@@@
for (int j = 0; j < _num_columns; j++) {
if (j == y_index) {
continue;
}
all_columns.push_back(j);
}
if (_my_rank == MASTER_RANK) {
// initialize columns of tree-configs
for (size_t i = 0; i < configList.size(); i++) {
TreeConfig &config = configList[i];
if (config.type == DECISION_TREE) {
config.column_distribution.resize(1);
config.rootList.resize(1);
config.column_distribution[0] = all_columns;
} else if (config.type == RANDOM_FOREST || config.type == EXTRA_TREES) {
config.column_distribution.resize(config.num_trees);
config.rootList.resize(config.num_trees);
int num_columns;
if(config.column_sample == 0) { // default setting with sqrt(_num_columns - 1)
num_columns = sqrt(_num_columns - 1);
} else if (config.column_sample < 0) {
num_columns = - config.column_sample;
assert(num_columns < _num_columns);
} else { // still a ratio
num_columns = (_num_columns - 1) * config.column_sample;
assert(num_columns > 0);
}
for (int tree_index = 0; tree_index < config.num_trees;
tree_index++) {
//config.column_distribution[tree_index].clear();
random_shuffle(num_columns,
config.column_distribution[tree_index]);
}
} else {
cout << "ERROR : Wrong type, type = " << config.type
<< ", File " << __FILE__ << ", Line " << __LINE__
<< endl;
exit(-1);
}
}
}
//========== check path + init
if (_my_rank == MASTER_RANK) {
// if (dirCheck(meta_file.c_str()) == -1) return; //deep forest is not using it
if (dirCheck(train_file.c_str()) == -1)
return;
}
//========== build mac_map
if (_my_rank == MASTER_RANK) {
mac_map.resize(GROUP_OF_COLUMNS);
if (params.column_assignment == MODE_ALL_COLUMNS) {
for (int i = 0; i < GROUP_OF_COLUMNS; i++) {
for (int j = 0; j < _num_workers; j++) {
if (j == MASTER_RANK) {
continue;
}
mac_map[i].push_back(j);
}
}
} else if (params.column_assignment == MODE_REPLICATE) {
//init min-heap
priority_queue<min_heap_entry> min_heap;
for (int i = 0; i < _num_workers; i++) {
if (i == MASTER_RANK) { //master is not serving data, to save bandwidth for control msgs
continue;
}
min_heap_entry en;
en.count = 0;
en.rank = i;
min_heap.push(en);
}
//assign:
//algo: each time assign k replicates of a column to lightest-loaded machines
for (int i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
vector<min_heap_entry> mins;
for (int j = 0; j < params.replicate; j++) {
mins.push_back(min_heap.top());
min_heap.pop();
}
for (size_t j = 0; j < mins.size(); j++) {
mac_map[i].push_back(mins[j].rank);
mins[j].count += group_size[i];
min_heap.push(mins[j]);
}
}
} else {
cout << "ERROR:: File = " << __FILE__ << ", Line = " << __LINE__
<< ": this column-assignment mode is not implemented yet"
<< endl;
exit(-1);
}
//bcast-send
masterBcast(mac_map); // blocking operation
} else {
slaveBcast(mac_map); // blocking operation
}
//========== load columns
if (_my_rank != MASTER_RANK) {
for (size_t i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
vector<int> &macs = mac_map[i];
auto it = find(macs.begin(), macs.end(), _my_rank);
if (it == macs.end()) { // can happen, column 'i' does not need to be loaded in _my_rank
continue;
}
cserver.load_column_group(group_in_src[i], * group_src[i]);
}
cserver.load_y_group(dsrc); //load y from the first data_src
}
//==========
if (_my_rank == MASTER_RANK) {
deque_p<plan> plan_buffer;
queue<plan*> root_plan_buffer;
conmap2t<int, Task_Master*> task_table; // only for master
PlanQueue planQueue;
MasterRecver master_receiver(task_table, planQueue, plan_buffer);
if (_n_samples < subtree_D) {
create_root_subtree_plans(root_plan_buffer, configList);
} else {
create_root_col_split_plan(root_plan_buffer, configList);
}
auto start = chrono::system_clock::now();
run_master(planQueue, root_plan_buffer, plan_buffer, task_table);
auto end = chrono::system_clock::now();
auto train_time = chrono::duration_cast < chrono::milliseconds
> (end - start).count();
cout
<< "Training done... Now printing and deleting the tree, File = "
<< __FILE__ << ", Line = " << __LINE__ << endl;
//load test data (if specified)
if (!params.test_file_path.empty()) {
// loading test_set.csv and test_meta.csv
load_csv(params.test_file_path.c_str(),
params.test_meta_file.c_str(), test_set);
}
if (SAVE_TREE_HDFS) {
dirCheck(hdfs_tree_dir, true); //enable force
}
// print tree configs + accuracy results
for (size_t i = 0; i < configList.size(); i++) {
TreeConfig &treeConfig = configList[i];
cout << i << ": " << treeConfig.type
<< " (testing and) saving ... " << endl;
if (!params.test_file_path.empty()) {
if (treeConfig.IMPURITY_FUNC == IMPURITY_VARIANCE) {
double RMSE = calculate_RMSE(treeConfig.rootList,
test_set, y_index, INT_MAX);
cout << "RMSE found for Task " << i << " is : " << RMSE
<< endl << endl;
} else if (treeConfig.IMPURITY_FUNC == IMPURITY_ENTROPY
|| treeConfig.IMPURITY_FUNC == IMPURITY_GINI
|| treeConfig.IMPURITY_FUNC
== IMPURITY_CLASSIFICATION_ERROR) {
cout << "Accuracy found for Task " << i << " is : "
<< get_accuracy(test_set, treeConfig.rootList,
y_index, INT_MAX) << endl << endl;
} else {
cout << "ERROR : File = " << __FILE__ << ", Line = "
<< __LINE__ << endl;
exit(-1);
}
}
vector<TreeNode*> &rootList = treeConfig.rootList;
string tree_dir = job_dir;
if (SAVE_TREE) {
string tree_path = tree_dir + "/model_" + to_string(i);
save_forest(tree_path.c_str(), rootList);
}
if (SAVE_TREE_HDFS) {
string tree_path = hdfs_tree_dir;
tree_path += "/model_" + to_string(i);
save_forest_hdfs(tree_path.c_str(), rootList);
}
vector<vector<int>> &column_distribution =
treeConfig.column_distribution;
for (size_t root_idx = 0; root_idx < rootList.size();
root_idx++) {
if (PRINT_TREE) {
cout
<< "##################################################"
<< endl;
cout << "config : " << treeConfig.type
<< ", tree index = " << root_idx << endl;
cout
<< "##################################################"
<< endl;
cout << "Candidate Columns = ";
for (size_t columns_index = 0;
columns_index
< column_distribution[root_idx].size();
columns_index++) {
cout << column_distribution[root_idx][columns_index]
<< ", ";
}
cout << endl;
cout
<< "##################################################"
<< endl;
print_tree(rootList[root_idx]);
cout << endl << endl;
}
free_tree(rootList[root_idx], y_index, cserver.X);
}
}
cout
<< "...................................................................."
<< endl;
cout << "total train time = " << train_time << " milliseconds "
<< endl;
} else { // slaves
conque_p<Task_Slave> task_buf; // use by slave compers
conque_p<resp2master> send_buffer;
conmap2t<int, Task_Slave*> task_table;
RespQueue resp_queue;
ReqQueue req_queue;
ReqServer req_server(task_table, resp_queue, req_queue); // run on master, slave, serving remote data for sub_tree, row_indices (subtree and col_split)
SlaveSender slaveSender(send_buffer);
RespServer resp_server(task_table, task_buf, resp_queue);
// would run only on slaves
// since RespServer is the recv-side of data serving
vector<Comper*> compers(num_compers);
for (int i = 0; i < num_compers; i++) {
compers[i] = new Comper(task_buf, send_buffer, task_table);
}
while (global_end_label == false) {
bool computing = run_slave(req_queue, task_table, task_buf,
send_buffer);
if (!computing) {
usleep(STATUS_SYNC_TIME_GAP);
}
}
for (size_t i = 0; i < compers.size(); i++) {
delete compers[i];
}
}
#ifdef ASSERT
if (_my_rank == MASTER_RANK) {
bool isOk = true;
for (size_t i = 0; i < load_matrix.size(); i++) {
for (size_t j = 0; j < load_matrix[i].size(); j++) {
isOk = isOk && (load_matrix[i][j] == 0);
}
}
if (!isOk) {
for (size_t i = 0; i < load_matrix.size(); i++) {
for (size_t j = 0; j < load_matrix[i].size(); j++) {
cout << load_matrix[i][j] << ", ";
}
cout << endl;
}
}
assert(isOk); // todo
assert(tree_progress.active_trees() == 0);
}
#endif
// cout << "DEBUG: Terminating worker " << _my_rank << endl;
}
//program entry point
void convert_CF0(int num_features, int RF_num, int ET_num, char* data_dir, int input_col_factor,
int output_col_factor, const char* output_hdfs_dir, char* job_config_file, char* model_dir, int n_threads) {
//========== check path + init
if (_my_rank == MASTER_RANK) {
// if (dirCheck(meta_file.c_str()) == -1) return; //deep forest is not using it
if (dirCheck(data_dir, output_hdfs_dir, true, true) == -1)
return;
}
load_job_config(job_config_file);
//========== load metadata
vector<data_source> sources;
cserver.append_meta(data_dir, sources); // HDFS path
_num_columns = cserver.X.col.size();
data_source & dsrc = sources[0];
//========== initialize dsrc
sources[0].set_params(num_features, input_col_factor);
init_column_group(sources, sources[0]);
//========== load columns
for (size_t i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
cserver.load_column_group_row_i(i, dsrc);
}
cserver.load_y_group_row_i(dsrc); //load y from the first data_src
//==========
Matrix & data_set = cserver.X;
int N = data_set.col[0]->size;
vector<vector<TreeNode*> > RF;
vector<vector<TreeNode*> > ET;
RF.resize(RF_num);
ET.resize(ET_num);
int model_id = 0;
for(int i=0; i<RF_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
RF[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
for(int i=0; i<ET_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
ET[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
//----------------------------------------------------------------
//one classVec list for each model
vector<vector<vector<double> > > RF_probVecs;
vector<vector<vector<double> > > ET_probVecs;
RF_probVecs.resize(RF_num);
for(int i=0; i<RF_num; i++)
{
RF_probVecs[i].resize(N);
}
ET_probVecs.resize(ET_num);
for(int i=0; i<ET_num; i++)
{
ET_probVecs[i].resize(N);
}
#pragma omp parallel for num_threads(n_threads)
for(int row_idx = 0; row_idx < N; row_idx++)
{
for(int i=0; i<RF_num; i++)
{
vector<TreeNode*> rootList = RF[i];
vector<double> & output_vector = RF_probVecs[i][row_idx];
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
}
for(int i=0; i<ET_num; i++)
{
vector<TreeNode*> rootList = ET[i];
vector<double> & output_vector = ET_probVecs[i][row_idx];
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
}
}
//merge
Column* y = data_set.col.back();
vector<vector<double> > merged_probVecs(N);
vector<string> merged_ylabels;
vector<vector<double> > avg_probVecs(N); //for training accuracy
for(int row_idx=0; row_idx<N; row_idx++)
{
vector<double> & cur = merged_probVecs[row_idx];
vector<double> & avg = avg_probVecs[row_idx];
avg.resize(y_classes.size(), 0.0);
for(int k=0; k<RF_num; k++)
{
vector<vector<double> > & vecs = RF_probVecs[k];
vector<double> & vec = vecs[row_idx];
cur.insert(cur.end(), vec.begin(), vec.end());
for(int j=0; j<vec.size(); j++) avg[j] += vec[j];
}
for(int k=0; k<ET_num; k++)
{
vector<vector<double> > & vecs = ET_probVecs[k];
vector<double> & vec = vecs[row_idx];
cur.insert(cur.end(), vec.begin(), vec.end());
for(int j=0; j<vec.size(); j++) avg[j] += vec[j];
}
string ytmp;
y->get(row_idx, &ytmp);
merged_ylabels.push_back(ytmp);
for(int j=0; j<avg.size(); j++) avg[j] /= (RF_num + ET_num);
}
// output to HDFS
string row_file = output_hdfs_dir;
row_file += "/rows_" + to_string(_my_rank);
//put_rows(row_file.c_str(), merged_probVecs, merged_ylabels); //no need as using models also reads columns like training models
put_cols(row_file.c_str(), merged_probVecs, merged_ylabels, output_col_factor);
//compute training accuracy
int N_correct = 0;
for(int i=0; i<N; i++)
{
string ytmp;
y->get(i, &ytmp);
size_t yid = ymap[ytmp];
vector<double> & cur = avg_probVecs[i];
double yprob = cur[yid];
bool is_max = true;
for(int j=0; j<cur.size(); j++)
{
if(cur[j] > yprob)
{
is_max = false;
break;
}
}
if(is_max) N_correct++;
}
if(_my_rank == MASTER_RANK)
{
for(int i=0; i<_num_workers; i++)
{
if(i != _my_rank)
{
int val;
MPI_Recv(&val, 1, MPI_INT, i, PLAN_CHANNEL, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
N_correct += val;
}
}
cout<<_my_rank<<": accuracy = "<<N_correct<<" / "<<_n_samples<<" = "<<((double)N_correct/_n_samples)<<endl;
}
else
{
MPI_Send(&N_correct, 1, MPI_INT, MASTER_RANK, PLAN_CHANNEL, MPI_COMM_WORLD);
}
// meta
if(_my_rank == 0)
{
string meta_file = output_hdfs_dir;
meta_file += "/meta.csv";
put_meta(meta_file.c_str(), merged_probVecs[0].size(), true);
}
// free models
for(int i=0; i<RF_num; i++) free_forest(RF[i]);
for(int i=0; i<ET_num; i++) free_forest(ET[i]);
}
void run_CFi(const WorkerParams ¶ms, int num_cols1, int col_factor1, const char* train_dir2, int num_cols2, int col_factor2, const char* hdfs_tree_dir) {
//as a practice, we will put train_dir1 as mgs-win-output, and train_dir2 as the previous CF output
assert(params.replicate < _num_workers); //otherwise, a machine will keep a column more than once
//note that only n-1 slaves are partitioning the data
vector<TreeConfig> configList; //only used my master
load_job_config(params.job_file_path.c_str()); //every worker loads job-config
if (_my_rank == MASTER_RANK)
load_tree_configs(params, configList);
//========== load metadata
vector<data_source> sources;
cserver.append_meta(train_file.c_str(), sources); // HDFS path
cserver.X.pop_back(); //remove y !!! this is needed for all but the last data source
cserver.append_meta(train_dir2, sources); // HDFS path
_num_columns = cserver.X.col.size();
data_source & dsrc = sources[0];
data_source & dsrc2 = sources[1];
//========== initialize dsrc
dsrc.set_params(num_cols1, col_factor1);
dsrc2.set_params(num_cols2, col_factor2);
init_column_group(sources, dsrc); // y is obtained from dsrc, not dsrc2
// get all non-y column IDs into "all_columns" //@@@@@@@@@@@@@@@@@
for (int j = 0; j < _num_columns; j++) {
if (j == y_index) {
continue;
}
all_columns.push_back(j);
}
//========== init treeConfigs
if (_my_rank == MASTER_RANK) {
// initialize columns of tree-configs
for (size_t i = 0; i < configList.size(); i++) {
TreeConfig &config = configList[i];
if (config.type == DECISION_TREE) {
config.column_distribution.resize(1);
config.rootList.resize(1);
config.column_distribution[0] = all_columns;
} else if (config.type == RANDOM_FOREST || config.type == EXTRA_TREES) {
config.column_distribution.resize(config.num_trees);
config.rootList.resize(config.num_trees);
int num_columns;
if(config.column_sample == 0) { // default setting with sqrt(_num_columns - 1)
num_columns = sqrt(_num_columns - 1);
} else if (config.column_sample < 0) {
num_columns = - config.column_sample;
assert(num_columns < _num_columns);
} else { // still a ratio
num_columns = (_num_columns - 1) * config.column_sample;
assert(num_columns > 0);
}
for (int tree_index = 0; tree_index < config.num_trees;
tree_index++) {
//config.column_distribution[tree_index].clear();
random_shuffle(num_columns,
config.column_distribution[tree_index]);
}
} else {
cout << "ERROR : Wrong type, type = " << config.type
<< ", File " << __FILE__ << ", Line " << __LINE__
<< endl;
exit(-1);
}
}
}
//========== check path + init
if (_my_rank == MASTER_RANK) {
// if (dirCheck(meta_file.c_str()) == -1) return; //deep forest is not using it
if (dirCheck(train_file.c_str()) == -1)
return;
}
//========== build mac_map
if (_my_rank == MASTER_RANK) {
mac_map.resize(GROUP_OF_COLUMNS);
if (params.column_assignment == MODE_ALL_COLUMNS) {
for (int i = 0; i < GROUP_OF_COLUMNS; i++) {
for (int j = 0; j < _num_workers; j++) {
if (j == MASTER_RANK) {
continue;
}
mac_map[i].push_back(j);
}
}
} else if (params.column_assignment == MODE_REPLICATE) {
//init min-heap
priority_queue<min_heap_entry> min_heap;
for (int i = 0; i < _num_workers; i++) {
if (i == MASTER_RANK) { //master is not serving data, to save bandwidth for control msgs
continue;
}
min_heap_entry en;
en.count = 0;
en.rank = i;
min_heap.push(en);
}
//assign:
//algo: each time assign k replicates of a column to lightest-loaded machines
for (int i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
vector<min_heap_entry> mins;
for (int j = 0; j < params.replicate; j++) {
mins.push_back(min_heap.top());
min_heap.pop();
}
for (size_t j = 0; j < mins.size(); j++) {
mac_map[i].push_back(mins[j].rank);
mins[j].count += group_size[i];
min_heap.push(mins[j]);
}
}
} else {
cout << "ERROR:: File = " << __FILE__ << ", Line = " << __LINE__
<< ": this column-assignment mode is not implemented yet"
<< endl;
exit(-1);
}
//bcast-send
masterBcast(mac_map); // blocking operation
} else {
slaveBcast(mac_map); // blocking operation
}
//========== load columns
if (_my_rank != MASTER_RANK) {
for (size_t i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
vector<int> &macs = mac_map[i];
auto it = find(macs.begin(), macs.end(), _my_rank);
if (it == macs.end()) { // can happen, column 'i' does not need to be loaded in _my_rank
continue;
}
cserver.load_column_group(group_in_src[i], * group_src[i]);
}
cserver.load_y_group(dsrc2); //load y from the last data_src
}
//==========
if (_my_rank == MASTER_RANK) {
deque_p<plan> plan_buffer;
queue<plan*> root_plan_buffer;
conmap2t<int, Task_Master*> task_table; // only for master
PlanQueue planQueue;
MasterRecver master_receiver(task_table, planQueue, plan_buffer);
if (_n_samples < subtree_D) {
create_root_subtree_plans(root_plan_buffer, configList);
} else {
create_root_col_split_plan(root_plan_buffer, configList);
}
auto start = chrono::system_clock::now();
run_master(planQueue, root_plan_buffer, plan_buffer, task_table);
auto end = chrono::system_clock::now();
auto train_time = chrono::duration_cast < chrono::milliseconds
> (end - start).count();
cout
<< "Training done... Now printing and deleting the tree, File = "
<< __FILE__ << ", Line = " << __LINE__ << endl;
//load test data (if specified)
if (!params.test_file_path.empty()) {
// loading test_set.csv and test_meta.csv
load_csv(params.test_file_path.c_str(),
params.test_meta_file.c_str(), test_set);
}
if (SAVE_TREE_HDFS) {
dirCheck(hdfs_tree_dir, true); //enable force
}
// print tree configs + accuracy results
for (size_t i = 0; i < configList.size(); i++) {
TreeConfig &treeConfig = configList[i];
cout << i << ": " << treeConfig.type
<< " (testing and) saving ... " << endl;
if (!params.test_file_path.empty()) {
if (treeConfig.IMPURITY_FUNC == IMPURITY_VARIANCE) {
double RMSE = calculate_RMSE(treeConfig.rootList,
test_set, y_index, INT_MAX);
cout << "RMSE found for Task " << i << " is : " << RMSE
<< endl << endl;
} else if (treeConfig.IMPURITY_FUNC == IMPURITY_ENTROPY
|| treeConfig.IMPURITY_FUNC == IMPURITY_GINI
|| treeConfig.IMPURITY_FUNC
== IMPURITY_CLASSIFICATION_ERROR) {
cout << "Accuracy found for Task " << i << " is : "
<< get_accuracy(test_set, treeConfig.rootList,
y_index, INT_MAX) << endl << endl;
} else {
cout << "ERROR : File = " << __FILE__ << ", Line = "
<< __LINE__ << endl;
exit(-1);
}
}
vector<TreeNode*> &rootList = treeConfig.rootList;
string tree_dir = job_dir;
if (SAVE_TREE) {
string tree_path = tree_dir + "/model_" + to_string(i);
save_forest(tree_path.c_str(), rootList);
}
if (SAVE_TREE_HDFS) {
string tree_path = hdfs_tree_dir;
tree_path += "/model_" + to_string(i);
save_forest_hdfs(tree_path.c_str(), rootList);
}
vector<vector<int>> &column_distribution =
treeConfig.column_distribution;
for (size_t root_idx = 0; root_idx < rootList.size();
root_idx++) {
if (PRINT_TREE) {
cout
<< "##################################################"
<< endl;
cout << "config : " << treeConfig.type
<< ", tree index = " << root_idx << endl;
cout
<< "##################################################"
<< endl;
cout << "Candidate Columns = ";
for (size_t columns_index = 0;
columns_index
< column_distribution[root_idx].size();
columns_index++) {
cout << column_distribution[root_idx][columns_index]
<< ", ";
}
cout << endl;
cout
<< "##################################################"
<< endl;
print_tree(rootList[root_idx]);
cout << endl << endl;
}
free_tree(rootList[root_idx], y_index, cserver.X);
}
}
cout
<< "...................................................................."
<< endl;
cout << "total train time = " << train_time << " milliseconds "
<< endl;
} else { // slaves
conque_p<Task_Slave> task_buf; // use by slave compers
conque_p<resp2master> send_buffer;
conmap2t<int, Task_Slave*> task_table;
RespQueue resp_queue;
ReqQueue req_queue;
ReqServer req_server(task_table, resp_queue, req_queue); // run on master, slave, serving remote data for sub_tree, row_indices (subtree and col_split)
SlaveSender slaveSender(send_buffer);
RespServer resp_server(task_table, task_buf, resp_queue);
// would run only on slaves
// since RespServer is the recv-side of data serving
vector<Comper*> compers(num_compers);
for (int i = 0; i < num_compers; i++) {
compers[i] = new Comper(task_buf, send_buffer, task_table);
}
while (global_end_label == false) {
bool computing = run_slave(req_queue, task_table, task_buf,
send_buffer);
if (!computing) {
usleep(STATUS_SYNC_TIME_GAP);
}
}
for (size_t i = 0; i < compers.size(); i++) {
delete compers[i];
}
}
#ifdef ASSERT
if (_my_rank == MASTER_RANK) {
bool isOk = true;
for (size_t i = 0; i < load_matrix.size(); i++) {
for (size_t j = 0; j < load_matrix[i].size(); j++) {
isOk = isOk && (load_matrix[i][j] == 0);
}
}
if (!isOk) {
for (size_t i = 0; i < load_matrix.size(); i++) {
for (size_t j = 0; j < load_matrix[i].size(); j++) {
cout << load_matrix[i][j] << ", ";
}
cout << endl;
}
}
assert(isOk); // todo
assert(tree_progress.active_trees() == 0);
}
#endif
// cout << "DEBUG: Terminating worker " << _my_rank << endl;
}
//program entry point
void convert_CFi(int RF_num, int ET_num, char* data_dir1, int num_features1, int input1_col_factor, char* data_dir2, int num_features2, int input2_col_factor,
int output_col_factor, const char* output_hdfs_dir, char* job_config_file, char* model_dir, int n_threads) {
//========== check path + init
if (_my_rank == MASTER_RANK) {
// if (dirCheck(meta_file.c_str()) == -1) return; //deep forest is not using it
if (dirCheck(data_dir1, output_hdfs_dir, true, true) == -1)
return;
if (dirCheck(data_dir2) == -1) return;
}
load_job_config(job_config_file);
//========== load metadata
vector<data_source> sources;
cserver.append_meta(data_dir1, sources); // HDFS path
cserver.X.pop_back(); //remove y !!! this is needed for all but the last data source
cserver.append_meta(data_dir2, sources); // HDFS path
_num_columns = cserver.X.col.size();
data_source & dsrc = sources[0];
data_source & dsrc2 = sources[1];
//========== initialize dsrc
dsrc.set_params(num_features1, input1_col_factor);
dsrc2.set_params(num_features2, input2_col_factor);
init_column_group(sources, dsrc); // y is obtained from dsrc, not dsrc2
//========== load columns
for (size_t i = 0; i < GROUP_OF_COLUMNS - 1; i++) { // -1 to not counting y
cserver.load_column_group_row_i(group_in_src[i], * group_src[i]);
}
cserver.load_y_group_row_i(dsrc2); //load y from the first data_src
//==========
Matrix & data_set = cserver.X;
int N = data_set.col[0]->size;
vector<vector<TreeNode*> > RF;
vector<vector<TreeNode*> > ET;
RF.resize(RF_num);
ET.resize(ET_num);
int model_id = 0;
for(int i=0; i<RF_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
RF[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
for(int i=0; i<ET_num; i++)
{
string path = model_dir;
path += "/model_" + to_string(model_id);
ET[i] = load_forest_hdfs(data_set, y_index, path.c_str());
model_id ++;
}
//----------------------------------------------------------------
//one classVec list for each model
vector<vector<vector<double> > > RF_probVecs;
vector<vector<vector<double> > > ET_probVecs;
RF_probVecs.resize(RF_num);
for(int i=0; i<RF_num; i++)
{
RF_probVecs[i].resize(N);
}
ET_probVecs.resize(ET_num);
for(int i=0; i<ET_num; i++)
{
ET_probVecs[i].resize(N);
}
#pragma omp parallel for num_threads(n_threads)
for(int row_idx = 0; row_idx < N; row_idx++)
{
for(int i=0; i<RF_num; i++)
{
vector<TreeNode*> rootList = RF[i];
vector<double> & output_vector = RF_probVecs[i][row_idx];
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
}
for(int i=0; i<ET_num; i++)
{
vector<TreeNode*> rootList = ET[i];
vector<double> & output_vector = ET_probVecs[i][row_idx];
predict_forest<string>(rootList, row_idx, output_vector, data_set, INT_MAX);
}
}
//merge
Column* y = data_set.col.back();
vector<vector<double> > merged_probVecs(N);
vector<string> merged_ylabels;
vector<vector<double> > avg_probVecs(N); //for training accuracy
for(int row_idx=0; row_idx<N; row_idx++)
{
vector<double> & cur = merged_probVecs[row_idx];
vector<double> & avg = avg_probVecs[row_idx];
avg.resize(y_classes.size(), 0.0);
for(int k=0; k<RF_num; k++)
{
vector<vector<double> > & vecs = RF_probVecs[k];
vector<double> & vec = vecs[row_idx];
cur.insert(cur.end(), vec.begin(), vec.end());
for(int j=0; j<vec.size(); j++) avg[j] += vec[j];
}
for(int k=0; k<ET_num; k++)
{
vector<vector<double> > & vecs = ET_probVecs[k];
vector<double> & vec = vecs[row_idx];
cur.insert(cur.end(), vec.begin(), vec.end());
for(int j=0; j<vec.size(); j++) avg[j] += vec[j];
}
string ytmp;
y->get(row_idx, &ytmp);
merged_ylabels.push_back(ytmp);
for(int j=0; j<avg.size(); j++) avg[j] /= (RF_num + ET_num);
}
// output to HDFS
string row_file = output_hdfs_dir;
row_file += "/rows_" + to_string(_my_rank);
// put_rows(row_file.c_str(), merged_probVecs, merged_ylabels); //no need as using models also reads columns like training models
put_cols(row_file.c_str(), merged_probVecs, merged_ylabels, output_col_factor);
//compute training accuracy
int N_correct = 0;
for(int i=0; i<N; i++)
{
string ytmp;
y->get(i, &ytmp);
size_t yid = ymap[ytmp];
vector<double> & cur = avg_probVecs[i];
double yprob = cur[yid];
bool is_max = true;
for(int j=0; j<cur.size(); j++)
{
if(cur[j] > yprob)
{
is_max = false;
break;
}
}
if(is_max) N_correct++;
}
if(_my_rank == MASTER_RANK)
{
for(int i=0; i<_num_workers; i++)
{
if(i != _my_rank)
{
int val;
MPI_Recv(&val, 1, MPI_INT, i, PLAN_CHANNEL, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
N_correct += val;
}
}
cout<<_my_rank<<": accuracy = "<<N_correct<<" / "<<_n_samples<<" = "<<((double)N_correct/_n_samples)<<endl;
}
else
{
MPI_Send(&N_correct, 1, MPI_INT, MASTER_RANK, PLAN_CHANNEL, MPI_COMM_WORLD);
}
// meta
if(_my_rank == 0)
{
string meta_file = output_hdfs_dir;
meta_file += "/meta.csv";
put_meta(meta_file.c_str(), merged_probVecs[0].size(), true);
}
// free models
for(int i=0; i<RF_num; i++) free_forest(RF[i]);
for(int i=0; i<ET_num; i++) free_forest(ET[i]);
}
};
#endif
|
distance.h | #pragma once
#include <utils.h>
#ifdef _WINDOWS
#include <immintrin.h>
#include <smmintrin.h>
#include <tmmintrin.h>
#include <intrin.h>
#else
#include <immintrin.h>
#endif
#include <cosine_similarity.h>
#include <iostream>
namespace {
static inline __m256 _mm256_mul_epi8(__m256i X, __m256i Y) {
__m256i zero = _mm256_setzero_si256();
__m256i sign_x = _mm256_cmpgt_epi8(zero, X);
__m256i sign_y = _mm256_cmpgt_epi8(zero, Y);
__m256i xlo = _mm256_unpacklo_epi8(X, sign_x);
__m256i xhi = _mm256_unpackhi_epi8(X, sign_x);
__m256i ylo = _mm256_unpacklo_epi8(Y, sign_y);
__m256i yhi = _mm256_unpackhi_epi8(Y, sign_y);
return _mm256_cvtepi32_ps(_mm256_add_epi32(_mm256_madd_epi16(xlo, ylo),
_mm256_madd_epi16(xhi, yhi)));
}
static inline __m256 _mm256_mul32_pi8(__m128i X, __m128i Y) {
__m256i xlo = _mm256_cvtepi8_epi16(X), ylo = _mm256_cvtepi8_epi16(Y);
return _mm256_blend_ps(_mm256_cvtepi32_ps(_mm256_madd_epi16(xlo, ylo)),
_mm256_setzero_ps(), 252);
}
static inline float _mm256_reduce_add_ps(__m256 x) {
/* ( x3+x7, x2+x6, x1+x5, x0+x4 ) */
const __m128 x128 =
_mm_add_ps(_mm256_extractf128_ps(x, 1), _mm256_castps256_ps128(x));
/* ( -, -, x1+x3+x5+x7, x0+x2+x4+x6 ) */
const __m128 x64 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128));
/* ( -, -, -, x0+x1+x2+x3+x4+x5+x6+x7 ) */
const __m128 x32 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55));
/* Conversion to float is a no-op on x86-64 */
return _mm_cvtss_f32(x32);
}
} // namespace
namespace diskann {
// enum Metric { L2 = 0, INNER_PRODUCT = 1, FAST_L2 = 2, PQ = 3 };
template<typename T>
class Distance {
public:
virtual float compare(const T *a, const T *b, unsigned length) const = 0;
virtual ~Distance() {
}
};
template<typename T>
class DistanceCosine : public Distance<T> {
float compare(const T *a, const T *b, unsigned length) const {
return diskann::compute_cosine_similarity<T>(a, b, length);
}
~DistanceCosine() {
}
};
class DistanceL2Int8 : public Distance<int8_t> {
public:
float compare(const int8_t *a, const int8_t *b, unsigned size) const {
int32_t result = 0;
#ifdef _WINDOWS
#ifdef USE_AVX2
__m256 r = _mm256_setzero_ps();
char * pX = (char *) a, *pY = (char *) b;
while (size >= 32) {
__m256i r1 = _mm256_subs_epi8(_mm256_loadu_si256((__m256i *) pX),
_mm256_loadu_si256((__m256i *) pY));
r = _mm256_add_ps(r, _mm256_mul_epi8(r1, r1));
pX += 32;
pY += 32;
size -= 32;
}
while (size > 0) {
__m128i r2 = _mm_subs_epi8(_mm_loadu_si128((__m128i *) pX),
_mm_loadu_si128((__m128i *) pY));
r = _mm256_add_ps(r, _mm256_mul32_pi8(r2, r2));
pX += 4;
pY += 4;
size -= 4;
}
r = _mm256_hadd_ps(_mm256_hadd_ps(r, r), r);
return r.m256_f32[0] + r.m256_f32[4];
#else
#pragma omp simd reduction(+ : result) // aligned(a, b : 8)
for (_s32 i = 0; i < (_s32) size; i++) {
result += ((int32_t)((int16_t) a[i] - (int16_t) b[i])) *
((int32_t)((int16_t) a[i] - (int16_t) b[i]));
}
return (float) result;
#endif
#else
#pragma omp simd reduction(+ : result) // aligned(a, b : 8)
for (_s32 i = 0; i < (_s32) size; i++) {
result += ((int32_t)((int16_t) a[i] - (int16_t) b[i])) *
((int32_t)((int16_t) a[i] - (int16_t) b[i]));
}
return (float) result;
#endif
}
~DistanceL2Int8() {
}
};
class DistanceL2UInt8 : public Distance<uint8_t> {
public:
float compare(const uint8_t *a, const uint8_t *b, unsigned size) const {
uint32_t result = 0;
#pragma omp simd reduction(+ : result) // aligned(a, b : 8)
for (_s32 i = 0; i < (_s32) size; i++) {
result += ((int32_t)((int16_t) a[i] - (int16_t) b[i])) *
((int32_t)((int16_t) a[i] - (int16_t) b[i]));
}
return (float) result;
}
~DistanceL2UInt8() {
}
};
class DistanceL2 : public Distance<float> {
public:
#ifndef _WINDOWS
float compare(const float *a, const float *b, unsigned size) const
__attribute__((hot)){
// a = (const float *) __builtin_assume_aligned(a, 32);
// b = (const float *) __builtin_assume_aligned(b, 32);
#else
float compare(const float *a, const float *b, unsigned size) const {
#endif
float result = 0;
#ifdef USE_AVX2
// assume size is divisible by 8
_u16 niters = size / 8;
__m256 sum = _mm256_setzero_ps();
for (_u16 j = 0; j < niters; j++) {
// scope is a[8j:8j+7], b[8j:8j+7]
// load a_vec
if (j < (niters - 1)) {
_mm_prefetch((char *) (a + 8 * (j + 1)), _MM_HINT_T0);
_mm_prefetch((char *) (b + 8 * (j + 1)), _MM_HINT_T0);
}
__m256 a_vec = _mm256_load_ps(a + 8 * j);
// load b_vec
__m256 b_vec = _mm256_load_ps(b + 8 * j);
// a_vec - b_vec
__m256 tmp_vec = _mm256_sub_ps(a_vec, b_vec);
/*
// (a_vec - b_vec)**2
__m256 tmp_vec2 = _mm256_mul_ps(tmp_vec, tmp_vec);
// accumulate sum
sum = _mm256_add_ps(sum, tmp_vec2);
*/
// sum = (tmp_vec**2) + sum
sum = _mm256_fmadd_ps(tmp_vec, tmp_vec, sum);
}
// horizontal add sum
result = _mm256_reduce_add_ps(sum);
#else
#ifndef _WINDOWS
#pragma omp simd reduction(+ : result) // aligned(a, b : 32)
#endif
for (_s32 i = 0; i < (_s32) size; i++) {
result += (a[i] - b[i]) * (a[i] - b[i]);
}
#endif
return result;
} ~DistanceL2() {
}
};
} // namespace diskann
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.