blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
405cba984f1af2900f30a5141c237a2d567c07b1 | f64462af1aaa8e9be719346f7a57f06e9b4bb984 | /Archive/C++/Data_Structure/Trees/traversal.cpp | ead2c7ecdbc68174065d534569c81130b25221a5 | [] | no_license | tushar-rishav/Algorithms | 4cc5f4b94b5c70d05cf06a5e4394bf2c2670286a | 51062dcdaa5287f457c251de59c8694463e01e99 | refs/heads/master | 2020-05-20T07:27:06.933182 | 2016-11-11T18:50:00 | 2016-11-11T19:33:23 | 40,429,054 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,357 | cpp | /*
Implementation of Preorder, Inorder, Postorder traversals in a Tree
*/
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
int key;
struct node* left;
struct node* right;
};
class Tree{
private:
node* root;
int node_count = 0;
public:
void insert(node**, int);
node** get_root();
void update_root(node** ptr);
void preorder(node**);
void inorder(node**);
void postorder(node**);
int search(node**, int);
};
node** Tree::get_root()
{
return &(this->root);
}
void Tree::update_root(node** ptr)
{
this->root = *ptr;
}
void Tree::insert(node** head, int item)
{
if(*head){
if((*head)->data > item)
this->insert(&(*head)->left, item);
else
this->insert(&(*head)->right, item);
}
else{
*head = new node; // create a new node to insert the value
(*head)->data = item;
(*head)->left = NULL;
(*head)->right = NULL;
this->node_count++;
(*head)->key = this->node_count;
printf("Node inserted with value : %d\n", item);
}
}
int Tree::search(node** head, int key)
{
if(!*(head))
return -1;
if(key == (*head)->data)
return (*head)->key;
else if(key > (*head)->data)
return (this->search(&((*head)->right),key));
else
return (this->search(&((*head)->left), key));
}
void Tree::preorder(node** head)
{
if(*head){
cout<< (*head)->data<<" ";
this->preorder(&((*head)->left));
this->preorder(&((*head)->right));
}
}
void Tree::inorder(node** head)
{
if(*head){
this->inorder(&((*head)->left));
cout<< (*head)->data<<" ";
this->inorder(&((*head)->right));
}
}
void Tree::postorder(node** head)
{
if(*head){
this->postorder(&((*head)->right));
this->postorder(&((*head)->left));
cout<< (*head)->data<<" ";
}
}
int main()
{
node* head = NULL;
Tree tree;
tree.insert(&head, 10);
tree.insert(&head, 4);
tree.insert(&head, 20);
tree.insert(&head, 30);
tree.insert(&head, 8);
tree.insert(&head, 23);
tree.insert(&head, 1);
tree.insert(&head, 21);
tree.update_root(&head);
tree.preorder(tree.get_root());
cout<<"\tPreorder"<<endl;
tree.inorder(tree.get_root());
cout<<"\tInorder"<<endl;
tree.postorder(tree.get_root());
cout<<"\tPostorder"<<endl;
cout<<"Enter an item to search\t";
int n;
cin>>n;
int pos = tree.search(tree.get_root(),n);
if(pos!=-1)
cout<<"\nFound at position "<<pos<<endl;
else
cout<<"\nNot Found\n";
return 0;
} | [
"tushar.rishav@gmail.com"
] | tushar.rishav@gmail.com |
deb96de62f026156485714813b96eecdc37e10c5 | ab964b34945e3f759818571daa65edde91287ec4 | /chapter2/2_2.cpp | e0265b85a821816be5203374fdbabbb841eb8094 | [] | no_license | wtfenfenmiao/zishuCode | bd53f9f5bfbe498008efecb9a7da8046dc4a8f51 | 11d1b2980c2a7824337c2b058c2e154633c1b164 | refs/heads/master | 2020-03-14T17:19:19.300374 | 2018-10-19T02:23:13 | 2018-10-19T02:23:13 | 131,716,561 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 479 | cpp | #include<stdio.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int count=0;
long long temp=n; //输入987654321程序会崩,然而这个987654321在10^9内,所以要加这一个,防止溢出
while(temp>1)
{
if(temp%2==1)
temp=3*temp+1;
else
temp/=2;
++count;
//printf("%d\n",temp); 调试用
}
printf("%d\n",count);
}
}
| [
"wtbupt@outlook.com"
] | wtbupt@outlook.com |
d4e5af009aa7b9c010bf82a389f97c3eba3532e4 | 003305cdacdb538de90cea987b5d85f12dbd73e0 | /BasicModule/inc/inc_det/svBase/sv_utils.h | cbd997e44da082bd370bd7d47993dbda7949feed | [] | no_license | github188/EC700IR | a1a66fc88b1256bb60ddb0ec0d33cd3386cf6a63 | d7976578c627d9eaa04078fbd7a48d4a211ae3a0 | refs/heads/master | 2021-01-17T14:01:31.259583 | 2016-05-13T02:28:04 | 2016-05-13T02:28:04 | 66,121,249 | 2 | 0 | null | 2016-08-20T01:02:58 | 2016-08-20T01:02:58 | null | GB18030 | C++ | false | false | 6,745 | h | /// @file
/// @brief 工具函数定义
/// @author liaoy
/// @date 2013/8/26 10:46:40
///
/// 修改说明:
/// [2013/8/26 10:46:40 liaoy] 最初版本
#pragma once
#include "sv_basetype.h"
#include "sv_error.h"
#include "sv_rect.h"
#include "sv_image.h"
#if SV_RUN_PLATFORM == SV_PLATFORM_WIN
#include <stdio.h>
#endif
namespace sv
{
/// 文本信息输出回调原型
typedef int (*TRACE_CALLBACK_TXT)(
const char* szInfo, ///< 字符串
int nLen ///< 字符串长度+1
);
/// 设置文本输出回调
void utSetTraceCallBack_TXT(
TRACE_CALLBACK_TXT hCallBack ///< 回调函数指针
);
/// 调试信息输出
/// @note 信息长度不能超过640字节
void utTrace(
char* szFmt, ///< 输出格式
...
);
/// 取得系统TICK毫秒数
/// @return 系统TICK毫秒数
SV_UINT32 utGetSystemTick();
/// 计时开始
#define TS(tag) SV_UINT32 nTime_##tag = sv::utGetSystemTick(); //
/// 计时结束
#define TE(tag) utTrace("%s: %d ms\n", #tag, sv::utGetSystemTick()-nTime_##tag); //
#define SAFE_DELETE(p) if(p) {delete p; p = NULL;}
/// 画竖线
SV_RESULT utMarkLine(
const SV_IMAGE* pImgSrc, ///< 源图像
int nLinePos, ///< 画线位置
SV_UINT8 nColor ///< 线颜色
);
/// 画框
SV_RESULT utMarkRect(
const SV_IMAGE* pImgSrc, ///< 源图像
const SV_RECT* pRect, ///< 画框位置
SV_UINT8 nColor ///< 框颜色
);
/// 保存灰度内存图
SV_RESULT utSaveGrayImage(
const SV_WCHAR* szPath, ///< 保存路径
const void* pImgBuf, ///< 图像数据
int nWidth, ///< 宽
int nHeight, ///< 高
int nStrideWidth ///< 内存扫描行宽
);
/// 保存灰度内存图
SV_RESULT utSaveGrayImage(
const char* szPath, ///< 保存路径
const void* pImgBuf, ///< 图像数据
int nWidth, ///< 宽
int nHeight, ///< 高
int nStrideWidth ///< 内存扫描行宽
);
/// 保存BMP图片
SV_RESULT utSaveImage(
const SV_WCHAR* szPath, ///< 保存路径
const SV_IMAGE* pImg ///< 源图像
);
/// 保存BMP图片
SV_RESULT utSaveImage(
const char* szPath, ///< 保存路径
const SV_IMAGE* pImg ///< 源图像
);
/// 保存JPEG图片,可支持GRAY和YUV422类型
SV_RESULT utSaveImage_Jpeg(
const SV_WCHAR* szPath, ///< 保存路径
const SV_IMAGE* pImg, ///< 源图像
int nQuality = 95 ///< 压缩质量
);
/// 保存JPEG图片,可支持GRAY和YUV422类型
SV_RESULT utSaveImage_Jpeg(
const char* szPath, ///< 保存路径
const SV_IMAGE* pImg, ///< 源图像
int nQuality = 95 ///< 压缩质量
);
/// 读取JPEG图片
/// @note 可通过pImg 传入
SV_RESULT utReadImage_Jpeg(
const SV_UINT8* pJpegDat, ///< JPEG数据
int nDatLen, ///< 数据长度
SV_IMAGE* pImg, ///< 解压后图像,只支持YUV422格式
int* pWidth, ///< 宽
int* pHeight ///< 高
);
#if SV_RUN_PLATFORM == SV_PLATFORM_WIN
/// 保存内存数据到文本文件
template<typename T>
SV_RESULT utMemDump(
const char* szDumpFile,
const T* pDat,
int nWidth,
int nHeight,
int nStride = -1
)
{
FILE* hFile = NULL;
fopen_s(&hFile, szDumpFile, "w");
if(hFile == NULL)
{
return RS_E_UNEXPECTED;
}
if(nStride == -1)
{
nStride = nWidth;
}
T* pLine = (T*)pDat;
for(int i = 0; i < nHeight; i++, pLine += nStride)
{
for(int j = 0; j < nWidth; j++)
{
fprintf(hFile, "%8.3f,", (float)pLine[j]);
}
fprintf(hFile, "\n");
}
fclose(hFile);
return RS_S_OK;
}
/// 读取文本文件到内存
template<typename T>
SV_RESULT utLoadMem(
const char* szMemFile,
T* pDat,
int nLen,
int* pWidth,
int* pHeight
)
{
if(pDat == NULL || pWidth == NULL || pHeight == NULL)
{
return RS_E_INVALIDARG;
}
*pWidth = 0;
*pHeight = 0;
FILE* hFile = NULL;
fopen_s(&hFile, szMemFile, "r");
if(hFile == NULL)
{
return RS_E_UNEXPECTED;
}
const int nMaxLen = 100000;
CMemAlloc cAlloc;
char* pLine = (char*)cAlloc.Alloc(nMaxLen * sizeof(char));
if(pLine == NULL)
{
return RS_E_UNEXPECTED;
}
SV_BOOL fLoadOK = TRUE;
int nReadCount = 0;
int nHeight = 0;
int nWidth = 0;
while(fgets(pLine, nMaxLen, hFile))
{
pLine[strlen(pLine) - 1] = '\0';
char* pTokNext = NULL;
int nLineWidth = 0;
char* pTok = strtok_s(pLine, ",", &pTokNext);
while(pTok)
{
if(nReadCount >= nLen)
{
fLoadOK = FALSE;
break;
}
pDat[nReadCount++] = (T)atof(pTok);
pTok = strtok_s(NULL, ",", &pTokNext);
nLineWidth++;
}
nWidth = SV_MAX(nWidth, nLineWidth);
nHeight++;
}
fclose(hFile);
if(!fLoadOK)
{
return RS_E_OUTOFMEMORY;
}
*pWidth = nWidth;
*pHeight = nHeight;
return RS_S_OK;
}
#else
template<typename T>
SV_RESULT utMemDump(
const char* szDumpFile,
const T* pDat,
int nWidth,
int nHeight,
int nStride = -1
)
{
return RS_E_NOTIMPL;
}
template<typename T>
SV_RESULT utLoadMem(
const char* szMemFile,
T* pDat,
int nLen,
int* pWidth,
int* pHeight
)
{
return RS_E_NOTIMPL;
}
#endif
} // sv
| [
"cangmu2007@163.com"
] | cangmu2007@163.com |
f51e1c30bf25999263f8ebdde857c058d67bb69f | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_repos_function_768_curl-7.41.0.cpp | dea17d6877dc420d4c5c9022265db5e6417b20dc | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | ParameterError str2double(double *val, const char *str)
{
if(str) {
char *endptr;
double num = strtod(str, &endptr);
if((endptr != str) && (endptr == str + strlen(str))) {
*val = num;
return PARAM_OK; /* Ok */
}
}
return PARAM_BAD_NUMERIC; /* badness */
} | [
"993273596@qq.com"
] | 993273596@qq.com |
74269d4d777545a89ceb113e15cb28beb3d10d63 | 503d6e66cd9d93cce8464a386aa8116013964e6d | /labs/WS01/Lab1/tools.h | 6044523207e200044f53df94d637a3740fa10526 | [] | no_license | Jegurfinkel/OOP244Term2 | baad2b1e0170e9ac3d133e590fd8d4739f2748fa | 1d82b40b6353887044cdec6aaf28bab338295085 | refs/heads/master | 2020-03-19T10:41:38.171503 | 2018-06-07T00:41:06 | 2018-06-07T00:41:06 | 136,393,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | h | /***********************************************************************
// OOP244 Workshop 1: Compiling modular source code
// File tools.h
// Version 1.0
// Date 2018/05/18
// Author Jeffrey Gurfinkel, jegurfinkel@myseneca.ca, 066364092
// Description
// provides tools
//
/////////////////////////////////////////////////////////////////
***********************************************************************/
#ifndef sict_tools_H
#define sict_tools_H
namespace sict {
// Displays the user interface menu
int menu();
// Performs a fool-proof integer entry
int getInt(int min, int max);
}
#endif | [
"jeffrey.gurfinkel@gmail.com"
] | jeffrey.gurfinkel@gmail.com |
39caad74672d16f08df0c68d95c48bcbd89885df | 55a565712300b73fa4cce94bdf4d275cbf7802af | /SEI/recapitulare/lab4/timers/timers/timersDlg.h | 53359218bc692f64850331295a110e667f38e127 | [] | no_license | scorpionipx/ETTIM1 | 18effb605c1f957ed43012db051a4e3d8c633aec | ff1348a0581b49e48ca034849f5cc738f5aa2839 | refs/heads/master | 2020-03-30T12:57:16.890238 | 2019-07-15T11:21:00 | 2019-07-15T11:21:00 | 151,249,532 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 766 | h | // timersDlg.h : header file
//
#pragma once
#include "afxwin.h"
// CtimersDlg dialog
class CtimersDlg : public CDialog
{
// Construction
public:
CtimersDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_TIMERS_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
#if defined(_DEVICE_RESOLUTION_AWARE) && !defined(WIN32_PLATFORM_WFSP)
afx_msg void OnSize(UINT /*nType*/, int /*cx*/, int /*cy*/);
#endif
DECLARE_MESSAGE_MAP()
public:
CEdit tb1;
CEdit tb2;
afx_msg void OnBnClickedButton1();
afx_msg void OnBnClickedButton2();
afx_msg void OnTimer(UINT_PTR nIDEvent);
};
| [
"scorpionipx@gmail.com"
] | scorpionipx@gmail.com |
5b6ca9d55259526271d3717381d147f60d9dc239 | 80a53fe88d258b48fcf94f4f1b16edcbdb091e1f | /TP2018/TP2018/T3/Z5/main.cpp | 8b9dcf168ee80b6f397532a1444179bf17bf1e4c | [] | no_license | MedinaKapo/Programming-tecniques | 1170d524bc96600c8bd2ab366bd7778ff3b79396 | 719f56eeeaf8d47b63f52d5e76297c895d7efe78 | refs/heads/main | 2023-05-06T14:55:40.015843 | 2021-06-01T08:58:03 | 2021-06-01T08:58:03 | 372,763,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,234 | cpp | //TP 2017/2018: Tutorijal 3, Zadatak 5
#include <iostream>
#include<deque>
using namespace std;
int Suma(int n)
{
int sum=0;
while(n!=0) {
sum+=n%10;
n/=10;
}
return sum;
}
deque<int>IzdvojiElemente(deque<int>d,bool vrijednost)
{
deque<int> vracam;
if(vrijednost==true) {
for(int i=d.size()-1; i>=0; i--) {
if(Suma(d.at(i))%2==0)vracam.push_front(d.at(i));
}
} else {
for(int i=d.size()-1; i>=0; i--) {
if(Suma(d.at(i))%2!=0)vracam.push_front(d.at(i));
}
}
return vracam;
}
int main ()
{
int br,n;
cout<<"Koliko zelite unijeti elemenata: ";
cin>>n;
if(n<=0) {
cout<<"Broj elemenata mora biti veci od 0!"<<endl;
return 0;
}
cout<<"Unesite elemente: ";
deque<int>a;
for(int i=0; i<n; i++) {
cin>>br;
a.push_back(br);
}
deque<int>b;
deque<int>c;
b=IzdvojiElemente(a,true);
c=IzdvojiElemente(a,false);
for(int i=0; i<b.size(); i++) {
if(i>0 && i<b.size())cout<<",";
cout<<b.at(i);
}
cout<<endl;
for(int i=0; i<c.size(); i++) {
if(i>0 && i<c.size())cout<<",";
cout<<c.at(i);
}
return 0;
}
| [
"mkapo2@etf.unsa.ba"
] | mkapo2@etf.unsa.ba |
c772f9050abb1517fbf04b037f440bda8996799b | 43b3dfe24ccd0f33878cb2bf630a9c8e4aecea66 | /level1/p07_encrypt_decrypt/encrypt_decrypt/main.cpp | 8690973b5519e2079f7a7bc3c0e72f4b763dd4fa | [
"MIT"
] | permissive | yanrui20/c2020-1 | 3c7f5286b5e42dc4a47245577f1d21d3778eb3e8 | 6f108b1b6a981ac9b12a9422f611f20fd45f7901 | refs/heads/master | 2021-01-16T05:10:41.193697 | 2020-03-18T15:34:10 | 2020-03-18T15:34:10 | 242,986,667 | 1 | 0 | MIT | 2020-02-25T11:46:28 | 2020-02-25T11:46:27 | null | GB18030 | C++ | false | false | 838 | cpp | #include <stdio.h>
#include "encrypt_decrypt.h"
int main(int argc, char* argv[])
{
int choice = -1;
// 循环 + 菜单
while (choice)
{
printf("程序菜单:\n");
printf("1)加密\n");
printf("2)解密\n");
printf("※其他输入将退出程序\n");
printf("请输入您的选择:");
if (scanf_s("%d", &choice) == 1)
{
//解决多余输入
while (getchar() != '\n')
continue;
switch (choice)
{
case 1: // 加密
encrypt();
break;
case 2: // 解密
decrypt();
break;
default: // 退出程序
choice = 0;
break;
}
}
else
choice = 0; // 用于退出程序
}
printf("感谢您的使用,再见!\n");
printf("※输入回车退出窗口\n");
while (getchar() != '\n')
continue;
return 0;
} | [
"1657066071@qq.com"
] | 1657066071@qq.com |
1a9f08fb09dcee59512c5725dc176e213ef82fe6 | 98ec42398374ef91666550255e4958be69820cae | /emilib/profiler.cpp | d98bddf3d8fafd5acbc4034febe33127192ffe50 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-public-domain-disclaimer"
] | permissive | Zabrane/emilib | fde23b7e00f345db7c8a9b4e5b390f686885eff6 | 0d90f4c0cd44813f6898b417bf3f4ef574a5b136 | refs/heads/master | 2022-04-23T10:52:29.257760 | 2020-04-23T10:13:57 | 2020-04-23T10:13:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,574 | cpp | // Created by Emil Ernerfeldt on 2014-05-22.
// Copyright (c) 2015 Emil Ernerfeldt. All rights reserved.
//
#include "profiler.hpp"
#include <loguru.hpp>
#ifdef __APPLE__
#include "TargetConditionals.h"
#endif
namespace profiler {
using namespace std;
using namespace std::chrono;
const bool OUTPUT_STALLS = false;
const char* FRAME_ID = "Frame";
// ------------------------------------------------------------------------
uint64_t now_ns()
{
using Clock = std::chrono::high_resolution_clock;
return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count();
}
template<typename T>
void encode_int(Stream& out_stream, T value)
{
out_stream.insert(out_stream.end(), (uint8_t*)&value, (uint8_t*)&value + sizeof(value));
}
void encode_time(Stream& out_stream)
{
encode_int(out_stream, now_ns());
}
void encode_string(Stream& out_stream, const char* str)
{
do { out_stream.push_back(*str); } while (*str++);
}
template<typename T>
T parse_int(const Stream& stream, size_t& io_offset)
{
CHECK_LE_F(io_offset + sizeof(T), stream.size());
auto result = *(const T*)&stream[io_offset];
io_offset += sizeof(T);
return result;
}
const char* parse_string(const Stream& stream, size_t& io_offset)
{
CHECK_LE_F(io_offset, stream.size());
const char* result = reinterpret_cast<const char*>(&stream[io_offset]);
while (stream[io_offset] != 0) {
++io_offset;
}
++io_offset;
return result;
}
std::string format(unsigned indent, const char* id, const char* extra, NanoSeconds ns)
{
auto indentation = std::string(4 * indent, ' ');
return loguru::strprintf("%10.3f ms:%s %s %s", ns / 1e6, indentation.c_str(), id, extra);
}
// ------------------------------------------------------------------------
boost::optional<Scope> parse_scope(const Stream& stream, size_t offset)
{
if (offset >= stream.size()) { return boost::none; }
if (stream[offset] != kScopeBegin) { return boost::none; }
++offset;
Scope scope;
scope.record.start_ns = parse_int<NanoSeconds>(stream, offset);
scope.record.id = parse_string(stream, offset);
scope.record.extra = parse_string(stream, offset);
const auto scope_size = parse_int<ScopeSize>(stream, offset);
if (scope_size == ScopeSize(-1))
{
// Scope started but never ended.
return boost::none;
}
scope.child_idx = offset;
scope.child_end_idx = offset + scope_size;
CHECK_LT_F(scope.child_end_idx, stream.size());
CHECK_EQ_F(stream[scope.child_end_idx], kScopeEnd);
auto next_idx = scope.child_end_idx + 1;
auto stop_ns = parse_int<NanoSeconds>(stream, next_idx);
CHECK_LE_F(scope.record.start_ns, stop_ns);
scope.record.duration_ns = stop_ns - scope.record.start_ns;
scope.next_idx = next_idx;
return scope;
}
std::vector<Scope> collectScopes(const Stream& stream, size_t offset)
{
std::vector<Scope> result;
while (auto scope = parse_scope(stream, offset))
{
result.push_back(*scope);
offset = scope->next_idx;
}
return result;
}
// ------------------------------------------------------------------------
NanoSeconds check_for_stalls(const Stream& stream, const Scope& scope, NanoSeconds stall_cutoff_ns, unsigned depth)
{
auto parent_ns = scope.record.duration_ns;
if (OUTPUT_STALLS && parent_ns > stall_cutoff_ns) {
LOG_S(INFO) << format(depth, scope.record.id, scope.record.extra, parent_ns);
// Process children:
NanoSeconds child_ns = 0;
size_t idx = scope.child_idx;
while (auto child = parse_scope(stream, idx)) {
child_ns += check_for_stalls(stream, *child, stall_cutoff_ns, depth + 1);
idx = child->next_idx;
}
CHECK_EQ_F(idx, scope.child_end_idx);
if (child_ns > stall_cutoff_ns) {
auto missing = parent_ns - child_ns;
if (missing > stall_cutoff_ns) {
LOG_S(INFO) << format(depth + 1, "* Unaccounted", "", missing);
}
}
}
return parent_ns;
}
// ------------------------------------------------------------------------
ProfilerMngr& ProfilerMngr::instance()
{
static ProfilerMngr s_profile_mngr;
return s_profile_mngr;
}
ProfilerMngr::ProfilerMngr()
{
set_stall_cutoff(0.010);
auto frame_str = std::to_string(_frame_counter);
_frame_offset = get_thread_profiler().start(FRAME_ID, frame_str.c_str());
}
void ProfilerMngr::set_stall_cutoff(double secs)
{
_stall_cutoff_ns = static_cast<NanoSeconds>(secs * 1e9);
}
void ProfilerMngr::update()
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
get_thread_profiler().stop(_frame_offset);
_frame_counter += 1;
for (const auto& p : _streams) {
ERROR_CONTEXT("thread name", p.second.thread_info.name.c_str());
size_t idx = 0;
while (auto scope = parse_scope(p.second.stream, idx)) {
check_for_stalls(p.second.stream, *scope, _stall_cutoff_ns, 0);
idx = scope->next_idx;
}
CHECK_EQ_F(idx, p.second.stream.size());
}
_last_frame.swap(_streams);
_streams.clear();
if (_first_frame.empty()) {
_first_frame = _last_frame;
}
auto frame_str = std::to_string(_frame_counter);
_frame_offset = get_thread_profiler().start(FRAME_ID, frame_str.c_str());
}
void ProfilerMngr::report(const ThreadInfo& thread_info, const Stream& stream)
{
std::lock_guard<std::recursive_mutex> lock(_mutex);
auto& thread_stream = _streams[thread_info.id];
thread_stream.thread_info = thread_info;
thread_stream.stream.insert(thread_stream.stream.end(),
stream.begin(), stream.end());
}
// ----------------------------------------------------------------------------
ThreadProfiler::ThreadProfiler()
: _start_time_ns(now_ns())
{
}
Offset ThreadProfiler::start(const char* id, const char* extra)
{
_depth += 1;
_stream.push_back(kScopeBegin);
encode_time(_stream);
encode_string(_stream, id);
encode_string(_stream, extra);
// Make room for writing size of this scope:
auto offset = _stream.size();
encode_int(_stream, ScopeSize(-1));
return offset;
}
void ThreadProfiler::stop(Offset start_offset)
{
CHECK_GT_F(_depth, 0u);
_depth -= 1;
auto skip = _stream.size() - (start_offset + sizeof(ScopeSize));
CHECK_LE_F(start_offset + sizeof(ScopeSize), _stream.size());
*reinterpret_cast<ScopeSize*>(&_stream[start_offset]) = static_cast<ScopeSize>(skip);
_stream.push_back(kScopeEnd);
encode_time(_stream);
if (_depth == 0) {
char thread_name[17];
loguru::get_thread_name(thread_name, sizeof(thread_name), false);
ThreadInfo thread_info {
std::this_thread::get_id(),
thread_name,
_start_time_ns
};
ProfilerMngr::instance().report(thread_info, _stream);
_stream.clear();
}
}
// ----------------------------------------------------------------------------
#if !defined(__APPLE__)
static thread_local ThreadProfiler thread_profiler_object;
ThreadProfiler& get_thread_profiler()
{
return thread_profiler_object;
}
#else // !thread_local
static pthread_once_t s_profiler_pthread_once = PTHREAD_ONCE_INIT;
static pthread_key_t s_profiler_pthread_key;
void free_thread_profiler(void* io_error_context)
{
delete reinterpret_cast<ThreadProfiler*>(io_error_context);
}
void profiler_make_pthread_key()
{
(void)pthread_key_create(&s_profiler_pthread_key, free_thread_profiler);
}
ThreadProfiler& get_thread_profiler()
{
(void)pthread_once(&s_profiler_pthread_once, profiler_make_pthread_key);
auto ec = reinterpret_cast<ThreadProfiler*>(pthread_getspecific(s_profiler_pthread_key));
if (ec == nullptr) {
ec = new ThreadProfiler();
(void)pthread_setspecific(s_profiler_pthread_key, ec);
}
return *ec;
}
#endif // !thread_local
// ----------------------------------------------------------------------------
} // namespace profiler
| [
"emilernerfeldt@gmail.com"
] | emilernerfeldt@gmail.com |
4de6bc276e05de90281a3a5ce0df422d6cba9499 | dae883ee037ad0680e8aff4936f4880be98acaee | /lib/CodeGen/SelectionDAG/DAGCombiner.cpp | 8f05c61a957f8b9e95e911e6cee21ffdf7116871 | [
"NCSA"
] | permissive | frankroeder/llvm_mpi_checks | 25af07d680f825fe2f0871abcd8658ffedcec4a7 | d1f6385f3739bd746329276822d42efb6385941c | refs/heads/master | 2021-07-01T00:50:27.308673 | 2017-09-21T20:30:07 | 2017-09-21T20:30:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632,278 | cpp | //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
// both before and after the DAG is legalized.
//
// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
// primarily intended to handle simplification opportunities that are implicit
// in the LLVM IR and exposed by the various codegen lowering phases.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGTargetInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include <algorithm>
using namespace llvm;
#define DEBUG_TYPE "dagcombine"
STATISTIC(NodesCombined , "Number of dag nodes combined");
STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
STATISTIC(SlicedLoads, "Number of load sliced");
namespace {
static cl::opt<bool>
CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
cl::desc("Enable DAG combiner's use of IR alias analysis"));
static cl::opt<bool>
UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
cl::desc("Enable DAG combiner's use of TBAA"));
#ifndef NDEBUG
static cl::opt<std::string>
CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
cl::desc("Only use DAG-combiner alias analysis in this"
" function"));
#endif
/// Hidden option to stress test load slicing, i.e., when this option
/// is enabled, load slicing bypasses most of its profitability guards.
static cl::opt<bool>
StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
cl::desc("Bypass the profitability model of load "
"slicing"),
cl::init(false));
static cl::opt<bool>
MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
cl::desc("DAG combiner may split indexing from loads"));
//------------------------------ DAGCombiner ---------------------------------//
class DAGCombiner {
SelectionDAG &DAG;
const TargetLowering &TLI;
CombineLevel Level;
CodeGenOpt::Level OptLevel;
bool LegalOperations;
bool LegalTypes;
bool ForCodeSize;
/// \brief Worklist of all of the nodes that need to be simplified.
///
/// This must behave as a stack -- new nodes to process are pushed onto the
/// back and when processing we pop off of the back.
///
/// The worklist will not contain duplicates but may contain null entries
/// due to nodes being deleted from the underlying DAG.
SmallVector<SDNode *, 64> Worklist;
/// \brief Mapping from an SDNode to its position on the worklist.
///
/// This is used to find and remove nodes from the worklist (by nulling
/// them) when they are deleted from the underlying DAG. It relies on
/// stable indices of nodes within the worklist.
DenseMap<SDNode *, unsigned> WorklistMap;
/// \brief Set of nodes which have been combined (at least once).
///
/// This is used to allow us to reliably add any operands of a DAG node
/// which have not yet been combined to the worklist.
SmallPtrSet<SDNode *, 32> CombinedNodes;
// AA - Used for DAG load/store alias analysis.
AliasAnalysis &AA;
/// When an instruction is simplified, add all users of the instruction to
/// the work lists because they might get more simplified now.
void AddUsersToWorklist(SDNode *N) {
for (SDNode *Node : N->uses())
AddToWorklist(Node);
}
/// Call the node-specific routine that folds each particular type of node.
SDValue visit(SDNode *N);
public:
/// Add to the worklist making sure its instance is at the back (next to be
/// processed.)
void AddToWorklist(SDNode *N) {
assert(N->getOpcode() != ISD::DELETED_NODE &&
"Deleted Node added to Worklist");
// Skip handle nodes as they can't usefully be combined and confuse the
// zero-use deletion strategy.
if (N->getOpcode() == ISD::HANDLENODE)
return;
if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
Worklist.push_back(N);
}
/// Remove all instances of N from the worklist.
void removeFromWorklist(SDNode *N) {
CombinedNodes.erase(N);
auto It = WorklistMap.find(N);
if (It == WorklistMap.end())
return; // Not in the worklist.
// Null out the entry rather than erasing it to avoid a linear operation.
Worklist[It->second] = nullptr;
WorklistMap.erase(It);
}
void deleteAndRecombine(SDNode *N);
bool recursivelyDeleteUnusedNodes(SDNode *N);
/// Replaces all uses of the results of one DAG node with new values.
SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
bool AddTo = true);
/// Replaces all uses of the results of one DAG node with new values.
SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
return CombineTo(N, &Res, 1, AddTo);
}
/// Replaces all uses of the results of one DAG node with new values.
SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
bool AddTo = true) {
SDValue To[] = { Res0, Res1 };
return CombineTo(N, To, 2, AddTo);
}
void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
private:
unsigned MaximumLegalStoreInBits;
/// Check the specified integer node value to see if it can be simplified or
/// if things it uses can be simplified by bit propagation.
/// If so, return true.
bool SimplifyDemandedBits(SDValue Op) {
unsigned BitWidth = Op.getScalarValueSizeInBits();
APInt Demanded = APInt::getAllOnesValue(BitWidth);
return SimplifyDemandedBits(Op, Demanded);
}
bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
bool CombineToPreIndexedLoadStore(SDNode *N);
bool CombineToPostIndexedLoadStore(SDNode *N);
SDValue SplitIndexingFromLoad(LoadSDNode *LD);
bool SliceUpLoad(SDNode *N);
/// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
/// load.
///
/// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
/// \param InVecVT type of the input vector to EVE with bitcasts resolved.
/// \param EltNo index of the vector element to load.
/// \param OriginalLoad load that EVE came from to be replaced.
/// \returns EVE on success SDValue() on failure.
SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
SDValue PromoteIntBinOp(SDValue Op);
SDValue PromoteIntShiftOp(SDValue Op);
SDValue PromoteExtend(SDValue Op);
bool PromoteLoad(SDValue Op);
void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, SDValue Trunc,
SDValue ExtLoad, const SDLoc &DL,
ISD::NodeType ExtType);
/// Call the node-specific routine that knows how to fold each
/// particular type of node. If that doesn't do anything, try the
/// target-specific DAG combines.
SDValue combine(SDNode *N);
// Visitation implementation - Implement dag node combining for different
// node types. The semantics are as follows:
// Return Value:
// SDValue.getNode() == 0 - No change was made
// SDValue.getNode() == N - N was replaced, is dead and has been handled.
// otherwise - N should be replaced by the returned Operand.
//
SDValue visitTokenFactor(SDNode *N);
SDValue visitMERGE_VALUES(SDNode *N);
SDValue visitADD(SDNode *N);
SDValue visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference);
SDValue visitSUB(SDNode *N);
SDValue visitADDC(SDNode *N);
SDValue visitUADDO(SDNode *N);
SDValue visitSUBC(SDNode *N);
SDValue visitUSUBO(SDNode *N);
SDValue visitADDE(SDNode *N);
SDValue visitSUBE(SDNode *N);
SDValue visitMUL(SDNode *N);
SDValue useDivRem(SDNode *N);
SDValue visitSDIV(SDNode *N);
SDValue visitUDIV(SDNode *N);
SDValue visitREM(SDNode *N);
SDValue visitMULHU(SDNode *N);
SDValue visitMULHS(SDNode *N);
SDValue visitSMUL_LOHI(SDNode *N);
SDValue visitUMUL_LOHI(SDNode *N);
SDValue visitSMULO(SDNode *N);
SDValue visitUMULO(SDNode *N);
SDValue visitIMINMAX(SDNode *N);
SDValue visitAND(SDNode *N);
SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
SDValue visitOR(SDNode *N);
SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
SDValue visitXOR(SDNode *N);
SDValue SimplifyVBinOp(SDNode *N);
SDValue visitSHL(SDNode *N);
SDValue visitSRA(SDNode *N);
SDValue visitSRL(SDNode *N);
SDValue visitRotate(SDNode *N);
SDValue visitABS(SDNode *N);
SDValue visitBSWAP(SDNode *N);
SDValue visitBITREVERSE(SDNode *N);
SDValue visitCTLZ(SDNode *N);
SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
SDValue visitCTTZ(SDNode *N);
SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
SDValue visitCTPOP(SDNode *N);
SDValue visitSELECT(SDNode *N);
SDValue visitVSELECT(SDNode *N);
SDValue visitSELECT_CC(SDNode *N);
SDValue visitSETCC(SDNode *N);
SDValue visitSETCCE(SDNode *N);
SDValue visitSIGN_EXTEND(SDNode *N);
SDValue visitZERO_EXTEND(SDNode *N);
SDValue visitANY_EXTEND(SDNode *N);
SDValue visitAssertZext(SDNode *N);
SDValue visitSIGN_EXTEND_INREG(SDNode *N);
SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N);
SDValue visitTRUNCATE(SDNode *N);
SDValue visitBITCAST(SDNode *N);
SDValue visitBUILD_PAIR(SDNode *N);
SDValue visitFADD(SDNode *N);
SDValue visitFSUB(SDNode *N);
SDValue visitFMUL(SDNode *N);
SDValue visitFMA(SDNode *N);
SDValue visitFDIV(SDNode *N);
SDValue visitFREM(SDNode *N);
SDValue visitFSQRT(SDNode *N);
SDValue visitFCOPYSIGN(SDNode *N);
SDValue visitSINT_TO_FP(SDNode *N);
SDValue visitUINT_TO_FP(SDNode *N);
SDValue visitFP_TO_SINT(SDNode *N);
SDValue visitFP_TO_UINT(SDNode *N);
SDValue visitFP_ROUND(SDNode *N);
SDValue visitFP_ROUND_INREG(SDNode *N);
SDValue visitFP_EXTEND(SDNode *N);
SDValue visitFNEG(SDNode *N);
SDValue visitFABS(SDNode *N);
SDValue visitFCEIL(SDNode *N);
SDValue visitFTRUNC(SDNode *N);
SDValue visitFFLOOR(SDNode *N);
SDValue visitFMINNUM(SDNode *N);
SDValue visitFMAXNUM(SDNode *N);
SDValue visitBRCOND(SDNode *N);
SDValue visitBR_CC(SDNode *N);
SDValue visitLOAD(SDNode *N);
SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
SDValue visitSTORE(SDNode *N);
SDValue visitINSERT_VECTOR_ELT(SDNode *N);
SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
SDValue visitBUILD_VECTOR(SDNode *N);
SDValue visitCONCAT_VECTORS(SDNode *N);
SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
SDValue visitVECTOR_SHUFFLE(SDNode *N);
SDValue visitSCALAR_TO_VECTOR(SDNode *N);
SDValue visitINSERT_SUBVECTOR(SDNode *N);
SDValue visitMLOAD(SDNode *N);
SDValue visitMSTORE(SDNode *N);
SDValue visitMGATHER(SDNode *N);
SDValue visitMSCATTER(SDNode *N);
SDValue visitFP_TO_FP16(SDNode *N);
SDValue visitFP16_TO_FP(SDNode *N);
SDValue visitFADDForFMACombine(SDNode *N);
SDValue visitFSUBForFMACombine(SDNode *N);
SDValue visitFMULForFMADistributiveCombine(SDNode *N);
SDValue XformToShuffleWithZero(SDNode *N);
SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue LHS,
SDValue RHS);
SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
SDValue foldSelectOfConstants(SDNode *N);
SDValue foldBinOpIntoSelect(SDNode *BO);
bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
SDValue N2, SDValue N3, ISD::CondCode CC,
bool NotExtCompare = false);
SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
SDValue N2, SDValue N3, ISD::CondCode CC);
SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
const SDLoc &DL);
SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
const SDLoc &DL, bool foldBooleans = true);
bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
SDValue &CC) const;
bool isOneUseSetCC(SDValue N) const;
SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
unsigned HiOp);
SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
SDValue CombineExtLoad(SDNode *N);
SDValue combineRepeatedFPDivisors(SDNode *N);
SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
SDValue BuildSDIV(SDNode *N);
SDValue BuildSDIVPow2(SDNode *N);
SDValue BuildUDIV(SDNode *N);
SDValue BuildLogBase2(SDValue Op, const SDLoc &DL);
SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags);
SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags, bool Recip);
SDValue buildSqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
SDNodeFlags *Flags, bool Reciprocal);
SDValue buildSqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
SDNodeFlags *Flags, bool Reciprocal);
SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
bool DemandHighBits = true);
SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
SDValue InnerPos, SDValue InnerNeg,
unsigned PosOpcode, unsigned NegOpcode,
const SDLoc &DL);
SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
SDValue MatchLoadCombine(SDNode *N);
SDValue ReduceLoadWidth(SDNode *N);
SDValue ReduceLoadOpStoreWidth(SDNode *N);
SDValue splitMergedValStore(StoreSDNode *ST);
SDValue TransformFPLoadStorePair(SDNode *N);
SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
SDValue reduceBuildVecToShuffle(SDNode *N);
SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
ArrayRef<int> VectorMask, SDValue VecIn1,
SDValue VecIn2, unsigned LeftIdx);
SDValue GetDemandedBits(SDValue V, const APInt &Mask);
/// Walk up chain skipping non-aliasing memory nodes,
/// looking for aliasing nodes and adding them to the Aliases vector.
void GatherAllAliases(SDNode *N, SDValue OriginalChain,
SmallVectorImpl<SDValue> &Aliases);
/// Return true if there is any possibility that the two addresses overlap.
bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
/// Walk up chain skipping non-aliasing memory nodes, looking for a better
/// chain (aliasing node.)
SDValue FindBetterChain(SDNode *N, SDValue Chain);
/// Try to replace a store and any possibly adjacent stores on
/// consecutive chains with better chains. Return true only if St is
/// replaced.
///
/// Notice that other chains may still be replaced even if the function
/// returns false.
bool findBetterNeighborChains(StoreSDNode *St);
/// Match "(X shl/srl V1) & V2" where V2 may not be present.
bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask);
/// Holds a pointer to an LSBaseSDNode as well as information on where it
/// is located in a sequence of memory operations connected by a chain.
struct MemOpLink {
MemOpLink(LSBaseSDNode *N, int64_t Offset)
: MemNode(N), OffsetFromBase(Offset) {}
// Ptr to the mem node.
LSBaseSDNode *MemNode;
// Offset from the base ptr.
int64_t OffsetFromBase;
};
/// This is a helper function for visitMUL to check the profitability
/// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
/// MulNode is the original multiply, AddNode is (add x, c1),
/// and ConstNode is c2.
bool isMulAddWithConstProfitable(SDNode *MulNode,
SDValue &AddNode,
SDValue &ConstNode);
/// This is a helper function for visitAND and visitZERO_EXTEND. Returns
/// true if the (and (load x) c) pattern matches an extload. ExtVT returns
/// the type of the loaded value to be extended. LoadedVT returns the type
/// of the original loaded value. NarrowLoad returns whether the load would
/// need to be narrowed in order to match.
bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
bool &NarrowLoad);
/// This is a helper function for MergeConsecutiveStores. When the source
/// elements of the consecutive stores are all constants or all extracted
/// vector elements, try to merge them into one larger store.
/// \return True if a merged store was created.
bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
EVT MemVT, unsigned NumStores,
bool IsConstantSrc, bool UseVector);
/// This is a helper function for MergeConsecutiveStores.
/// Stores that may be merged are placed in StoreNodes.
void getStoreMergeCandidates(StoreSDNode *St,
SmallVectorImpl<MemOpLink> &StoreNodes);
/// Helper function for MergeConsecutiveStores. Checks if
/// Candidate stores have indirect dependency through their
/// operands. \return True if safe to merge
bool checkMergeStoreCandidatesForDependencies(
SmallVectorImpl<MemOpLink> &StoreNodes);
/// Merge consecutive store operations into a wide store.
/// This optimization uses wide integers or vectors when possible.
/// \return number of stores that were merged into a merged store (the
/// affected nodes are stored as a prefix in \p StoreNodes).
bool MergeConsecutiveStores(StoreSDNode *N);
/// \brief Try to transform a truncation where C is a constant:
/// (trunc (and X, C)) -> (and (trunc X), (trunc C))
///
/// \p N needs to be a truncation and its first operand an AND. Other
/// requirements are checked by the function (e.g. that trunc is
/// single-use) and if missed an empty SDValue is returned.
SDValue distributeTruncateThroughAnd(SDNode *N);
public:
DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
: DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
MaximumLegalStoreInBits = 0;
for (MVT VT : MVT::all_valuetypes())
if (EVT(VT).isSimple() && VT != MVT::Other &&
TLI.isTypeLegal(EVT(VT)) &&
VT.getSizeInBits() >= MaximumLegalStoreInBits)
MaximumLegalStoreInBits = VT.getSizeInBits();
}
/// Runs the dag combiner on all nodes in the work list
void Run(CombineLevel AtLevel);
SelectionDAG &getDAG() const { return DAG; }
/// Returns a type large enough to hold any valid shift amount - before type
/// legalization these can be huge.
EVT getShiftAmountTy(EVT LHSTy) {
assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
if (LHSTy.isVector())
return LHSTy;
auto &DL = DAG.getDataLayout();
return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
: TLI.getPointerTy(DL);
}
/// This method returns true if we are running before type legalization or
/// if the specified VT is legal.
bool isTypeLegal(const EVT &VT) {
if (!LegalTypes) return true;
return TLI.isTypeLegal(VT);
}
/// Convenience wrapper around TargetLowering::getSetCCResultType
EVT getSetCCResultType(EVT VT) const {
return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
}
};
}
namespace {
/// This class is a DAGUpdateListener that removes any deleted
/// nodes from the worklist.
class WorklistRemover : public SelectionDAG::DAGUpdateListener {
DAGCombiner &DC;
public:
explicit WorklistRemover(DAGCombiner &dc)
: SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
void NodeDeleted(SDNode *N, SDNode *E) override {
DC.removeFromWorklist(N);
}
};
}
//===----------------------------------------------------------------------===//
// TargetLowering::DAGCombinerInfo implementation
//===----------------------------------------------------------------------===//
void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
((DAGCombiner*)DC)->AddToWorklist(N);
}
SDValue TargetLowering::DAGCombinerInfo::
CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
}
SDValue TargetLowering::DAGCombinerInfo::
CombineTo(SDNode *N, SDValue Res, bool AddTo) {
return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
}
SDValue TargetLowering::DAGCombinerInfo::
CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
}
void TargetLowering::DAGCombinerInfo::
CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
}
//===----------------------------------------------------------------------===//
// Helper Functions
//===----------------------------------------------------------------------===//
void DAGCombiner::deleteAndRecombine(SDNode *N) {
removeFromWorklist(N);
// If the operands of this node are only used by the node, they will now be
// dead. Make sure to re-visit them and recursively delete dead nodes.
for (const SDValue &Op : N->ops())
// For an operand generating multiple values, one of the values may
// become dead allowing further simplification (e.g. split index
// arithmetic from an indexed load).
if (Op->hasOneUse() || Op->getNumValues() > 1)
AddToWorklist(Op.getNode());
DAG.DeleteNode(N);
}
/// Return 1 if we can compute the negated form of the specified expression for
/// the same cost as the expression itself, or 2 if we can compute the negated
/// form more cheaply than the expression itself.
static char isNegatibleForFree(SDValue Op, bool LegalOperations,
const TargetLowering &TLI,
const TargetOptions *Options,
unsigned Depth = 0) {
// fneg is removable even if it has multiple uses.
if (Op.getOpcode() == ISD::FNEG) return 2;
// Don't allow anything with multiple uses.
if (!Op.hasOneUse()) return 0;
// Don't recurse exponentially.
if (Depth > 6) return 0;
switch (Op.getOpcode()) {
default: return false;
case ISD::ConstantFP: {
if (!LegalOperations)
return 1;
// Don't invert constant FP values after legalization unless the target says
// the negated constant is legal.
EVT VT = Op.getValueType();
return TLI.isOperationLegal(ISD::ConstantFP, VT) ||
TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT);
}
case ISD::FADD:
// FIXME: determine better conditions for this xform.
if (!Options->UnsafeFPMath) return 0;
// After operation legalization, it might not be legal to create new FSUBs.
if (LegalOperations &&
!TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
return 0;
// fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
Options, Depth + 1))
return V;
// fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Depth + 1);
case ISD::FSUB:
// We can't turn -(A-B) into B-A when we honor signed zeros.
if (!Options->NoSignedZerosFPMath &&
!Op.getNode()->getFlags()->hasNoSignedZeros())
return 0;
// fold (fneg (fsub A, B)) -> (fsub B, A)
return 1;
case ISD::FMUL:
case ISD::FDIV:
if (Options->HonorSignDependentRoundingFPMath()) return 0;
// fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
Options, Depth + 1))
return V;
return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Depth + 1);
case ISD::FP_EXTEND:
case ISD::FP_ROUND:
case ISD::FSIN:
return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Depth + 1);
}
}
/// If isNegatibleForFree returns true, return the newly negated expression.
static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
bool LegalOperations, unsigned Depth = 0) {
const TargetOptions &Options = DAG.getTarget().Options;
// fneg is removable even if it has multiple uses.
if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
// Don't allow anything with multiple uses.
assert(Op.hasOneUse() && "Unknown reuse!");
assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
const SDNodeFlags *Flags = Op.getNode()->getFlags();
switch (Op.getOpcode()) {
default: llvm_unreachable("Unknown code");
case ISD::ConstantFP: {
APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
V.changeSign();
return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
}
case ISD::FADD:
// FIXME: determine better conditions for this xform.
assert(Options.UnsafeFPMath);
// fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
DAG.getTargetLoweringInfo(), &Options, Depth+1))
return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
GetNegatedExpression(Op.getOperand(0), DAG,
LegalOperations, Depth+1),
Op.getOperand(1), Flags);
// fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
GetNegatedExpression(Op.getOperand(1), DAG,
LegalOperations, Depth+1),
Op.getOperand(0), Flags);
case ISD::FSUB:
// fold (fneg (fsub 0, B)) -> B
if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
if (N0CFP->isZero())
return Op.getOperand(1);
// fold (fneg (fsub A, B)) -> (fsub B, A)
return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Op.getOperand(1), Op.getOperand(0), Flags);
case ISD::FMUL:
case ISD::FDIV:
assert(!Options.HonorSignDependentRoundingFPMath());
// fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
DAG.getTargetLoweringInfo(), &Options, Depth+1))
return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
GetNegatedExpression(Op.getOperand(0), DAG,
LegalOperations, Depth+1),
Op.getOperand(1), Flags);
// fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Op.getOperand(0),
GetNegatedExpression(Op.getOperand(1), DAG,
LegalOperations, Depth+1), Flags);
case ISD::FP_EXTEND:
case ISD::FSIN:
return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
GetNegatedExpression(Op.getOperand(0), DAG,
LegalOperations, Depth+1));
case ISD::FP_ROUND:
return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
GetNegatedExpression(Op.getOperand(0), DAG,
LegalOperations, Depth+1),
Op.getOperand(1));
}
}
// APInts must be the same size for most operations, this helper
// function zero extends the shorter of the pair so that they match.
// We provide an Offset so that we can create bitwidths that won't overflow.
static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
LHS = LHS.zextOrSelf(Bits);
RHS = RHS.zextOrSelf(Bits);
}
// Return true if this node is a setcc, or is a select_cc
// that selects between the target values used for true and false, making it
// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
// the appropriate nodes based on the type of node we are checking. This
// simplifies life a bit for the callers.
bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
SDValue &CC) const {
if (N.getOpcode() == ISD::SETCC) {
LHS = N.getOperand(0);
RHS = N.getOperand(1);
CC = N.getOperand(2);
return true;
}
if (N.getOpcode() != ISD::SELECT_CC ||
!TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
!TLI.isConstFalseVal(N.getOperand(3).getNode()))
return false;
if (TLI.getBooleanContents(N.getValueType()) ==
TargetLowering::UndefinedBooleanContent)
return false;
LHS = N.getOperand(0);
RHS = N.getOperand(1);
CC = N.getOperand(4);
return true;
}
/// Return true if this is a SetCC-equivalent operation with only one use.
/// If this is true, it allows the users to invert the operation for free when
/// it is profitable to do so.
bool DAGCombiner::isOneUseSetCC(SDValue N) const {
SDValue N0, N1, N2;
if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
return true;
return false;
}
// \brief Returns the SDNode if it is a constant float BuildVector
// or constant float.
static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
if (isa<ConstantFPSDNode>(N))
return N.getNode();
if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
return N.getNode();
return nullptr;
}
// Determines if it is a constant integer or a build vector of constant
// integers (and undefs).
// Do not permit build vector implicit truncation.
static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
return !(Const->isOpaque() && NoOpaques);
if (N.getOpcode() != ISD::BUILD_VECTOR)
return false;
unsigned BitWidth = N.getScalarValueSizeInBits();
for (const SDValue &Op : N->op_values()) {
if (Op.isUndef())
continue;
ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
(Const->isOpaque() && NoOpaques))
return false;
}
return true;
}
// Determines if it is a constant null integer or a splatted vector of a
// constant null integer (with no undefs).
// Build vector implicit truncation is not an issue for null values.
static bool isNullConstantOrNullSplatConstant(SDValue N) {
if (ConstantSDNode *Splat = isConstOrConstSplat(N))
return Splat->isNullValue();
return false;
}
// Determines if it is a constant integer of one or a splatted vector of a
// constant integer of one (with no undefs).
// Do not permit build vector implicit truncation.
static bool isOneConstantOrOneSplatConstant(SDValue N) {
unsigned BitWidth = N.getScalarValueSizeInBits();
if (ConstantSDNode *Splat = isConstOrConstSplat(N))
return Splat->isOne() && Splat->getAPIntValue().getBitWidth() == BitWidth;
return false;
}
// Determines if it is a constant integer of all ones or a splatted vector of a
// constant integer of all ones (with no undefs).
// Do not permit build vector implicit truncation.
static bool isAllOnesConstantOrAllOnesSplatConstant(SDValue N) {
unsigned BitWidth = N.getScalarValueSizeInBits();
if (ConstantSDNode *Splat = isConstOrConstSplat(N))
return Splat->isAllOnesValue() &&
Splat->getAPIntValue().getBitWidth() == BitWidth;
return false;
}
// Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
// undef's.
static bool isAnyConstantBuildVector(const SDNode *N) {
return ISD::isBuildVectorOfConstantSDNodes(N) ||
ISD::isBuildVectorOfConstantFPSDNodes(N);
}
SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
SDValue N1) {
EVT VT = N0.getValueType();
if (N0.getOpcode() == Opc) {
if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
// reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
return SDValue();
}
if (N0.hasOneUse()) {
// reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
// use
SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
if (!OpNode.getNode())
return SDValue();
AddToWorklist(OpNode.getNode());
return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
}
}
}
if (N1.getOpcode() == Opc) {
if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
// reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
return SDValue();
}
if (N1.hasOneUse()) {
// reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one
// use
SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0));
if (!OpNode.getNode())
return SDValue();
AddToWorklist(OpNode.getNode());
return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
}
}
}
return SDValue();
}
SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
bool AddTo) {
assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
++NodesCombined;
DEBUG(dbgs() << "\nReplacing.1 ";
N->dump(&DAG);
dbgs() << "\nWith: ";
To[0].getNode()->dump(&DAG);
dbgs() << " and " << NumTo-1 << " other values\n");
for (unsigned i = 0, e = NumTo; i != e; ++i)
assert((!To[i].getNode() ||
N->getValueType(i) == To[i].getValueType()) &&
"Cannot combine value to value of different type!");
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesWith(N, To);
if (AddTo) {
// Push the new nodes and any users onto the worklist
for (unsigned i = 0, e = NumTo; i != e; ++i) {
if (To[i].getNode()) {
AddToWorklist(To[i].getNode());
AddUsersToWorklist(To[i].getNode());
}
}
}
// Finally, if the node is now dead, remove it from the graph. The node
// may not be dead if the replacement process recursively simplified to
// something else needing this node.
if (N->use_empty())
deleteAndRecombine(N);
return SDValue(N, 0);
}
void DAGCombiner::
CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
// Replace all uses. If any nodes become isomorphic to other nodes and
// are deleted, make sure to remove them from our worklist.
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
// Push the new node and any (possibly new) users onto the worklist.
AddToWorklist(TLO.New.getNode());
AddUsersToWorklist(TLO.New.getNode());
// Finally, if the node is now dead, remove it from the graph. The node
// may not be dead if the replacement process recursively simplified to
// something else needing this node.
if (TLO.Old.getNode()->use_empty())
deleteAndRecombine(TLO.Old.getNode());
}
/// Check the specified integer node value to see if it can be simplified or if
/// things it uses can be simplified by bit propagation. If so, return true.
bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
APInt KnownZero, KnownOne;
if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
return false;
// Revisit the node.
AddToWorklist(Op.getNode());
// Replace the old value with the new one.
++NodesCombined;
DEBUG(dbgs() << "\nReplacing.2 ";
TLO.Old.getNode()->dump(&DAG);
dbgs() << "\nWith: ";
TLO.New.getNode()->dump(&DAG);
dbgs() << '\n');
CommitTargetLoweringOpt(TLO);
return true;
}
void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
SDLoc DL(Load);
EVT VT = Load->getValueType(0);
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
DEBUG(dbgs() << "\nReplacing.9 ";
Load->dump(&DAG);
dbgs() << "\nWith: ";
Trunc.getNode()->dump(&DAG);
dbgs() << '\n');
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
deleteAndRecombine(Load);
AddToWorklist(Trunc.getNode());
}
SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
Replace = false;
SDLoc DL(Op);
if (ISD::isUNINDEXEDLoad(Op.getNode())) {
LoadSDNode *LD = cast<LoadSDNode>(Op);
EVT MemVT = LD->getMemoryVT();
ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
: ISD::EXTLOAD)
: LD->getExtensionType();
Replace = true;
return DAG.getExtLoad(ExtType, DL, PVT,
LD->getChain(), LD->getBasePtr(),
MemVT, LD->getMemOperand());
}
unsigned Opc = Op.getOpcode();
switch (Opc) {
default: break;
case ISD::AssertSext:
return DAG.getNode(ISD::AssertSext, DL, PVT,
SExtPromoteOperand(Op.getOperand(0), PVT),
Op.getOperand(1));
case ISD::AssertZext:
return DAG.getNode(ISD::AssertZext, DL, PVT,
ZExtPromoteOperand(Op.getOperand(0), PVT),
Op.getOperand(1));
case ISD::Constant: {
unsigned ExtOpc =
Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
return DAG.getNode(ExtOpc, DL, PVT, Op);
}
}
if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
return SDValue();
return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
}
SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
return SDValue();
EVT OldVT = Op.getValueType();
SDLoc DL(Op);
bool Replace = false;
SDValue NewOp = PromoteOperand(Op, PVT, Replace);
if (!NewOp.getNode())
return SDValue();
AddToWorklist(NewOp.getNode());
if (Replace)
ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
DAG.getValueType(OldVT));
}
SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
EVT OldVT = Op.getValueType();
SDLoc DL(Op);
bool Replace = false;
SDValue NewOp = PromoteOperand(Op, PVT, Replace);
if (!NewOp.getNode())
return SDValue();
AddToWorklist(NewOp.getNode());
if (Replace)
ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
}
/// Promote the specified integer binary operation if the target indicates it is
/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
/// i32 since i16 instructions are longer.
SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
if (!LegalOperations)
return SDValue();
EVT VT = Op.getValueType();
if (VT.isVector() || !VT.isInteger())
return SDValue();
// If operation type is 'undesirable', e.g. i16 on x86, consider
// promoting it.
unsigned Opc = Op.getOpcode();
if (TLI.isTypeDesirableForOp(Opc, VT))
return SDValue();
EVT PVT = VT;
// Consult target whether it is a good idea to promote this operation and
// what's the right type to promote it to.
if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
assert(PVT != VT && "Don't know what type to promote to!");
DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
bool Replace0 = false;
SDValue N0 = Op.getOperand(0);
SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
bool Replace1 = false;
SDValue N1 = Op.getOperand(1);
SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
SDLoc DL(Op);
SDValue RV =
DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
// New replace instances of N0 and N1
if (Replace0 && N0 && N0.getOpcode() != ISD::DELETED_NODE && NN0 &&
NN0.getOpcode() != ISD::DELETED_NODE) {
AddToWorklist(NN0.getNode());
ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
}
if (Replace1 && N1 && N1.getOpcode() != ISD::DELETED_NODE && NN1 &&
NN1.getOpcode() != ISD::DELETED_NODE) {
AddToWorklist(NN1.getNode());
ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
}
// Deal with Op being deleted.
if (Op && Op.getOpcode() != ISD::DELETED_NODE)
return RV;
}
return SDValue();
}
/// Promote the specified integer shift operation if the target indicates it is
/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
/// i32 since i16 instructions are longer.
SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
if (!LegalOperations)
return SDValue();
EVT VT = Op.getValueType();
if (VT.isVector() || !VT.isInteger())
return SDValue();
// If operation type is 'undesirable', e.g. i16 on x86, consider
// promoting it.
unsigned Opc = Op.getOpcode();
if (TLI.isTypeDesirableForOp(Opc, VT))
return SDValue();
EVT PVT = VT;
// Consult target whether it is a good idea to promote this operation and
// what's the right type to promote it to.
if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
assert(PVT != VT && "Don't know what type to promote to!");
DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
bool Replace = false;
SDValue N0 = Op.getOperand(0);
SDValue N1 = Op.getOperand(1);
if (Opc == ISD::SRA)
N0 = SExtPromoteOperand(N0, PVT);
else if (Opc == ISD::SRL)
N0 = ZExtPromoteOperand(N0, PVT);
else
N0 = PromoteOperand(N0, PVT, Replace);
if (!N0.getNode())
return SDValue();
SDLoc DL(Op);
SDValue RV =
DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
AddToWorklist(N0.getNode());
if (Replace)
ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
// Deal with Op being deleted.
if (Op && Op.getOpcode() != ISD::DELETED_NODE)
return RV;
}
return SDValue();
}
SDValue DAGCombiner::PromoteExtend(SDValue Op) {
if (!LegalOperations)
return SDValue();
EVT VT = Op.getValueType();
if (VT.isVector() || !VT.isInteger())
return SDValue();
// If operation type is 'undesirable', e.g. i16 on x86, consider
// promoting it.
unsigned Opc = Op.getOpcode();
if (TLI.isTypeDesirableForOp(Opc, VT))
return SDValue();
EVT PVT = VT;
// Consult target whether it is a good idea to promote this operation and
// what's the right type to promote it to.
if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
assert(PVT != VT && "Don't know what type to promote to!");
// fold (aext (aext x)) -> (aext x)
// fold (aext (zext x)) -> (zext x)
// fold (aext (sext x)) -> (sext x)
DEBUG(dbgs() << "\nPromoting ";
Op.getNode()->dump(&DAG));
return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
}
return SDValue();
}
bool DAGCombiner::PromoteLoad(SDValue Op) {
if (!LegalOperations)
return false;
if (!ISD::isUNINDEXEDLoad(Op.getNode()))
return false;
EVT VT = Op.getValueType();
if (VT.isVector() || !VT.isInteger())
return false;
// If operation type is 'undesirable', e.g. i16 on x86, consider
// promoting it.
unsigned Opc = Op.getOpcode();
if (TLI.isTypeDesirableForOp(Opc, VT))
return false;
EVT PVT = VT;
// Consult target whether it is a good idea to promote this operation and
// what's the right type to promote it to.
if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
assert(PVT != VT && "Don't know what type to promote to!");
SDLoc DL(Op);
SDNode *N = Op.getNode();
LoadSDNode *LD = cast<LoadSDNode>(N);
EVT MemVT = LD->getMemoryVT();
ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
: ISD::EXTLOAD)
: LD->getExtensionType();
SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
LD->getChain(), LD->getBasePtr(),
MemVT, LD->getMemOperand());
SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
DEBUG(dbgs() << "\nPromoting ";
N->dump(&DAG);
dbgs() << "\nTo: ";
Result.getNode()->dump(&DAG);
dbgs() << '\n');
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
deleteAndRecombine(N);
AddToWorklist(Result.getNode());
return true;
}
return false;
}
/// \brief Recursively delete a node which has no uses and any operands for
/// which it is the only use.
///
/// Note that this both deletes the nodes and removes them from the worklist.
/// It also adds any nodes who have had a user deleted to the worklist as they
/// may now have only one use and subject to other combines.
bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
if (!N->use_empty())
return false;
SmallSetVector<SDNode *, 16> Nodes;
Nodes.insert(N);
do {
N = Nodes.pop_back_val();
if (!N)
continue;
if (N->use_empty()) {
for (const SDValue &ChildN : N->op_values())
Nodes.insert(ChildN.getNode());
removeFromWorklist(N);
DAG.DeleteNode(N);
} else {
AddToWorklist(N);
}
} while (!Nodes.empty());
return true;
}
//===----------------------------------------------------------------------===//
// Main DAG Combiner implementation
//===----------------------------------------------------------------------===//
void DAGCombiner::Run(CombineLevel AtLevel) {
// set the instance variables, so that the various visit routines may use it.
Level = AtLevel;
LegalOperations = Level >= AfterLegalizeVectorOps;
LegalTypes = Level >= AfterLegalizeTypes;
// Add all the dag nodes to the worklist.
for (SDNode &Node : DAG.allnodes())
AddToWorklist(&Node);
// Create a dummy node (which is not added to allnodes), that adds a reference
// to the root node, preventing it from being deleted, and tracking any
// changes of the root.
HandleSDNode Dummy(DAG.getRoot());
// While the worklist isn't empty, find a node and try to combine it.
while (!WorklistMap.empty()) {
SDNode *N;
// The Worklist holds the SDNodes in order, but it may contain null entries.
do {
N = Worklist.pop_back_val();
} while (!N);
bool GoodWorklistEntry = WorklistMap.erase(N);
(void)GoodWorklistEntry;
assert(GoodWorklistEntry &&
"Found a worklist entry without a corresponding map entry!");
// If N has no uses, it is dead. Make sure to revisit all N's operands once
// N is deleted from the DAG, since they too may now be dead or may have a
// reduced number of uses, allowing other xforms.
if (recursivelyDeleteUnusedNodes(N))
continue;
WorklistRemover DeadNodes(*this);
// If this combine is running after legalizing the DAG, re-legalize any
// nodes pulled off the worklist.
if (Level == AfterLegalizeDAG) {
SmallSetVector<SDNode *, 16> UpdatedNodes;
bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
for (SDNode *LN : UpdatedNodes) {
AddToWorklist(LN);
AddUsersToWorklist(LN);
}
if (!NIsValid)
continue;
}
DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
// Add any operands of the new node which have not yet been combined to the
// worklist as well. Because the worklist uniques things already, this
// won't repeatedly process the same operand.
CombinedNodes.insert(N);
for (const SDValue &ChildN : N->op_values())
if (!CombinedNodes.count(ChildN.getNode()))
AddToWorklist(ChildN.getNode());
SDValue RV = combine(N);
if (!RV.getNode())
continue;
++NodesCombined;
// If we get back the same node we passed in, rather than a new node or
// zero, we know that the node must have defined multiple values and
// CombineTo was used. Since CombineTo takes care of the worklist
// mechanics for us, we have no work to do in this case.
if (RV.getNode() == N)
continue;
assert(N->getOpcode() != ISD::DELETED_NODE &&
RV.getOpcode() != ISD::DELETED_NODE &&
"Node was deleted but visit returned new node!");
DEBUG(dbgs() << " ... into: ";
RV.getNode()->dump(&DAG));
if (N->getNumValues() == RV.getNode()->getNumValues())
DAG.ReplaceAllUsesWith(N, RV.getNode());
else {
assert(N->getValueType(0) == RV.getValueType() &&
N->getNumValues() == 1 && "Type mismatch");
DAG.ReplaceAllUsesWith(N, &RV);
}
// Push the new node and any users onto the worklist
AddToWorklist(RV.getNode());
AddUsersToWorklist(RV.getNode());
// Finally, if the node is now dead, remove it from the graph. The node
// may not be dead if the replacement process recursively simplified to
// something else needing this node. This will also take care of adding any
// operands which have lost a user to the worklist.
recursivelyDeleteUnusedNodes(N);
}
// If the root changed (e.g. it was a dead load, update the root).
DAG.setRoot(Dummy.getValue());
DAG.RemoveDeadNodes();
}
SDValue DAGCombiner::visit(SDNode *N) {
switch (N->getOpcode()) {
default: break;
case ISD::TokenFactor: return visitTokenFactor(N);
case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
case ISD::ADD: return visitADD(N);
case ISD::SUB: return visitSUB(N);
case ISD::ADDC: return visitADDC(N);
case ISD::UADDO: return visitUADDO(N);
case ISD::SUBC: return visitSUBC(N);
case ISD::USUBO: return visitUSUBO(N);
case ISD::ADDE: return visitADDE(N);
case ISD::SUBE: return visitSUBE(N);
case ISD::MUL: return visitMUL(N);
case ISD::SDIV: return visitSDIV(N);
case ISD::UDIV: return visitUDIV(N);
case ISD::SREM:
case ISD::UREM: return visitREM(N);
case ISD::MULHU: return visitMULHU(N);
case ISD::MULHS: return visitMULHS(N);
case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
case ISD::SMULO: return visitSMULO(N);
case ISD::UMULO: return visitUMULO(N);
case ISD::SMIN:
case ISD::SMAX:
case ISD::UMIN:
case ISD::UMAX: return visitIMINMAX(N);
case ISD::AND: return visitAND(N);
case ISD::OR: return visitOR(N);
case ISD::XOR: return visitXOR(N);
case ISD::SHL: return visitSHL(N);
case ISD::SRA: return visitSRA(N);
case ISD::SRL: return visitSRL(N);
case ISD::ROTR:
case ISD::ROTL: return visitRotate(N);
case ISD::ABS: return visitABS(N);
case ISD::BSWAP: return visitBSWAP(N);
case ISD::BITREVERSE: return visitBITREVERSE(N);
case ISD::CTLZ: return visitCTLZ(N);
case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
case ISD::CTTZ: return visitCTTZ(N);
case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
case ISD::CTPOP: return visitCTPOP(N);
case ISD::SELECT: return visitSELECT(N);
case ISD::VSELECT: return visitVSELECT(N);
case ISD::SELECT_CC: return visitSELECT_CC(N);
case ISD::SETCC: return visitSETCC(N);
case ISD::SETCCE: return visitSETCCE(N);
case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
case ISD::AssertZext: return visitAssertZext(N);
case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N);
case ISD::TRUNCATE: return visitTRUNCATE(N);
case ISD::BITCAST: return visitBITCAST(N);
case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
case ISD::FADD: return visitFADD(N);
case ISD::FSUB: return visitFSUB(N);
case ISD::FMUL: return visitFMUL(N);
case ISD::FMA: return visitFMA(N);
case ISD::FDIV: return visitFDIV(N);
case ISD::FREM: return visitFREM(N);
case ISD::FSQRT: return visitFSQRT(N);
case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
case ISD::FP_ROUND: return visitFP_ROUND(N);
case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
case ISD::FP_EXTEND: return visitFP_EXTEND(N);
case ISD::FNEG: return visitFNEG(N);
case ISD::FABS: return visitFABS(N);
case ISD::FFLOOR: return visitFFLOOR(N);
case ISD::FMINNUM: return visitFMINNUM(N);
case ISD::FMAXNUM: return visitFMAXNUM(N);
case ISD::FCEIL: return visitFCEIL(N);
case ISD::FTRUNC: return visitFTRUNC(N);
case ISD::BRCOND: return visitBRCOND(N);
case ISD::BR_CC: return visitBR_CC(N);
case ISD::LOAD: return visitLOAD(N);
case ISD::STORE: return visitSTORE(N);
case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
case ISD::MGATHER: return visitMGATHER(N);
case ISD::MLOAD: return visitMLOAD(N);
case ISD::MSCATTER: return visitMSCATTER(N);
case ISD::MSTORE: return visitMSTORE(N);
case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
}
return SDValue();
}
SDValue DAGCombiner::combine(SDNode *N) {
SDValue RV = visit(N);
// If nothing happened, try a target-specific DAG combine.
if (!RV.getNode()) {
assert(N->getOpcode() != ISD::DELETED_NODE &&
"Node was deleted but visit returned NULL!");
if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
// Expose the DAG combiner to the target combiner impls.
TargetLowering::DAGCombinerInfo
DagCombineInfo(DAG, Level, false, this);
RV = TLI.PerformDAGCombine(N, DagCombineInfo);
}
}
// If nothing happened still, try promoting the operation.
if (!RV.getNode()) {
switch (N->getOpcode()) {
default: break;
case ISD::ADD:
case ISD::SUB:
case ISD::MUL:
case ISD::AND:
case ISD::OR:
case ISD::XOR:
RV = PromoteIntBinOp(SDValue(N, 0));
break;
case ISD::SHL:
case ISD::SRA:
case ISD::SRL:
RV = PromoteIntShiftOp(SDValue(N, 0));
break;
case ISD::SIGN_EXTEND:
case ISD::ZERO_EXTEND:
case ISD::ANY_EXTEND:
RV = PromoteExtend(SDValue(N, 0));
break;
case ISD::LOAD:
if (PromoteLoad(SDValue(N, 0)))
RV = SDValue(N, 0);
break;
}
}
// If N is a commutative binary node, try commuting it to enable more
// sdisel CSE.
if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
N->getNumValues() == 1) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
// Constant operands are canonicalized to RHS.
if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
SDValue Ops[] = {N1, N0};
SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
N->getFlags());
if (CSENode)
return SDValue(CSENode, 0);
}
}
return RV;
}
/// Given a node, return its input chain if it has one, otherwise return a null
/// sd operand.
static SDValue getInputChainForNode(SDNode *N) {
if (unsigned NumOps = N->getNumOperands()) {
if (N->getOperand(0).getValueType() == MVT::Other)
return N->getOperand(0);
if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
return N->getOperand(NumOps-1);
for (unsigned i = 1; i < NumOps-1; ++i)
if (N->getOperand(i).getValueType() == MVT::Other)
return N->getOperand(i);
}
return SDValue();
}
SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
// If N has two operands, where one has an input chain equal to the other,
// the 'other' chain is redundant.
if (N->getNumOperands() == 2) {
if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
return N->getOperand(0);
if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
return N->getOperand(1);
}
SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
SmallPtrSet<SDNode*, 16> SeenOps;
bool Changed = false; // If we should replace this token factor.
// Start out with this token factor.
TFs.push_back(N);
// Iterate through token factors. The TFs grows when new token factors are
// encountered.
for (unsigned i = 0; i < TFs.size(); ++i) {
SDNode *TF = TFs[i];
// Check each of the operands.
for (const SDValue &Op : TF->op_values()) {
switch (Op.getOpcode()) {
case ISD::EntryToken:
// Entry tokens don't need to be added to the list. They are
// redundant.
Changed = true;
break;
case ISD::TokenFactor:
if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
// Queue up for processing.
TFs.push_back(Op.getNode());
// Clean up in case the token factor is removed.
AddToWorklist(Op.getNode());
Changed = true;
break;
}
LLVM_FALLTHROUGH;
default:
// Only add if it isn't already in the list.
if (SeenOps.insert(Op.getNode()).second)
Ops.push_back(Op);
else
Changed = true;
break;
}
}
}
// Remove Nodes that are chained to another node in the list. Do so
// by walking up chains breath-first stopping when we've seen
// another operand. In general we must climb to the EntryNode, but we can exit
// early if we find all remaining work is associated with just one operand as
// no further pruning is possible.
// List of nodes to search through and original Ops from which they originate.
SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
SmallPtrSet<SDNode *, 16> SeenChains;
bool DidPruneOps = false;
unsigned NumLeftToConsider = 0;
for (const SDValue &Op : Ops) {
Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
OpWorkCount.push_back(1);
}
auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
// If this is an Op, we can remove the op from the list. Remark any
// search associated with it as from the current OpNumber.
if (SeenOps.count(Op) != 0) {
Changed = true;
DidPruneOps = true;
unsigned OrigOpNumber = 0;
while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
OrigOpNumber++;
assert((OrigOpNumber != Ops.size()) &&
"expected to find TokenFactor Operand");
// Re-mark worklist from OrigOpNumber to OpNumber
for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
if (Worklist[i].second == OrigOpNumber) {
Worklist[i].second = OpNumber;
}
}
OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
OpWorkCount[OrigOpNumber] = 0;
NumLeftToConsider--;
}
// Add if it's a new chain
if (SeenChains.insert(Op).second) {
OpWorkCount[OpNumber]++;
Worklist.push_back(std::make_pair(Op, OpNumber));
}
};
for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
// We need at least be consider at least 2 Ops to prune.
if (NumLeftToConsider <= 1)
break;
auto CurNode = Worklist[i].first;
auto CurOpNumber = Worklist[i].second;
assert((OpWorkCount[CurOpNumber] > 0) &&
"Node should not appear in worklist");
switch (CurNode->getOpcode()) {
case ISD::EntryToken:
// Hitting EntryToken is the only way for the search to terminate without
// hitting
// another operand's search. Prevent us from marking this operand
// considered.
NumLeftToConsider++;
break;
case ISD::TokenFactor:
for (const SDValue &Op : CurNode->op_values())
AddToWorklist(i, Op.getNode(), CurOpNumber);
break;
case ISD::CopyFromReg:
case ISD::CopyToReg:
AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
break;
default:
if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
break;
}
OpWorkCount[CurOpNumber]--;
if (OpWorkCount[CurOpNumber] == 0)
NumLeftToConsider--;
}
SDValue Result;
// If we've changed things around then replace token factor.
if (Changed) {
if (Ops.empty()) {
// The entry token is the only possible outcome.
Result = DAG.getEntryNode();
} else {
if (DidPruneOps) {
SmallVector<SDValue, 8> PrunedOps;
//
for (const SDValue &Op : Ops) {
if (SeenChains.count(Op.getNode()) == 0)
PrunedOps.push_back(Op);
}
Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, PrunedOps);
} else {
Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
}
}
// Add users to worklist, since we may introduce a lot of new
// chained token factors while removing memory deps.
return CombineTo(N, Result, true /*add to worklist*/);
}
return Result;
}
/// MERGE_VALUES can always be eliminated.
SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
WorklistRemover DeadNodes(*this);
// Replacing results may cause a different MERGE_VALUES to suddenly
// be CSE'd with N, and carry its uses with it. Iterate until no
// uses remain, to ensure that the node can be safely deleted.
// First add the users of this node to the work list so that they
// can be tried again once they have new operands.
AddUsersToWorklist(N);
do {
for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
} while (!N->use_empty());
deleteAndRecombine(N);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
/// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
/// ConstantSDNode pointer else nullptr.
static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
}
SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
auto BinOpcode = BO->getOpcode();
assert((BinOpcode == ISD::ADD || BinOpcode == ISD::SUB ||
BinOpcode == ISD::MUL || BinOpcode == ISD::SDIV ||
BinOpcode == ISD::UDIV || BinOpcode == ISD::SREM ||
BinOpcode == ISD::UREM || BinOpcode == ISD::AND ||
BinOpcode == ISD::OR || BinOpcode == ISD::XOR ||
BinOpcode == ISD::SHL || BinOpcode == ISD::SRL ||
BinOpcode == ISD::SRA || BinOpcode == ISD::FADD ||
BinOpcode == ISD::FSUB || BinOpcode == ISD::FMUL ||
BinOpcode == ISD::FDIV || BinOpcode == ISD::FREM) &&
"Unexpected binary operator");
// Bail out if any constants are opaque because we can't constant fold those.
SDValue C1 = BO->getOperand(1);
if (!isConstantOrConstantVector(C1, true) &&
!isConstantFPBuildVectorOrConstantFP(C1))
return SDValue();
// Don't do this unless the old select is going away. We want to eliminate the
// binary operator, not replace a binop with a select.
// TODO: Handle ISD::SELECT_CC.
SDValue Sel = BO->getOperand(0);
if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
return SDValue();
SDValue CT = Sel.getOperand(1);
if (!isConstantOrConstantVector(CT, true) &&
!isConstantFPBuildVectorOrConstantFP(CT))
return SDValue();
SDValue CF = Sel.getOperand(2);
if (!isConstantOrConstantVector(CF, true) &&
!isConstantFPBuildVectorOrConstantFP(CF))
return SDValue();
// We have a select-of-constants followed by a binary operator with a
// constant. Eliminate the binop by pulling the constant math into the select.
// Example: add (select Cond, CT, CF), C1 --> select Cond, CT + C1, CF + C1
EVT VT = Sel.getValueType();
SDLoc DL(Sel);
SDValue NewCT = DAG.getNode(BinOpcode, DL, VT, CT, C1);
assert((NewCT.isUndef() || isConstantOrConstantVector(NewCT) ||
isConstantFPBuildVectorOrConstantFP(NewCT)) &&
"Failed to constant fold a binop with constant operands");
SDValue NewCF = DAG.getNode(BinOpcode, DL, VT, CF, C1);
assert((NewCF.isUndef() || isConstantOrConstantVector(NewCF) ||
isConstantFPBuildVectorOrConstantFP(NewCF)) &&
"Failed to constant fold a binop with constant operands");
return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
}
SDValue DAGCombiner::visitADD(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
SDLoc DL(N);
// fold vector ops
if (VT.isVector()) {
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (add x, 0) -> x, vector edition
if (ISD::isBuildVectorAllZeros(N1.getNode()))
return N0;
if (ISD::isBuildVectorAllZeros(N0.getNode()))
return N1;
}
// fold (add x, undef) -> undef
if (N0.isUndef())
return N0;
if (N1.isUndef())
return N1;
if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
// canonicalize constant to RHS
if (!DAG.isConstantIntBuildVectorOrConstantInt(N1))
return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
// fold (add c1, c2) -> c1+c2
return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(),
N1.getNode());
}
// fold (add x, 0) -> x
if (isNullConstant(N1))
return N0;
// fold ((c1-A)+c2) -> (c1+c2)-A
if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
if (N0.getOpcode() == ISD::SUB)
if (isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
return DAG.getNode(ISD::SUB, DL, VT,
DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
N0.getOperand(1));
}
}
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// reassociate add
if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1))
return RADD;
// fold ((0-A) + B) -> B-A
if (N0.getOpcode() == ISD::SUB &&
isNullConstantOrNullSplatConstant(N0.getOperand(0)))
return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
// fold (A + (0-B)) -> A-B
if (N1.getOpcode() == ISD::SUB &&
isNullConstantOrNullSplatConstant(N1.getOperand(0)))
return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
// fold (A+(B-A)) -> B
if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
return N1.getOperand(0);
// fold ((B-A)+A) -> B
if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
return N0.getOperand(0);
// fold (A+(B-(A+C))) to (B-C)
if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
N0 == N1.getOperand(1).getOperand(0))
return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
N1.getOperand(1).getOperand(1));
// fold (A+(B-(C+A))) to (B-C)
if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
N0 == N1.getOperand(1).getOperand(1))
return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
N1.getOperand(1).getOperand(0));
// fold (A+((B-A)+or-C)) to (B+or-C)
if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
N1.getOperand(0).getOpcode() == ISD::SUB &&
N0 == N1.getOperand(0).getOperand(1))
return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
N1.getOperand(1));
// fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
SDValue N00 = N0.getOperand(0);
SDValue N01 = N0.getOperand(1);
SDValue N10 = N1.getOperand(0);
SDValue N11 = N1.getOperand(1);
if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
return DAG.getNode(ISD::SUB, DL, VT,
DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
}
if (SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
// fold (a+b) -> (a|b) iff a and b share no bits.
if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
VT.isInteger() && DAG.haveNoCommonBitsSet(N0, N1))
return DAG.getNode(ISD::OR, DL, VT, N0, N1);
if (SDValue Combined = visitADDLike(N0, N1, N))
return Combined;
if (SDValue Combined = visitADDLike(N1, N0, N))
return Combined;
return SDValue();
}
SDValue DAGCombiner::visitADDLike(SDValue N0, SDValue N1, SDNode *LocReference) {
EVT VT = N0.getValueType();
SDLoc DL(LocReference);
// fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
isNullConstantOrNullSplatConstant(N1.getOperand(0).getOperand(0)))
return DAG.getNode(ISD::SUB, DL, VT, N0,
DAG.getNode(ISD::SHL, DL, VT,
N1.getOperand(0).getOperand(1),
N1.getOperand(1)));
if (N1.getOpcode() == ISD::AND) {
SDValue AndOp0 = N1.getOperand(0);
unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
unsigned DestBits = VT.getScalarSizeInBits();
// (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
// and similar xforms where the inner op is either ~0 or 0.
if (NumSignBits == DestBits &&
isOneConstantOrOneSplatConstant(N1->getOperand(1)))
return DAG.getNode(ISD::SUB, DL, VT, N0, AndOp0);
}
// add (sext i1), X -> sub X, (zext i1)
if (N0.getOpcode() == ISD::SIGN_EXTEND &&
N0.getOperand(0).getValueType() == MVT::i1 &&
!TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
}
// add X, (sextinreg Y i1) -> sub X, (and Y 1)
if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
if (TN->getVT() == MVT::i1) {
SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
DAG.getConstant(1, DL, VT));
return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
}
}
return SDValue();
}
SDValue DAGCombiner::visitADDC(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
SDLoc DL(N);
// If the flag result is dead, turn this into an ADD.
if (!N->hasAnyUseOfValue(1))
return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
// canonicalize constant to RHS.
ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
if (N0C && !N1C)
return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
// fold (addc x, 0) -> x + no carry out
if (isNullConstant(N1))
return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
DL, MVT::Glue));
// If it cannot overflow, transform into an add.
if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
return SDValue();
}
SDValue DAGCombiner::visitUADDO(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
if (VT.isVector())
return SDValue();
EVT CarryVT = N->getValueType(1);
SDLoc DL(N);
// If the flag result is dead, turn this into an ADD.
if (!N->hasAnyUseOfValue(1))
return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
DAG.getUNDEF(CarryVT));
// canonicalize constant to RHS.
ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
if (N0C && !N1C)
return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N1, N0);
// fold (uaddo x, 0) -> x + no carry out
if (isNullConstant(N1))
return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
// If it cannot overflow, transform into an add.
if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
DAG.getConstant(0, DL, CarryVT));
return SDValue();
}
SDValue DAGCombiner::visitADDE(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue CarryIn = N->getOperand(2);
// canonicalize constant to RHS
ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
if (N0C && !N1C)
return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
N1, N0, CarryIn);
// fold (adde x, y, false) -> (addc x, y)
if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
return SDValue();
}
// Since it may not be valid to emit a fold to zero for vector initializers
// check if we can before folding.
static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
SelectionDAG &DAG, bool LegalOperations,
bool LegalTypes) {
if (!VT.isVector())
return DAG.getConstant(0, DL, VT);
if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
return DAG.getConstant(0, DL, VT);
return SDValue();
}
SDValue DAGCombiner::visitSUB(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
SDLoc DL(N);
// fold vector ops
if (VT.isVector()) {
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (sub x, 0) -> x, vector edition
if (ISD::isBuildVectorAllZeros(N1.getNode()))
return N0;
}
// fold (sub x, x) -> 0
// FIXME: Refactor this and xor and other similar operations together.
if (N0 == N1)
return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations, LegalTypes);
if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
DAG.isConstantIntBuildVectorOrConstantInt(N1)) {
// fold (sub c1, c2) -> c1-c2
return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(),
N1.getNode());
}
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
// fold (sub x, c) -> (add x, -c)
if (N1C) {
return DAG.getNode(ISD::ADD, DL, VT, N0,
DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
}
if (isNullConstantOrNullSplatConstant(N0)) {
unsigned BitWidth = VT.getScalarSizeInBits();
// Right-shifting everything out but the sign bit followed by negation is
// the same as flipping arithmetic/logical shift type without the negation:
// -(X >>u 31) -> (X >>s 31)
// -(X >>s 31) -> (X >>u 31)
if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) {
auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
}
}
// 0 - X --> 0 if the sub is NUW.
if (N->getFlags()->hasNoUnsignedWrap())
return N0;
if (DAG.MaskedValueIsZero(N1, ~APInt::getSignBit(BitWidth))) {
// N1 is either 0 or the minimum signed value. If the sub is NSW, then
// N1 must be 0 because negating the minimum signed value is undefined.
if (N->getFlags()->hasNoSignedWrap())
return N0;
// 0 - X --> X if X is 0 or the minimum signed value.
return N1;
}
}
// Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
if (isAllOnesConstantOrAllOnesSplatConstant(N0))
return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
// fold A-(A-B) -> B
if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
return N1.getOperand(1);
// fold (A+B)-A -> B
if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
return N0.getOperand(1);
// fold (A+B)-B -> A
if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
return N0.getOperand(0);
// fold C2-(A+C1) -> (C2-C1)-A
if (N1.getOpcode() == ISD::ADD) {
SDValue N11 = N1.getOperand(1);
if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11);
return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
}
}
// fold ((A+(B+or-C))-B) -> A+or-C
if (N0.getOpcode() == ISD::ADD &&
(N0.getOperand(1).getOpcode() == ISD::SUB ||
N0.getOperand(1).getOpcode() == ISD::ADD) &&
N0.getOperand(1).getOperand(0) == N1)
return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
N0.getOperand(1).getOperand(1));
// fold ((A+(C+B))-B) -> A+C
if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
N0.getOperand(1).getOperand(1) == N1)
return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
N0.getOperand(1).getOperand(0));
// fold ((A-(B-C))-C) -> A-B
if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
N0.getOperand(1).getOperand(1) == N1)
return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
N0.getOperand(1).getOperand(0));
// If either operand of a sub is undef, the result is undef
if (N0.isUndef())
return N0;
if (N1.isUndef())
return N1;
// If the relocation model supports it, consider symbol offsets.
if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
// fold (sub Sym, c) -> Sym-c
if (N1C && GA->getOpcode() == ISD::GlobalAddress)
return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
GA->getOffset() -
(uint64_t)N1C->getSExtValue());
// fold (sub Sym+c1, Sym+c2) -> c1-c2
if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
if (GA->getGlobal() == GB->getGlobal())
return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
DL, VT);
}
// sub X, (sextinreg Y i1) -> add X, (and Y 1)
if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
if (TN->getVT() == MVT::i1) {
SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
DAG.getConstant(1, DL, VT));
return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
}
}
return SDValue();
}
SDValue DAGCombiner::visitSUBC(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
SDLoc DL(N);
// If the flag result is dead, turn this into an SUB.
if (!N->hasAnyUseOfValue(1))
return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
// fold (subc x, x) -> 0 + no borrow
if (N0 == N1)
return CombineTo(N, DAG.getConstant(0, DL, VT),
DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
// fold (subc x, 0) -> x + no borrow
if (isNullConstant(N1))
return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
// Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
if (isAllOnesConstant(N0))
return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
return SDValue();
}
SDValue DAGCombiner::visitUSUBO(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
if (VT.isVector())
return SDValue();
EVT CarryVT = N->getValueType(1);
SDLoc DL(N);
// If the flag result is dead, turn this into an SUB.
if (!N->hasAnyUseOfValue(1))
return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
DAG.getUNDEF(CarryVT));
// fold (usubo x, x) -> 0 + no borrow
if (N0 == N1)
return CombineTo(N, DAG.getConstant(0, DL, VT),
DAG.getConstant(0, DL, CarryVT));
// fold (usubo x, 0) -> x + no borrow
if (isNullConstant(N1))
return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
// Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
if (isAllOnesConstant(N0))
return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
DAG.getConstant(0, DL, CarryVT));
return SDValue();
}
SDValue DAGCombiner::visitSUBE(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue CarryIn = N->getOperand(2);
// fold (sube x, y, false) -> (subc x, y)
if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
return SDValue();
}
SDValue DAGCombiner::visitMUL(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
// fold (mul x, undef) -> 0
if (N0.isUndef() || N1.isUndef())
return DAG.getConstant(0, SDLoc(N), VT);
bool N0IsConst = false;
bool N1IsConst = false;
bool N1IsOpaqueConst = false;
bool N0IsOpaqueConst = false;
APInt ConstValue0, ConstValue1;
// fold vector ops
if (VT.isVector()) {
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0);
N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
} else {
N0IsConst = isa<ConstantSDNode>(N0);
if (N0IsConst) {
ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
}
N1IsConst = isa<ConstantSDNode>(N1);
if (N1IsConst) {
ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
}
}
// fold (mul c1, c2) -> c1*c2
if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
N0.getNode(), N1.getNode());
// canonicalize constant to RHS (vector doesn't have to splat)
if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
!DAG.isConstantIntBuildVectorOrConstantInt(N1))
return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
// fold (mul x, 0) -> 0
if (N1IsConst && ConstValue1 == 0)
return N1;
// We require a splat of the entire scalar bit width for non-contiguous
// bit patterns.
bool IsFullSplat =
ConstValue1.getBitWidth() == VT.getScalarSizeInBits();
// fold (mul x, 1) -> x
if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
return N0;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// fold (mul x, -1) -> 0-x
if (N1IsConst && ConstValue1.isAllOnesValue()) {
SDLoc DL(N);
return DAG.getNode(ISD::SUB, DL, VT,
DAG.getConstant(0, DL, VT), N0);
}
// fold (mul x, (1 << c)) -> x << c
if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
IsFullSplat) {
SDLoc DL(N);
return DAG.getNode(ISD::SHL, DL, VT, N0,
DAG.getConstant(ConstValue1.logBase2(), DL,
getShiftAmountTy(N0.getValueType())));
}
// fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
IsFullSplat) {
unsigned Log2Val = (-ConstValue1).logBase2();
SDLoc DL(N);
// FIXME: If the input is something that is easily negated (e.g. a
// single-use add), we should put the negate there.
return DAG.getNode(ISD::SUB, DL, VT,
DAG.getConstant(0, DL, VT),
DAG.getNode(ISD::SHL, DL, VT, N0,
DAG.getConstant(Log2Val, DL,
getShiftAmountTy(N0.getValueType()))));
}
// (mul (shl X, c1), c2) -> (mul X, c2 << c1)
if (N0.getOpcode() == ISD::SHL &&
isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
if (isConstantOrConstantVector(C3))
return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
}
// Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
// use.
{
SDValue Sh(nullptr, 0), Y(nullptr, 0);
// Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
if (N0.getOpcode() == ISD::SHL &&
isConstantOrConstantVector(N0.getOperand(1)) &&
N0.getNode()->hasOneUse()) {
Sh = N0; Y = N1;
} else if (N1.getOpcode() == ISD::SHL &&
isConstantOrConstantVector(N1.getOperand(1)) &&
N1.getNode()->hasOneUse()) {
Sh = N1; Y = N0;
}
if (Sh.getNode()) {
SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
}
}
// fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
N0.getOpcode() == ISD::ADD &&
DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
isMulAddWithConstProfitable(N, N0, N1))
return DAG.getNode(ISD::ADD, SDLoc(N), VT,
DAG.getNode(ISD::MUL, SDLoc(N0), VT,
N0.getOperand(0), N1),
DAG.getNode(ISD::MUL, SDLoc(N1), VT,
N0.getOperand(1), N1));
// reassociate mul
if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
return RMUL;
return SDValue();
}
/// Return true if divmod libcall is available.
static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
const TargetLowering &TLI) {
RTLIB::Libcall LC;
EVT NodeType = Node->getValueType(0);
if (!NodeType.isSimple())
return false;
switch (NodeType.getSimpleVT().SimpleTy) {
default: return false; // No libcall for vector types.
case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
}
return TLI.getLibcallName(LC) != nullptr;
}
/// Issue divrem if both quotient and remainder are needed.
SDValue DAGCombiner::useDivRem(SDNode *Node) {
if (Node->use_empty())
return SDValue(); // This is a dead node, leave it alone.
unsigned Opcode = Node->getOpcode();
bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
// DivMod lib calls can still work on non-legal types if using lib-calls.
EVT VT = Node->getValueType(0);
if (VT.isVector() || !VT.isInteger())
return SDValue();
if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
return SDValue();
// If DIVREM is going to get expanded into a libcall,
// but there is no libcall available, then don't combine.
if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
!isDivRemLibcallAvailable(Node, isSigned, TLI))
return SDValue();
// If div is legal, it's better to do the normal expansion
unsigned OtherOpcode = 0;
if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
if (TLI.isOperationLegalOrCustom(Opcode, VT))
return SDValue();
} else {
OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
return SDValue();
}
SDValue Op0 = Node->getOperand(0);
SDValue Op1 = Node->getOperand(1);
SDValue combined;
for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
UE = Op0.getNode()->use_end(); UI != UE;) {
SDNode *User = *UI++;
if (User == Node || User->use_empty())
continue;
// Convert the other matching node(s), too;
// otherwise, the DIVREM may get target-legalized into something
// target-specific that we won't be able to recognize.
unsigned UserOpc = User->getOpcode();
if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
User->getOperand(0) == Op0 &&
User->getOperand(1) == Op1) {
if (!combined) {
if (UserOpc == OtherOpcode) {
SDVTList VTs = DAG.getVTList(VT, VT);
combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
} else if (UserOpc == DivRemOpc) {
combined = SDValue(User, 0);
} else {
assert(UserOpc == Opcode);
continue;
}
}
if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
CombineTo(User, combined);
else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
CombineTo(User, combined.getValue(1));
}
}
return combined;
}
static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
SDLoc DL(N);
if (DAG.isUndef(N->getOpcode(), {N0, N1}))
return DAG.getUNDEF(VT);
// undef / X -> 0
// undef % X -> 0
if (N0.isUndef())
return DAG.getConstant(0, DL, VT);
return SDValue();
}
SDValue DAGCombiner::visitSDIV(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
// fold vector ops
if (VT.isVector())
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
SDLoc DL(N);
// fold (sdiv c1, c2) -> c1/c2
ConstantSDNode *N0C = isConstOrConstSplat(N0);
ConstantSDNode *N1C = isConstOrConstSplat(N1);
if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
// fold (sdiv X, 1) -> X
if (N1C && N1C->isOne())
return N0;
// fold (sdiv X, -1) -> 0-X
if (N1C && N1C->isAllOnesValue())
return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
if (SDValue V = simplifyDivRem(N, DAG))
return V;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// If we know the sign bits of both operands are zero, strength reduce to a
// udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
// fold (sdiv X, pow2) -> simple ops after legalize
// FIXME: We check for the exact bit here because the generic lowering gives
// better results in that case. The target-specific lowering should learn how
// to handle exact sdivs efficiently.
if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
!cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
(N1C->getAPIntValue().isPowerOf2() ||
(-N1C->getAPIntValue()).isPowerOf2())) {
// Target-specific implementation of sdiv x, pow2.
if (SDValue Res = BuildSDIVPow2(N))
return Res;
unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
// Splat the sign bit into the register
SDValue SGN =
DAG.getNode(ISD::SRA, DL, VT, N0,
DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
getShiftAmountTy(N0.getValueType())));
AddToWorklist(SGN.getNode());
// Add (N0 < 0) ? abs2 - 1 : 0;
SDValue SRL =
DAG.getNode(ISD::SRL, DL, VT, SGN,
DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
getShiftAmountTy(SGN.getValueType())));
SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
AddToWorklist(SRL.getNode());
AddToWorklist(ADD.getNode()); // Divide by pow2
SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
DAG.getConstant(lg2, DL,
getShiftAmountTy(ADD.getValueType())));
// If we're dividing by a positive value, we're done. Otherwise, we must
// negate the result.
if (N1C->getAPIntValue().isNonNegative())
return SRA;
AddToWorklist(SRA.getNode());
return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
}
// If integer divide is expensive and we satisfy the requirements, emit an
// alternate sequence. Targets may check function attributes for size/speed
// trade-offs.
AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
if (SDValue Op = BuildSDIV(N))
return Op;
// sdiv, srem -> sdivrem
// If the divisor is constant, then return DIVREM only if isIntDivCheap() is
// true. Otherwise, we break the simplification logic in visitREM().
if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
if (SDValue DivRem = useDivRem(N))
return DivRem;
return SDValue();
}
SDValue DAGCombiner::visitUDIV(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
// fold vector ops
if (VT.isVector())
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
SDLoc DL(N);
// fold (udiv c1, c2) -> c1/c2
ConstantSDNode *N0C = isConstOrConstSplat(N0);
ConstantSDNode *N1C = isConstOrConstSplat(N1);
if (N0C && N1C)
if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
N0C, N1C))
return Folded;
if (SDValue V = simplifyDivRem(N, DAG))
return V;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// fold (udiv x, (1 << c)) -> x >>u c
if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
DAG.isKnownToBeAPowerOfTwo(N1)) {
SDValue LogBase2 = BuildLogBase2(N1, DL);
AddToWorklist(LogBase2.getNode());
EVT ShiftVT = getShiftAmountTy(N0.getValueType());
SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
AddToWorklist(Trunc.getNode());
return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
}
// fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
if (N1.getOpcode() == ISD::SHL) {
SDValue N10 = N1.getOperand(0);
if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
DAG.isKnownToBeAPowerOfTwo(N10)) {
SDValue LogBase2 = BuildLogBase2(N10, DL);
AddToWorklist(LogBase2.getNode());
EVT ADDVT = N1.getOperand(1).getValueType();
SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
AddToWorklist(Trunc.getNode());
SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
AddToWorklist(Add.getNode());
return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
}
}
// fold (udiv x, c) -> alternate
AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
if (SDValue Op = BuildUDIV(N))
return Op;
// sdiv, srem -> sdivrem
// If the divisor is constant, then return DIVREM only if isIntDivCheap() is
// true. Otherwise, we break the simplification logic in visitREM().
if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
if (SDValue DivRem = useDivRem(N))
return DivRem;
return SDValue();
}
// handles ISD::SREM and ISD::UREM
SDValue DAGCombiner::visitREM(SDNode *N) {
unsigned Opcode = N->getOpcode();
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
bool isSigned = (Opcode == ISD::SREM);
SDLoc DL(N);
// fold (rem c1, c2) -> c1%c2
ConstantSDNode *N0C = isConstOrConstSplat(N0);
ConstantSDNode *N1C = isConstOrConstSplat(N1);
if (N0C && N1C)
if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
return Folded;
if (SDValue V = simplifyDivRem(N, DAG))
return V;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
if (isSigned) {
// If we know the sign bits of both operands are zero, strength reduce to a
// urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
} else {
SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
if (DAG.isKnownToBeAPowerOfTwo(N1)) {
// fold (urem x, pow2) -> (and x, pow2-1)
SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
AddToWorklist(Add.getNode());
return DAG.getNode(ISD::AND, DL, VT, N0, Add);
}
if (N1.getOpcode() == ISD::SHL &&
DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
// fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
AddToWorklist(Add.getNode());
return DAG.getNode(ISD::AND, DL, VT, N0, Add);
}
}
AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
// If X/C can be simplified by the division-by-constant logic, lower
// X%C to the equivalent of X-X/C*C.
// To avoid mangling nodes, this simplification requires that the combine()
// call for the speculative DIV must not cause a DIVREM conversion. We guard
// against this by skipping the simplification if isIntDivCheap(). When
// div is not cheap, combine will not return a DIVREM. Regardless,
// checking cheapness here makes sense since the simplification results in
// fatter code.
if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap(VT, Attr)) {
unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
AddToWorklist(Div.getNode());
SDValue OptimizedDiv = combine(Div.getNode());
if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
assert((OptimizedDiv.getOpcode() != ISD::UDIVREM) &&
(OptimizedDiv.getOpcode() != ISD::SDIVREM));
SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
AddToWorklist(Mul.getNode());
return Sub;
}
}
// sdiv, srem -> sdivrem
if (SDValue DivRem = useDivRem(N))
return DivRem.getValue(1);
return SDValue();
}
SDValue DAGCombiner::visitMULHS(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
SDLoc DL(N);
// fold (mulhs x, 0) -> 0
if (isNullConstant(N1))
return N1;
// fold (mulhs x, 1) -> (sra x, size(x)-1)
if (isOneConstant(N1)) {
SDLoc DL(N);
return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
DAG.getConstant(N0.getValueSizeInBits() - 1, DL,
getShiftAmountTy(N0.getValueType())));
}
// fold (mulhs x, undef) -> 0
if (N0.isUndef() || N1.isUndef())
return DAG.getConstant(0, SDLoc(N), VT);
// If the type twice as wide is legal, transform the mulhs to a wider multiply
// plus a shift.
if (VT.isSimple() && !VT.isVector()) {
MVT Simple = VT.getSimpleVT();
unsigned SimpleSize = Simple.getSizeInBits();
EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
DAG.getConstant(SimpleSize, DL,
getShiftAmountTy(N1.getValueType())));
return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
}
}
return SDValue();
}
SDValue DAGCombiner::visitMULHU(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
SDLoc DL(N);
// fold (mulhu x, 0) -> 0
if (isNullConstant(N1))
return N1;
// fold (mulhu x, 1) -> 0
if (isOneConstant(N1))
return DAG.getConstant(0, DL, N0.getValueType());
// fold (mulhu x, undef) -> 0
if (N0.isUndef() || N1.isUndef())
return DAG.getConstant(0, DL, VT);
// If the type twice as wide is legal, transform the mulhu to a wider multiply
// plus a shift.
if (VT.isSimple() && !VT.isVector()) {
MVT Simple = VT.getSimpleVT();
unsigned SimpleSize = Simple.getSizeInBits();
EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
DAG.getConstant(SimpleSize, DL,
getShiftAmountTy(N1.getValueType())));
return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
}
}
return SDValue();
}
/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
/// give the opcodes for the two computations that are being performed. Return
/// true if a simplification was made.
SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
unsigned HiOp) {
// If the high half is not needed, just compute the low half.
bool HiExists = N->hasAnyUseOfValue(1);
if (!HiExists &&
(!LegalOperations ||
TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
return CombineTo(N, Res, Res);
}
// If the low half is not needed, just compute the high half.
bool LoExists = N->hasAnyUseOfValue(0);
if (!LoExists &&
(!LegalOperations ||
TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
return CombineTo(N, Res, Res);
}
// If both halves are used, return as it is.
if (LoExists && HiExists)
return SDValue();
// If the two computed results can be simplified separately, separate them.
if (LoExists) {
SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
AddToWorklist(Lo.getNode());
SDValue LoOpt = combine(Lo.getNode());
if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
(!LegalOperations ||
TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
return CombineTo(N, LoOpt, LoOpt);
}
if (HiExists) {
SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
AddToWorklist(Hi.getNode());
SDValue HiOpt = combine(Hi.getNode());
if (HiOpt.getNode() && HiOpt != Hi &&
(!LegalOperations ||
TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
return CombineTo(N, HiOpt, HiOpt);
}
return SDValue();
}
SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
return Res;
EVT VT = N->getValueType(0);
SDLoc DL(N);
// If the type is twice as wide is legal, transform the mulhu to a wider
// multiply plus a shift.
if (VT.isSimple() && !VT.isVector()) {
MVT Simple = VT.getSimpleVT();
unsigned SimpleSize = Simple.getSizeInBits();
EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
// Compute the high part as N1.
Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
DAG.getConstant(SimpleSize, DL,
getShiftAmountTy(Lo.getValueType())));
Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
// Compute the low part as N0.
Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
return CombineTo(N, Lo, Hi);
}
}
return SDValue();
}
SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
return Res;
EVT VT = N->getValueType(0);
SDLoc DL(N);
// If the type is twice as wide is legal, transform the mulhu to a wider
// multiply plus a shift.
if (VT.isSimple() && !VT.isVector()) {
MVT Simple = VT.getSimpleVT();
unsigned SimpleSize = Simple.getSizeInBits();
EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
// Compute the high part as N1.
Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
DAG.getConstant(SimpleSize, DL,
getShiftAmountTy(Lo.getValueType())));
Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
// Compute the low part as N0.
Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
return CombineTo(N, Lo, Hi);
}
}
return SDValue();
}
SDValue DAGCombiner::visitSMULO(SDNode *N) {
// (smulo x, 2) -> (saddo x, x)
if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
if (C2->getAPIntValue() == 2)
return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
N->getOperand(0), N->getOperand(0));
return SDValue();
}
SDValue DAGCombiner::visitUMULO(SDNode *N) {
// (umulo x, 2) -> (uaddo x, x)
if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
if (C2->getAPIntValue() == 2)
return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
N->getOperand(0), N->getOperand(0));
return SDValue();
}
SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
// fold vector ops
if (VT.isVector())
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (add c1, c2) -> c1+c2
ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
if (N0C && N1C)
return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
// canonicalize constant to RHS
if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
!DAG.isConstantIntBuildVectorOrConstantInt(N1))
return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
return SDValue();
}
/// If this is a binary operator with two operands of the same opcode, try to
/// simplify it.
SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
EVT VT = N0.getValueType();
assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
// Bail early if none of these transforms apply.
if (N0.getNumOperands() == 0) return SDValue();
// For each of OP in AND/OR/XOR:
// fold (OP (zext x), (zext y)) -> (zext (OP x, y))
// fold (OP (sext x), (sext y)) -> (sext (OP x, y))
// fold (OP (aext x), (aext y)) -> (aext (OP x, y))
// fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
// fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
//
// do not sink logical op inside of a vector extend, since it may combine
// into a vsetcc.
EVT Op0VT = N0.getOperand(0).getValueType();
if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
N0.getOpcode() == ISD::SIGN_EXTEND ||
N0.getOpcode() == ISD::BSWAP ||
// Avoid infinite looping with PromoteIntBinOp.
(N0.getOpcode() == ISD::ANY_EXTEND &&
(!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
(N0.getOpcode() == ISD::TRUNCATE &&
(!TLI.isZExtFree(VT, Op0VT) ||
!TLI.isTruncateFree(Op0VT, VT)) &&
TLI.isTypeLegal(Op0VT))) &&
!VT.isVector() &&
Op0VT == N1.getOperand(0).getValueType() &&
(!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
N0.getOperand(0).getValueType(),
N0.getOperand(0), N1.getOperand(0));
AddToWorklist(ORNode.getNode());
return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
}
// For each of OP in SHL/SRL/SRA/AND...
// fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
// fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
// fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
N0.getOperand(1) == N1.getOperand(1)) {
SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
N0.getOperand(0).getValueType(),
N0.getOperand(0), N1.getOperand(0));
AddToWorklist(ORNode.getNode());
return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
ORNode, N0.getOperand(1));
}
// Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
// Only perform this optimization up until type legalization, before
// LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
// adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
// we don't want to undo this promotion.
// We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
// on scalars.
if ((N0.getOpcode() == ISD::BITCAST ||
N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
Level <= AfterLegalizeTypes) {
SDValue In0 = N0.getOperand(0);
SDValue In1 = N1.getOperand(0);
EVT In0Ty = In0.getValueType();
EVT In1Ty = In1.getValueType();
SDLoc DL(N);
// If both incoming values are integers, and the original types are the
// same.
if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
AddToWorklist(Op.getNode());
return BC;
}
}
// Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
// Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
// If both shuffles use the same mask, and both shuffle within a single
// vector, then it is worthwhile to move the swizzle after the operation.
// The type-legalizer generates this pattern when loading illegal
// vector types from memory. In many cases this allows additional shuffle
// optimizations.
// There are other cases where moving the shuffle after the xor/and/or
// is profitable even if shuffles don't perform a swizzle.
// If both shuffles use the same mask, and both shuffles have the same first
// or second operand, then it might still be profitable to move the shuffle
// after the xor/and/or operation.
if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
"Inputs to shuffles are not the same type");
// Check that both shuffles use the same mask. The masks are known to be of
// the same length because the result vector type is the same.
// Check also that shuffles have only one use to avoid introducing extra
// instructions.
if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
SVN0->getMask().equals(SVN1->getMask())) {
SDValue ShOp = N0->getOperand(1);
// Don't try to fold this node if it requires introducing a
// build vector of all zeros that might be illegal at this stage.
if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
if (!LegalTypes)
ShOp = DAG.getConstant(0, SDLoc(N), VT);
else
ShOp = SDValue();
}
// (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
// (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
// (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
N0->getOperand(0), N1->getOperand(0));
AddToWorklist(NewNode.getNode());
return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
SVN0->getMask());
}
// Don't try to fold this node if it requires introducing a
// build vector of all zeros that might be illegal at this stage.
ShOp = N0->getOperand(0);
if (N->getOpcode() == ISD::XOR && !ShOp.isUndef()) {
if (!LegalTypes)
ShOp = DAG.getConstant(0, SDLoc(N), VT);
else
ShOp = SDValue();
}
// (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
// (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
// (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
N0->getOperand(1), N1->getOperand(1));
AddToWorklist(NewNode.getNode());
return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
SVN0->getMask());
}
}
}
return SDValue();
}
/// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
const SDLoc &DL) {
SDValue LL, LR, RL, RR, N0CC, N1CC;
if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
!isSetCCEquivalent(N1, RL, RR, N1CC))
return SDValue();
assert(N0.getValueType() == N1.getValueType() &&
"Unexpected operand types for bitwise logic op");
assert(LL.getValueType() == LR.getValueType() &&
RL.getValueType() == RR.getValueType() &&
"Unexpected operand types for setcc");
// If we're here post-legalization or the logic op type is not i1, the logic
// op type must match a setcc result type. Also, all folds require new
// operations on the left and right operands, so those types must match.
EVT VT = N0.getValueType();
EVT OpVT = LL.getValueType();
if (LegalOperations || VT != MVT::i1)
if (VT != getSetCCResultType(OpVT))
return SDValue();
if (OpVT != RL.getValueType())
return SDValue();
ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
bool IsInteger = OpVT.isInteger();
if (LR == RR && CC0 == CC1 && IsInteger) {
bool IsZero = isNullConstantOrNullSplatConstant(LR);
bool IsNeg1 = isAllOnesConstantOrAllOnesSplatConstant(LR);
// All bits clear?
bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
// All sign bits clear?
bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
// Any bits set?
bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
// Any sign bits set?
bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
// (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
// (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
// (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
// (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
AddToWorklist(Or.getNode());
return DAG.getSetCC(DL, VT, Or, LR, CC1);
}
// All bits set?
bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
// All sign bits set?
bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
// Any bits clear?
bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
// Any sign bits clear?
bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
// (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
// (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
// (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
// (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
AddToWorklist(And.getNode());
return DAG.getSetCC(DL, VT, And, LR, CC1);
}
}
// TODO: What is the 'or' equivalent of this fold?
// (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
if (IsAnd && LL == RL && CC0 == CC1 && IsInteger && CC0 == ISD::SETNE &&
((isNullConstant(LR) && isAllOnesConstant(RR)) ||
(isAllOnesConstant(LR) && isNullConstant(RR)))) {
SDValue One = DAG.getConstant(1, DL, OpVT);
SDValue Two = DAG.getConstant(2, DL, OpVT);
SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
AddToWorklist(Add.getNode());
return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
}
// Try more general transforms if the predicates match and the only user of
// the compares is the 'and' or 'or'.
if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
N0.hasOneUse() && N1.hasOneUse()) {
// and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
// or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
SDValue Zero = DAG.getConstant(0, DL, OpVT);
return DAG.getSetCC(DL, VT, Or, Zero, CC1);
}
}
// Canonicalize equivalent operands to LL == RL.
if (LL == RR && LR == RL) {
CC1 = ISD::getSetCCSwappedOperands(CC1);
std::swap(RL, RR);
}
// (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
// (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
if (LL == RL && LR == RR) {
ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger)
: ISD::getSetCCOrOperation(CC0, CC1, IsInteger);
if (NewCC != ISD::SETCC_INVALID &&
(!LegalOperations ||
(TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
TLI.isOperationLegal(ISD::SETCC, OpVT))))
return DAG.getSetCC(DL, VT, LL, LR, NewCC);
}
return SDValue();
}
/// This contains all DAGCombine rules which reduce two values combined by
/// an And operation to a single value. This makes them reusable in the context
/// of visitSELECT(). Rules involving constants are not included as
/// visitSELECT() already handles those cases.
SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
EVT VT = N1.getValueType();
SDLoc DL(N);
// fold (and x, undef) -> 0
if (N0.isUndef() || N1.isUndef())
return DAG.getConstant(0, DL, VT);
if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
return V;
if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
VT.getSizeInBits() <= 64) {
if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
APInt ADDC = ADDI->getAPIntValue();
if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
// Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
// immediate for an add, but it is legal if its top c2 bits are set,
// transform the ADD so the immediate doesn't need to be materialized
// in a register.
if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
SRLI->getZExtValue());
if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
ADDC |= Mask;
if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
SDLoc DL0(N0);
SDValue NewAdd =
DAG.getNode(ISD::ADD, DL0, VT,
N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
CombineTo(N0.getNode(), NewAdd);
// Return N so it doesn't get rechecked!
return SDValue(N, 0);
}
}
}
}
}
}
// Reduce bit extract of low half of an integer to the narrower type.
// (and (srl i64:x, K), KMask) ->
// (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
unsigned Size = VT.getSizeInBits();
const APInt &AndMask = CAnd->getAPIntValue();
unsigned ShiftBits = CShift->getZExtValue();
// Bail out, this node will probably disappear anyway.
if (ShiftBits == 0)
return SDValue();
unsigned MaskBits = AndMask.countTrailingOnes();
EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
if (AndMask.isMask() &&
// Required bits must not span the two halves of the integer and
// must fit in the half size type.
(ShiftBits + MaskBits <= Size / 2) &&
TLI.isNarrowingProfitable(VT, HalfVT) &&
TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
TLI.isTruncateFree(VT, HalfVT) &&
TLI.isZExtFree(HalfVT, VT)) {
// The isNarrowingProfitable is to avoid regressions on PPC and
// AArch64 which match a few 64-bit bit insert / bit extract patterns
// on downstream users of this. Those patterns could probably be
// extended to handle extensions mixed in.
SDValue SL(N0);
assert(MaskBits <= Size);
// Extracting the highest bit of the low half.
EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
N0.getOperand(0));
SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
}
}
}
}
return SDValue();
}
bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
EVT LoadResultTy, EVT &ExtVT, EVT &LoadedVT,
bool &NarrowLoad) {
uint32_t ActiveBits = AndC->getAPIntValue().getActiveBits();
if (ActiveBits == 0 || !AndC->getAPIntValue().isMask(ActiveBits))
return false;
ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
LoadedVT = LoadN->getMemoryVT();
if (ExtVT == LoadedVT &&
(!LegalOperations ||
TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
// ZEXTLOAD will match without needing to change the size of the value being
// loaded.
NarrowLoad = false;
return true;
}
// Do not change the width of a volatile load.
if (LoadN->isVolatile())
return false;
// Do not generate loads of non-round integer types since these can
// be expensive (and would be wrong if the type is not byte sized).
if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
return false;
if (LegalOperations &&
!TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
return false;
if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
return false;
NarrowLoad = true;
return true;
}
SDValue DAGCombiner::visitAND(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N1.getValueType();
// x & x --> x
if (N0 == N1)
return N0;
// fold vector ops
if (VT.isVector()) {
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (and x, 0) -> 0, vector edition
if (ISD::isBuildVectorAllZeros(N0.getNode()))
// do not return N0, because undef node may exist in N0
return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()),
SDLoc(N), N0.getValueType());
if (ISD::isBuildVectorAllZeros(N1.getNode()))
// do not return N1, because undef node may exist in N1
return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()),
SDLoc(N), N1.getValueType());
// fold (and x, -1) -> x, vector edition
if (ISD::isBuildVectorAllOnes(N0.getNode()))
return N1;
if (ISD::isBuildVectorAllOnes(N1.getNode()))
return N0;
}
// fold (and c1, c2) -> c1&c2
ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
ConstantSDNode *N1C = isConstOrConstSplat(N1);
if (N0C && N1C && !N1C->isOpaque())
return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
// canonicalize constant to RHS
if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
!DAG.isConstantIntBuildVectorOrConstantInt(N1))
return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
// fold (and x, -1) -> x
if (isAllOnesConstant(N1))
return N0;
// if (and x, c) is known to be zero, return 0
unsigned BitWidth = VT.getScalarSizeInBits();
if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
APInt::getAllOnesValue(BitWidth)))
return DAG.getConstant(0, SDLoc(N), VT);
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// reassociate and
if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
return RAND;
// fold (and (or x, C), D) -> D if (C & D) == D
if (N1C && N0.getOpcode() == ISD::OR)
if (ConstantSDNode *ORI = isConstOrConstSplat(N0.getOperand(1)))
if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
return N1;
// fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
SDValue N0Op0 = N0.getOperand(0);
APInt Mask = ~N1C->getAPIntValue();
Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
N0.getValueType(), N0Op0);
// Replace uses of the AND with uses of the Zero extend node.
CombineTo(N, Zext);
// We actually want to replace all uses of the any_extend with the
// zero_extend, to avoid duplicating things. This will later cause this
// AND to be folded.
CombineTo(N0.getNode(), Zext);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
// (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
// already be zero by virtue of the width of the base type of the load.
//
// the 'X' node here can either be nothing or an extract_vector_elt to catch
// more cases.
if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
N0.getOperand(0).getOpcode() == ISD::LOAD &&
N0.getOperand(0).getResNo() == 0) ||
(N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
N0 : N0.getOperand(0) );
// Get the constant (if applicable) the zero'th operand is being ANDed with.
// This can be a pure constant or a vector splat, in which case we treat the
// vector as a scalar and use the splat value.
APInt Constant = APInt::getNullValue(1);
if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
Constant = C->getAPIntValue();
} else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
APInt SplatValue, SplatUndef;
unsigned SplatBitSize;
bool HasAnyUndefs;
bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
SplatBitSize, HasAnyUndefs);
if (IsSplat) {
// Undef bits can contribute to a possible optimisation if set, so
// set them.
SplatValue |= SplatUndef;
// The splat value may be something like "0x00FFFFFF", which means 0 for
// the first vector value and FF for the rest, repeating. We need a mask
// that will apply equally to all members of the vector, so AND all the
// lanes of the constant together.
EVT VT = Vector->getValueType(0);
unsigned BitWidth = VT.getScalarSizeInBits();
// If the splat value has been compressed to a bitlength lower
// than the size of the vector lane, we need to re-expand it to
// the lane size.
if (BitWidth > SplatBitSize)
for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
SplatBitSize < BitWidth;
SplatBitSize = SplatBitSize * 2)
SplatValue |= SplatValue.shl(SplatBitSize);
// Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
// multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
if (SplatBitSize % BitWidth == 0) {
Constant = APInt::getAllOnesValue(BitWidth);
for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
}
}
}
// If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
// actually legal and isn't going to get expanded, else this is a false
// optimisation.
bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
Load->getValueType(0),
Load->getMemoryVT());
// Resize the constant to the same size as the original memory access before
// extension. If it is still the AllOnesValue then this AND is completely
// unneeded.
Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
bool B;
switch (Load->getExtensionType()) {
default: B = false; break;
case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
case ISD::ZEXTLOAD:
case ISD::NON_EXTLOAD: B = true; break;
}
if (B && Constant.isAllOnesValue()) {
// If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
// preserve semantics once we get rid of the AND.
SDValue NewLoad(Load, 0);
// Fold the AND away. NewLoad may get replaced immediately.
CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
if (Load->getExtensionType() == ISD::EXTLOAD) {
NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Load->getValueType(0), SDLoc(Load),
Load->getChain(), Load->getBasePtr(),
Load->getOffset(), Load->getMemoryVT(),
Load->getMemOperand());
// Replace uses of the EXTLOAD with the new ZEXTLOAD.
if (Load->getNumValues() == 3) {
// PRE/POST_INC loads have 3 values.
SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
NewLoad.getValue(2) };
CombineTo(Load, To, 3, true);
} else {
CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
}
}
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (and (load x), 255) -> (zextload x, i8)
// fold (and (extload x, i16), 255) -> (zextload x, i8)
// fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
(N0.getOpcode() == ISD::ANY_EXTEND &&
N0.getOperand(0).getOpcode() == ISD::LOAD))) {
bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
LoadSDNode *LN0 = HasAnyExt
? cast<LoadSDNode>(N0.getOperand(0))
: cast<LoadSDNode>(N0);
if (LN0->getExtensionType() != ISD::SEXTLOAD &&
LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
auto NarrowLoad = false;
EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
EVT ExtVT, LoadedVT;
if (isAndLoadExtLoad(N1C, LN0, LoadResultTy, ExtVT, LoadedVT,
NarrowLoad)) {
if (!NarrowLoad) {
SDValue NewLoad =
DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
LN0->getChain(), LN0->getBasePtr(), ExtVT,
LN0->getMemOperand());
AddToWorklist(N);
CombineTo(LN0, NewLoad, NewLoad.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
} else {
EVT PtrType = LN0->getOperand(1).getValueType();
unsigned Alignment = LN0->getAlignment();
SDValue NewPtr = LN0->getBasePtr();
// For big endian targets, we need to add an offset to the pointer
// to load the correct bytes. For little endian systems, we merely
// need to read fewer bytes from the same pointer.
if (DAG.getDataLayout().isBigEndian()) {
unsigned LVTStoreBytes = LoadedVT.getStoreSize();
unsigned EVTStoreBytes = ExtVT.getStoreSize();
unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
SDLoc DL(LN0);
NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
Alignment = MinAlign(Alignment, PtrOff);
}
AddToWorklist(NewPtr.getNode());
SDValue Load = DAG.getExtLoad(
ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy, LN0->getChain(), NewPtr,
LN0->getPointerInfo(), ExtVT, Alignment,
LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
AddToWorklist(N);
CombineTo(LN0, Load, Load.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
}
}
if (SDValue Combined = visitANDLike(N0, N1, N))
return Combined;
// Simplify: (and (op x...), (op y...)) -> (op (and x, y))
if (N0.getOpcode() == N1.getOpcode())
if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
return Tmp;
// Masking the negated extension of a boolean is just the zero-extended
// boolean:
// and (sub 0, zext(bool X)), 1 --> zext(bool X)
// and (sub 0, sext(bool X)), 1 --> zext(bool X)
//
// Note: the SimplifyDemandedBits fold below can make an information-losing
// transform, and then we have no way to find this better fold.
if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
ConstantSDNode *SubLHS = isConstOrConstSplat(N0.getOperand(0));
SDValue SubRHS = N0.getOperand(1);
if (SubLHS && SubLHS->isNullValue()) {
if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
return SubRHS;
if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
}
}
// fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
// fold (and (sra)) -> (and (srl)) when possible.
if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
// fold (zext_inreg (extload x)) -> (zextload x)
if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
EVT MemVT = LN0->getMemoryVT();
// If we zero all the possible extended bits, then we can turn this into
// a zextload if we are running before legalize or the operation is legal.
unsigned BitWidth = N1.getScalarValueSizeInBits();
if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
BitWidth - MemVT.getScalarSizeInBits())) &&
((!LegalOperations && !LN0->isVolatile()) ||
TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
LN0->getChain(), LN0->getBasePtr(),
MemVT, LN0->getMemOperand());
AddToWorklist(N);
CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
N0.hasOneUse()) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
EVT MemVT = LN0->getMemoryVT();
// If we zero all the possible extended bits, then we can turn this into
// a zextload if we are running before legalize or the operation is legal.
unsigned BitWidth = N1.getScalarValueSizeInBits();
if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
BitWidth - MemVT.getScalarSizeInBits())) &&
((!LegalOperations && !LN0->isVolatile()) ||
TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
LN0->getChain(), LN0->getBasePtr(),
MemVT, LN0->getMemOperand());
AddToWorklist(N);
CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
N0.getOperand(1), false))
return BSwap;
}
return SDValue();
}
/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
bool DemandHighBits) {
if (!LegalOperations)
return SDValue();
EVT VT = N->getValueType(0);
if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
return SDValue();
if (!TLI.isOperationLegal(ISD::BSWAP, VT))
return SDValue();
// Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
bool LookPassAnd0 = false;
bool LookPassAnd1 = false;
if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
std::swap(N0, N1);
if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
std::swap(N0, N1);
if (N0.getOpcode() == ISD::AND) {
if (!N0.getNode()->hasOneUse())
return SDValue();
ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
if (!N01C || N01C->getZExtValue() != 0xFF00)
return SDValue();
N0 = N0.getOperand(0);
LookPassAnd0 = true;
}
if (N1.getOpcode() == ISD::AND) {
if (!N1.getNode()->hasOneUse())
return SDValue();
ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
if (!N11C || N11C->getZExtValue() != 0xFF)
return SDValue();
N1 = N1.getOperand(0);
LookPassAnd1 = true;
}
if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
std::swap(N0, N1);
if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
return SDValue();
if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
return SDValue();
ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
if (!N01C || !N11C)
return SDValue();
if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
return SDValue();
// Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
SDValue N00 = N0->getOperand(0);
if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
if (!N00.getNode()->hasOneUse())
return SDValue();
ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
if (!N001C || N001C->getZExtValue() != 0xFF)
return SDValue();
N00 = N00.getOperand(0);
LookPassAnd0 = true;
}
SDValue N10 = N1->getOperand(0);
if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
if (!N10.getNode()->hasOneUse())
return SDValue();
ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
if (!N101C || N101C->getZExtValue() != 0xFF00)
return SDValue();
N10 = N10.getOperand(0);
LookPassAnd1 = true;
}
if (N00 != N10)
return SDValue();
// Make sure everything beyond the low halfword gets set to zero since the SRL
// 16 will clear the top bits.
unsigned OpSizeInBits = VT.getSizeInBits();
if (DemandHighBits && OpSizeInBits > 16) {
// If the left-shift isn't masked out then the only way this is a bswap is
// if all bits beyond the low 8 are 0. In that case the entire pattern
// reduces to a left shift anyway: leave it for other parts of the combiner.
if (!LookPassAnd0)
return SDValue();
// However, if the right shift isn't masked out then it might be because
// it's not needed. See if we can spot that too.
if (!LookPassAnd1 &&
!DAG.MaskedValueIsZero(
N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
return SDValue();
}
SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
if (OpSizeInBits > 16) {
SDLoc DL(N);
Res = DAG.getNode(ISD::SRL, DL, VT, Res,
DAG.getConstant(OpSizeInBits - 16, DL,
getShiftAmountTy(VT)));
}
return Res;
}
/// Return true if the specified node is an element that makes up a 32-bit
/// packed halfword byteswap.
/// ((x & 0x000000ff) << 8) |
/// ((x & 0x0000ff00) >> 8) |
/// ((x & 0x00ff0000) << 8) |
/// ((x & 0xff000000) >> 8)
static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
if (!N.getNode()->hasOneUse())
return false;
unsigned Opc = N.getOpcode();
if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
return false;
ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!N1C)
return false;
unsigned Num;
switch (N1C->getZExtValue()) {
default:
return false;
case 0xFF: Num = 0; break;
case 0xFF00: Num = 1; break;
case 0xFF0000: Num = 2; break;
case 0xFF000000: Num = 3; break;
}
// Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
SDValue N0 = N.getOperand(0);
if (Opc == ISD::AND) {
if (Num == 0 || Num == 2) {
// (x >> 8) & 0xff
// (x >> 8) & 0xff0000
if (N0.getOpcode() != ISD::SRL)
return false;
ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
if (!C || C->getZExtValue() != 8)
return false;
} else {
// (x << 8) & 0xff00
// (x << 8) & 0xff000000
if (N0.getOpcode() != ISD::SHL)
return false;
ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
if (!C || C->getZExtValue() != 8)
return false;
}
} else if (Opc == ISD::SHL) {
// (x & 0xff) << 8
// (x & 0xff0000) << 8
if (Num != 0 && Num != 2)
return false;
ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!C || C->getZExtValue() != 8)
return false;
} else { // Opc == ISD::SRL
// (x & 0xff00) >> 8
// (x & 0xff000000) >> 8
if (Num != 1 && Num != 3)
return false;
ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
if (!C || C->getZExtValue() != 8)
return false;
}
if (Parts[Num])
return false;
Parts[Num] = N0.getOperand(0).getNode();
return true;
}
/// Match a 32-bit packed halfword bswap. That is
/// ((x & 0x000000ff) << 8) |
/// ((x & 0x0000ff00) >> 8) |
/// ((x & 0x00ff0000) << 8) |
/// ((x & 0xff000000) >> 8)
/// => (rotl (bswap x), 16)
SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
if (!LegalOperations)
return SDValue();
EVT VT = N->getValueType(0);
if (VT != MVT::i32)
return SDValue();
if (!TLI.isOperationLegal(ISD::BSWAP, VT))
return SDValue();
// Look for either
// (or (or (and), (and)), (or (and), (and)))
// (or (or (or (and), (and)), (and)), (and))
if (N0.getOpcode() != ISD::OR)
return SDValue();
SDValue N00 = N0.getOperand(0);
SDValue N01 = N0.getOperand(1);
SDNode *Parts[4] = {};
if (N1.getOpcode() == ISD::OR &&
N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
// (or (or (and), (and)), (or (and), (and)))
SDValue N000 = N00.getOperand(0);
if (!isBSwapHWordElement(N000, Parts))
return SDValue();
SDValue N001 = N00.getOperand(1);
if (!isBSwapHWordElement(N001, Parts))
return SDValue();
SDValue N010 = N01.getOperand(0);
if (!isBSwapHWordElement(N010, Parts))
return SDValue();
SDValue N011 = N01.getOperand(1);
if (!isBSwapHWordElement(N011, Parts))
return SDValue();
} else {
// (or (or (or (and), (and)), (and)), (and))
if (!isBSwapHWordElement(N1, Parts))
return SDValue();
if (!isBSwapHWordElement(N01, Parts))
return SDValue();
if (N00.getOpcode() != ISD::OR)
return SDValue();
SDValue N000 = N00.getOperand(0);
if (!isBSwapHWordElement(N000, Parts))
return SDValue();
SDValue N001 = N00.getOperand(1);
if (!isBSwapHWordElement(N001, Parts))
return SDValue();
}
// Make sure the parts are all coming from the same node.
if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
return SDValue();
SDLoc DL(N);
SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
SDValue(Parts[0], 0));
// Result of the bswap should be rotated by 16. If it's not legal, then
// do (x << 16) | (x >> 16).
SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
return DAG.getNode(ISD::OR, DL, VT,
DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
}
/// This contains all DAGCombine rules which reduce two values combined by
/// an Or operation to a single value \see visitANDLike().
SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
EVT VT = N1.getValueType();
SDLoc DL(N);
// fold (or x, undef) -> -1
if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
return DAG.getAllOnesConstant(DL, VT);
if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
return V;
// (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
// Don't increase # computations.
(N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
// We can only do this xform if we know that bits from X that are set in C2
// but not in C1 are already zero. Likewise for Y.
if (const ConstantSDNode *N0O1C =
getAsNonOpaqueConstant(N0.getOperand(1))) {
if (const ConstantSDNode *N1O1C =
getAsNonOpaqueConstant(N1.getOperand(1))) {
// We can only do this xform if we know that bits from X that are set in
// C2 but not in C1 are already zero. Likewise for Y.
const APInt &LHSMask = N0O1C->getAPIntValue();
const APInt &RHSMask = N1O1C->getAPIntValue();
if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
N0.getOperand(0), N1.getOperand(0));
return DAG.getNode(ISD::AND, DL, VT, X,
DAG.getConstant(LHSMask | RHSMask, DL, VT));
}
}
}
}
// (or (and X, M), (and X, N)) -> (and X, (or M, N))
if (N0.getOpcode() == ISD::AND &&
N1.getOpcode() == ISD::AND &&
N0.getOperand(0) == N1.getOperand(0) &&
// Don't increase # computations.
(N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
N0.getOperand(1), N1.getOperand(1));
return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
}
return SDValue();
}
SDValue DAGCombiner::visitOR(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N1.getValueType();
// x | x --> x
if (N0 == N1)
return N0;
// fold vector ops
if (VT.isVector()) {
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (or x, 0) -> x, vector edition
if (ISD::isBuildVectorAllZeros(N0.getNode()))
return N1;
if (ISD::isBuildVectorAllZeros(N1.getNode()))
return N0;
// fold (or x, -1) -> -1, vector edition
if (ISD::isBuildVectorAllOnes(N0.getNode()))
// do not return N0, because undef node may exist in N0
return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType());
if (ISD::isBuildVectorAllOnes(N1.getNode()))
// do not return N1, because undef node may exist in N1
return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
// fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
// Do this only if the resulting shuffle is legal.
if (isa<ShuffleVectorSDNode>(N0) &&
isa<ShuffleVectorSDNode>(N1) &&
// Avoid folding a node with illegal type.
TLI.isTypeLegal(VT)) {
bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
// Ensure both shuffles have a zero input.
if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
bool CanFold = true;
int NumElts = VT.getVectorNumElements();
SmallVector<int, 4> Mask(NumElts);
for (int i = 0; i != NumElts; ++i) {
int M0 = SV0->getMaskElt(i);
int M1 = SV1->getMaskElt(i);
// Determine if either index is pointing to a zero vector.
bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
// If one element is zero and the otherside is undef, keep undef.
// This also handles the case that both are undef.
if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
Mask[i] = -1;
continue;
}
// Make sure only one of the elements is zero.
if (M0Zero == M1Zero) {
CanFold = false;
break;
}
assert((M0 >= 0 || M1 >= 0) && "Undef index!");
// We have a zero and non-zero element. If the non-zero came from
// SV0 make the index a LHS index. If it came from SV1, make it
// a RHS index. We need to mod by NumElts because we don't care
// which operand it came from in the original shuffles.
Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
}
if (CanFold) {
SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
if (!LegalMask) {
std::swap(NewLHS, NewRHS);
ShuffleVectorSDNode::commuteMask(Mask);
LegalMask = TLI.isShuffleMaskLegal(Mask, VT);
}
if (LegalMask)
return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask);
}
}
}
}
// fold (or c1, c2) -> c1|c2
ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
if (N0C && N1C && !N1C->isOpaque())
return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
// canonicalize constant to RHS
if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
!DAG.isConstantIntBuildVectorOrConstantInt(N1))
return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
// fold (or x, 0) -> x
if (isNullConstant(N1))
return N0;
// fold (or x, -1) -> -1
if (isAllOnesConstant(N1))
return N1;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// fold (or x, c) -> c iff (x & ~c) == 0
if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
return N1;
if (SDValue Combined = visitORLike(N0, N1, N))
return Combined;
// Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
return BSwap;
if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
return BSwap;
// reassociate or
if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
return ROR;
// Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
// iff (c1 & c2) != 0.
if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
isa<ConstantSDNode>(N0.getOperand(1))) {
ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
N1C, C1))
return DAG.getNode(
ISD::AND, SDLoc(N), VT,
DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
return SDValue();
}
}
// Simplify: (or (op x...), (op y...)) -> (op (or x, y))
if (N0.getOpcode() == N1.getOpcode())
if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
return Tmp;
// See if this is some rotate idiom.
if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
return SDValue(Rot, 0);
if (SDValue Load = MatchLoadCombine(N))
return Load;
// Simplify the operands using demanded-bits information.
if (!VT.isVector() &&
SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
return SDValue();
}
/// Match "(X shl/srl V1) & V2" where V2 may not be present.
bool DAGCombiner::MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
if (Op.getOpcode() == ISD::AND) {
if (DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
Mask = Op.getOperand(1);
Op = Op.getOperand(0);
} else {
return false;
}
}
if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
Shift = Op;
return true;
}
return false;
}
// Return true if we can prove that, whenever Neg and Pos are both in the
// range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
//
// (or (shift1 X, Neg), (shift2 X, Pos))
//
// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
// in direction shift1 by Neg. The range [0, EltSize) means that we only need
// to consider shift amounts with defined behavior.
static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize) {
// If EltSize is a power of 2 then:
//
// (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
// (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
//
// So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
// for the stronger condition:
//
// Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
//
// for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
// we can just replace Neg with Neg' for the rest of the function.
//
// In other cases we check for the even stronger condition:
//
// Neg == EltSize - Pos [B]
//
// for all Neg and Pos. Note that the (or ...) then invokes undefined
// behavior if Pos == 0 (and consequently Neg == EltSize).
//
// We could actually use [A] whenever EltSize is a power of 2, but the
// only extra cases that it would match are those uninteresting ones
// where Neg and Pos are never in range at the same time. E.g. for
// EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
// as well as (sub 32, Pos), but:
//
// (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
//
// always invokes undefined behavior for 32-bit X.
//
// Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
unsigned MaskLoBits = 0;
if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
if (NegC->getAPIntValue() == EltSize - 1) {
Neg = Neg.getOperand(0);
MaskLoBits = Log2_64(EltSize);
}
}
}
// Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
if (Neg.getOpcode() != ISD::SUB)
return false;
ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
if (!NegC)
return false;
SDValue NegOp1 = Neg.getOperand(1);
// On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
// Pos'. The truncation is redundant for the purpose of the equality.
if (MaskLoBits && Pos.getOpcode() == ISD::AND)
if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
if (PosC->getAPIntValue() == EltSize - 1)
Pos = Pos.getOperand(0);
// The condition we need is now:
//
// (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
//
// If NegOp1 == Pos then we need:
//
// EltSize & Mask == NegC & Mask
//
// (because "x & Mask" is a truncation and distributes through subtraction).
APInt Width;
if (Pos == NegOp1)
Width = NegC->getAPIntValue();
// Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
// Then the condition we want to prove becomes:
//
// (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
//
// which, again because "x & Mask" is a truncation, becomes:
//
// NegC & Mask == (EltSize - PosC) & Mask
// EltSize & Mask == (NegC + PosC) & Mask
else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
Width = PosC->getAPIntValue() + NegC->getAPIntValue();
else
return false;
} else
return false;
// Now we just need to check that EltSize & Mask == Width & Mask.
if (MaskLoBits)
// EltSize & Mask is 0 since Mask is EltSize - 1.
return Width.getLoBits(MaskLoBits) == 0;
return Width == EltSize;
}
// A subroutine of MatchRotate used once we have found an OR of two opposite
// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
// former being preferred if supported. InnerPos and InnerNeg are Pos and
// Neg with outer conversions stripped away.
SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
SDValue Neg, SDValue InnerPos,
SDValue InnerNeg, unsigned PosOpcode,
unsigned NegOpcode, const SDLoc &DL) {
// fold (or (shl x, (*ext y)),
// (srl x, (*ext (sub 32, y)))) ->
// (rotl x, y) or (rotr x, (sub 32, y))
//
// fold (or (shl x, (*ext (sub 32, y))),
// (srl x, (*ext y))) ->
// (rotr x, y) or (rotl x, (sub 32, y))
EVT VT = Shifted.getValueType();
if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits())) {
bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
HasPos ? Pos : Neg).getNode();
}
return nullptr;
}
// MatchRotate - Handle an 'or' of two operands. If this is one of the many
// idioms for rotate, and if the target supports rotation instructions, generate
// a rot[lr].
SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
// Must be a legal type. Expanded 'n promoted things won't work with rotates.
EVT VT = LHS.getValueType();
if (!TLI.isTypeLegal(VT)) return nullptr;
// The target must have at least one rotate flavor.
bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
if (!HasROTL && !HasROTR) return nullptr;
// Match "(X shl/srl V1) & V2" where V2 may not be present.
SDValue LHSShift; // The shift.
SDValue LHSMask; // AND value if any.
if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
return nullptr; // Not part of a rotate.
SDValue RHSShift; // The shift.
SDValue RHSMask; // AND value if any.
if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
return nullptr; // Not part of a rotate.
if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
return nullptr; // Not shifting the same value.
if (LHSShift.getOpcode() == RHSShift.getOpcode())
return nullptr; // Shifts must disagree.
// Canonicalize shl to left side in a shl/srl pair.
if (RHSShift.getOpcode() == ISD::SHL) {
std::swap(LHS, RHS);
std::swap(LHSShift, RHSShift);
std::swap(LHSMask, RHSMask);
}
unsigned EltSizeInBits = VT.getScalarSizeInBits();
SDValue LHSShiftArg = LHSShift.getOperand(0);
SDValue LHSShiftAmt = LHSShift.getOperand(1);
SDValue RHSShiftArg = RHSShift.getOperand(0);
SDValue RHSShiftAmt = RHSShift.getOperand(1);
// fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
// fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
if (isConstOrConstSplat(LHSShiftAmt) && isConstOrConstSplat(RHSShiftAmt)) {
uint64_t LShVal = isConstOrConstSplat(LHSShiftAmt)->getZExtValue();
uint64_t RShVal = isConstOrConstSplat(RHSShiftAmt)->getZExtValue();
if ((LShVal + RShVal) != EltSizeInBits)
return nullptr;
SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
// If there is an AND of either shifted operand, apply it to the result.
if (LHSMask.getNode() || RHSMask.getNode()) {
SDValue Mask = DAG.getAllOnesConstant(DL, VT);
if (LHSMask.getNode()) {
APInt RHSBits = APInt::getLowBitsSet(EltSizeInBits, LShVal);
Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
DAG.getNode(ISD::OR, DL, VT, LHSMask,
DAG.getConstant(RHSBits, DL, VT)));
}
if (RHSMask.getNode()) {
APInt LHSBits = APInt::getHighBitsSet(EltSizeInBits, RShVal);
Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
DAG.getNode(ISD::OR, DL, VT, RHSMask,
DAG.getConstant(LHSBits, DL, VT)));
}
Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask);
}
return Rot.getNode();
}
// If there is a mask here, and we have a variable shift, we can't be sure
// that we're masking out the right stuff.
if (LHSMask.getNode() || RHSMask.getNode())
return nullptr;
// If the shift amount is sign/zext/any-extended just peel it off.
SDValue LExtOp0 = LHSShiftAmt;
SDValue RExtOp0 = RHSShiftAmt;
if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
(RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
LExtOp0 = LHSShiftAmt.getOperand(0);
RExtOp0 = RHSShiftAmt.getOperand(0);
}
SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
if (TryL)
return TryL;
SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
if (TryR)
return TryR;
return nullptr;
}
namespace {
/// Helper struct to parse and store a memory address as base + index + offset.
/// We ignore sign extensions when it is safe to do so.
/// The following two expressions are not equivalent. To differentiate we need
/// to store whether there was a sign extension involved in the index
/// computation.
/// (load (i64 add (i64 copyfromreg %c)
/// (i64 signextend (add (i8 load %index)
/// (i8 1))))
/// vs
///
/// (load (i64 add (i64 copyfromreg %c)
/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
/// (i32 1)))))
struct BaseIndexOffset {
SDValue Base;
SDValue Index;
int64_t Offset;
bool IsIndexSignExt;
BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
bool IsIndexSignExt) :
Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
bool equalBaseIndex(const BaseIndexOffset &Other) {
return Other.Base == Base && Other.Index == Index &&
Other.IsIndexSignExt == IsIndexSignExt;
}
/// Parses tree in Ptr for base, index, offset addresses.
static BaseIndexOffset match(SDValue Ptr, SelectionDAG &DAG,
int64_t PartialOffset = 0) {
bool IsIndexSignExt = false;
// Split up a folded GlobalAddress+Offset into its component parts.
if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ptr))
if (GA->getOpcode() == ISD::GlobalAddress && GA->getOffset() != 0) {
return BaseIndexOffset(DAG.getGlobalAddress(GA->getGlobal(),
SDLoc(GA),
GA->getValueType(0),
/*Offset=*/PartialOffset,
/*isTargetGA=*/false,
GA->getTargetFlags()),
SDValue(),
GA->getOffset(),
IsIndexSignExt);
}
// We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
// instruction, then it could be just the BASE or everything else we don't
// know how to handle. Just use Ptr as BASE and give up.
if (Ptr->getOpcode() != ISD::ADD)
return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
// We know that we have at least an ADD instruction. Try to pattern match
// the simple case of BASE + OFFSET.
if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
return match(Ptr->getOperand(0), DAG, Offset + PartialOffset);
}
// Inside a loop the current BASE pointer is calculated using an ADD and a
// MUL instruction. In this case Ptr is the actual BASE pointer.
// (i64 add (i64 %array_ptr)
// (i64 mul (i64 %induction_var)
// (i64 %element_size)))
if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
// Look at Base + Index + Offset cases.
SDValue Base = Ptr->getOperand(0);
SDValue IndexOffset = Ptr->getOperand(1);
// Skip signextends.
if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
IndexOffset = IndexOffset->getOperand(0);
IsIndexSignExt = true;
}
// Either the case of Base + Index (no offset) or something else.
if (IndexOffset->getOpcode() != ISD::ADD)
return BaseIndexOffset(Base, IndexOffset, PartialOffset, IsIndexSignExt);
// Now we have the case of Base + Index + offset.
SDValue Index = IndexOffset->getOperand(0);
SDValue Offset = IndexOffset->getOperand(1);
if (!isa<ConstantSDNode>(Offset))
return BaseIndexOffset(Ptr, SDValue(), PartialOffset, IsIndexSignExt);
// Ignore signextends.
if (Index->getOpcode() == ISD::SIGN_EXTEND) {
Index = Index->getOperand(0);
IsIndexSignExt = true;
} else IsIndexSignExt = false;
int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
return BaseIndexOffset(Base, Index, Off + PartialOffset, IsIndexSignExt);
}
};
} // namespace
namespace {
/// Represents known origin of an individual byte in load combine pattern. The
/// value of the byte is either constant zero or comes from memory.
struct ByteProvider {
// For constant zero providers Load is set to nullptr. For memory providers
// Load represents the node which loads the byte from memory.
// ByteOffset is the offset of the byte in the value produced by the load.
LoadSDNode *Load;
unsigned ByteOffset;
ByteProvider() : Load(nullptr), ByteOffset(0) {}
static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
return ByteProvider(Load, ByteOffset);
}
static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
bool isConstantZero() const { return !Load; }
bool isMemory() const { return Load; }
bool operator==(const ByteProvider &Other) const {
return Other.Load == Load && Other.ByteOffset == ByteOffset;
}
private:
ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
: Load(Load), ByteOffset(ByteOffset) {}
};
/// Recursively traverses the expression calculating the origin of the requested
/// byte of the given value. Returns None if the provider can't be calculated.
///
/// For all the values except the root of the expression verifies that the value
/// has exactly one use and if it's not true return None. This way if the origin
/// of the byte is returned it's guaranteed that the values which contribute to
/// the byte are not used outside of this expression.
///
/// Because the parts of the expression are not allowed to have more than one
/// use this function iterates over trees, not DAGs. So it never visits the same
/// node more than once.
const Optional<ByteProvider> calculateByteProvider(SDValue Op, unsigned Index,
unsigned Depth,
bool Root = false) {
// Typical i64 by i8 pattern requires recursion up to 8 calls depth
if (Depth == 10)
return None;
if (!Root && !Op.hasOneUse())
return None;
assert(Op.getValueType().isScalarInteger() && "can't handle other types");
unsigned BitWidth = Op.getValueSizeInBits();
if (BitWidth % 8 != 0)
return None;
unsigned ByteWidth = BitWidth / 8;
assert(Index < ByteWidth && "invalid index requested");
(void) ByteWidth;
switch (Op.getOpcode()) {
case ISD::OR: {
auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
if (!LHS)
return None;
auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
if (!RHS)
return None;
if (LHS->isConstantZero())
return RHS;
if (RHS->isConstantZero())
return LHS;
return None;
}
case ISD::SHL: {
auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
if (!ShiftOp)
return None;
uint64_t BitShift = ShiftOp->getZExtValue();
if (BitShift % 8 != 0)
return None;
uint64_t ByteShift = BitShift / 8;
return Index < ByteShift
? ByteProvider::getConstantZero()
: calculateByteProvider(Op->getOperand(0), Index - ByteShift,
Depth + 1);
}
case ISD::ANY_EXTEND:
case ISD::SIGN_EXTEND:
case ISD::ZERO_EXTEND: {
SDValue NarrowOp = Op->getOperand(0);
unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
if (NarrowBitWidth % 8 != 0)
return None;
uint64_t NarrowByteWidth = NarrowBitWidth / 8;
if (Index >= NarrowByteWidth)
return Op.getOpcode() == ISD::ZERO_EXTEND
? Optional<ByteProvider>(ByteProvider::getConstantZero())
: None;
return calculateByteProvider(NarrowOp, Index, Depth + 1);
}
case ISD::BSWAP:
return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
Depth + 1);
case ISD::LOAD: {
auto L = cast<LoadSDNode>(Op.getNode());
if (L->isVolatile() || L->isIndexed())
return None;
unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
if (NarrowBitWidth % 8 != 0)
return None;
uint64_t NarrowByteWidth = NarrowBitWidth / 8;
if (Index >= NarrowByteWidth)
return L->getExtensionType() == ISD::ZEXTLOAD
? Optional<ByteProvider>(ByteProvider::getConstantZero())
: None;
return ByteProvider::getMemory(L, Index);
}
}
return None;
}
} // namespace
/// Match a pattern where a wide type scalar value is loaded by several narrow
/// loads and combined by shifts and ors. Fold it into a single load or a load
/// and a BSWAP if the targets supports it.
///
/// Assuming little endian target:
/// i8 *a = ...
/// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
/// =>
/// i32 val = *((i32)a)
///
/// i8 *a = ...
/// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
/// =>
/// i32 val = BSWAP(*((i32)a))
///
/// TODO: This rule matches complex patterns with OR node roots and doesn't
/// interact well with the worklist mechanism. When a part of the pattern is
/// updated (e.g. one of the loads) its direct users are put into the worklist,
/// but the root node of the pattern which triggers the load combine is not
/// necessarily a direct user of the changed node. For example, once the address
/// of t28 load is reassociated load combine won't be triggered:
/// t25: i32 = add t4, Constant:i32<2>
/// t26: i64 = sign_extend t25
/// t27: i64 = add t2, t26
/// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
/// t29: i32 = zero_extend t28
/// t32: i32 = shl t29, Constant:i8<8>
/// t33: i32 = or t23, t32
/// As a possible fix visitLoad can check if the load can be a part of a load
/// combine pattern and add corresponding OR roots to the worklist.
SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
assert(N->getOpcode() == ISD::OR &&
"Can only match load combining against OR nodes");
// Handles simple types only
EVT VT = N->getValueType(0);
if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
return SDValue();
unsigned ByteWidth = VT.getSizeInBits() / 8;
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
// Before legalize we can introduce too wide illegal loads which will be later
// split into legal sized loads. This enables us to combine i64 load by i8
// patterns to a couple of i32 loads on 32 bit targets.
if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT))
return SDValue();
std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = [](
unsigned BW, unsigned i) { return i; };
std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = [](
unsigned BW, unsigned i) { return BW - i - 1; };
bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
auto MemoryByteOffset = [&] (ByteProvider P) {
assert(P.isMemory() && "Must be a memory byte provider");
unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
assert(LoadBitWidth % 8 == 0 &&
"can only analyze providers for individual bytes not bit");
unsigned LoadByteWidth = LoadBitWidth / 8;
return IsBigEndianTarget
? BigEndianByteAt(LoadByteWidth, P.ByteOffset)
: LittleEndianByteAt(LoadByteWidth, P.ByteOffset);
};
Optional<BaseIndexOffset> Base;
SDValue Chain;
SmallSet<LoadSDNode *, 8> Loads;
Optional<ByteProvider> FirstByteProvider;
int64_t FirstOffset = INT64_MAX;
// Check if all the bytes of the OR we are looking at are loaded from the same
// base address. Collect bytes offsets from Base address in ByteOffsets.
SmallVector<int64_t, 4> ByteOffsets(ByteWidth);
for (unsigned i = 0; i < ByteWidth; i++) {
auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
if (!P || !P->isMemory()) // All the bytes must be loaded from memory
return SDValue();
LoadSDNode *L = P->Load;
assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() &&
"Must be enforced by calculateByteProvider");
assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
// All loads must share the same chain
SDValue LChain = L->getChain();
if (!Chain)
Chain = LChain;
else if (Chain != LChain)
return SDValue();
// Loads must share the same base address
BaseIndexOffset Ptr = BaseIndexOffset::match(L->getBasePtr(), DAG);
if (!Base)
Base = Ptr;
else if (!Base->equalBaseIndex(Ptr))
return SDValue();
// Calculate the offset of the current byte from the base address
int64_t ByteOffsetFromBase = Ptr.Offset + MemoryByteOffset(*P);
ByteOffsets[i] = ByteOffsetFromBase;
// Remember the first byte load
if (ByteOffsetFromBase < FirstOffset) {
FirstByteProvider = P;
FirstOffset = ByteOffsetFromBase;
}
Loads.insert(L);
}
assert(Loads.size() > 0 && "All the bytes of the value must be loaded from "
"memory, so there must be at least one load which produces the value");
assert(Base && "Base address of the accessed memory location must be set");
assert(FirstOffset != INT64_MAX && "First byte offset must be set");
// Check if the bytes of the OR we are looking at match with either big or
// little endian value load
bool BigEndian = true, LittleEndian = true;
for (unsigned i = 0; i < ByteWidth; i++) {
int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i);
BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i);
if (!BigEndian && !LittleEndian)
return SDValue();
}
assert((BigEndian != LittleEndian) && "should be either or");
assert(FirstByteProvider && "must be set");
// Ensure that the first byte is loaded from zero offset of the first load.
// So the combined value can be loaded from the first load address.
if (MemoryByteOffset(*FirstByteProvider) != 0)
return SDValue();
LoadSDNode *FirstLoad = FirstByteProvider->Load;
// The node we are looking at matches with the pattern, check if we can
// replace it with a single load and bswap if needed.
// If the load needs byte swap check if the target supports it
bool NeedsBswap = IsBigEndianTarget != BigEndian;
// Before legalize we can introduce illegal bswaps which will be later
// converted to an explicit bswap sequence. This way we end up with a single
// load and byte shuffling instead of several loads and byte shuffling.
if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT))
return SDValue();
// Check that a load of the wide type is both allowed and fast on the target
bool Fast = false;
bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
VT, FirstLoad->getAddressSpace(),
FirstLoad->getAlignment(), &Fast);
if (!Allowed || !Fast)
return SDValue();
SDValue NewLoad =
DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(),
FirstLoad->getPointerInfo(), FirstLoad->getAlignment());
// Transfer chain users from old loads to the new load.
for (LoadSDNode *L : Loads)
DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad;
}
SDValue DAGCombiner::visitXOR(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
// fold vector ops
if (VT.isVector()) {
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (xor x, 0) -> x, vector edition
if (ISD::isBuildVectorAllZeros(N0.getNode()))
return N1;
if (ISD::isBuildVectorAllZeros(N1.getNode()))
return N0;
}
// fold (xor undef, undef) -> 0. This is a common idiom (misuse).
if (N0.isUndef() && N1.isUndef())
return DAG.getConstant(0, SDLoc(N), VT);
// fold (xor x, undef) -> undef
if (N0.isUndef())
return N0;
if (N1.isUndef())
return N1;
// fold (xor c1, c2) -> c1^c2
ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
if (N0C && N1C)
return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
// canonicalize constant to RHS
if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
!DAG.isConstantIntBuildVectorOrConstantInt(N1))
return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
// fold (xor x, 0) -> x
if (isNullConstant(N1))
return N0;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// reassociate xor
if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
return RXOR;
// fold !(x cc y) -> (x !cc y)
SDValue LHS, RHS, CC;
if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
bool isInt = LHS.getValueType().isInteger();
ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
isInt);
if (!LegalOperations ||
TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
switch (N0.getOpcode()) {
default:
llvm_unreachable("Unhandled SetCC Equivalent!");
case ISD::SETCC:
return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
case ISD::SELECT_CC:
return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
N0.getOperand(3), NotCC);
}
}
}
// fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
N0.getNode()->hasOneUse() &&
isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
SDValue V = N0.getOperand(0);
SDLoc DL(N0);
V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
DAG.getConstant(1, DL, V.getValueType()));
AddToWorklist(V.getNode());
return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
}
// fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
if (isOneConstant(N1) && VT == MVT::i1 &&
(N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
}
}
// fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
if (isAllOnesConstant(N1) &&
(N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
}
}
// fold (xor (and x, y), y) -> (and (not x), y)
if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
N0->getOperand(1) == N1) {
SDValue X = N0->getOperand(0);
SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
AddToWorklist(NotX.getNode());
return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
}
// fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
if (N1C && N0.getOpcode() == ISD::XOR) {
if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
SDLoc DL(N);
return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
DAG.getConstant(N1C->getAPIntValue() ^
N00C->getAPIntValue(), DL, VT));
}
if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
SDLoc DL(N);
return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
DAG.getConstant(N1C->getAPIntValue() ^
N01C->getAPIntValue(), DL, VT));
}
}
// fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
unsigned OpSizeInBits = VT.getScalarSizeInBits();
if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0) &&
TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
if (C->getAPIntValue() == (OpSizeInBits - 1))
return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0.getOperand(0));
}
// fold (xor x, x) -> 0
if (N0 == N1)
return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
// fold (xor (shl 1, x), -1) -> (rotl ~1, x)
// Here is a concrete example of this equivalence:
// i16 x == 14
// i16 shl == 1 << 14 == 16384 == 0b0100000000000000
// i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
//
// =>
//
// i16 ~1 == 0b1111111111111110
// i16 rol(~1, 14) == 0b1011111111111111
//
// Some additional tips to help conceptualize this transform:
// - Try to see the operation as placing a single zero in a value of all ones.
// - There exists no value for x which would allow the result to contain zero.
// - Values of x larger than the bitwidth are undefined and do not require a
// consistent result.
// - Pushing the zero left requires shifting one bits in from the right.
// A rotate left of ~1 is a nice way of achieving the desired result.
if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
&& isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
SDLoc DL(N);
return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
N0.getOperand(1));
}
// Simplify: xor (op x...), (op y...) -> (op (xor x, y))
if (N0.getOpcode() == N1.getOpcode())
if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
return Tmp;
// Simplify the expression using non-local knowledge.
if (!VT.isVector() &&
SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
return SDValue();
}
/// Handle transforms common to the three shifts, when the shift amount is a
/// constant.
SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
SDNode *LHS = N->getOperand(0).getNode();
if (!LHS->hasOneUse()) return SDValue();
// We want to pull some binops through shifts, so that we have (and (shift))
// instead of (shift (and)), likewise for add, or, xor, etc. This sort of
// thing happens with address calculations, so it's important to canonicalize
// it.
bool HighBitSet = false; // Can we transform this if the high bit is set?
switch (LHS->getOpcode()) {
default: return SDValue();
case ISD::OR:
case ISD::XOR:
HighBitSet = false; // We can only transform sra if the high bit is clear.
break;
case ISD::AND:
HighBitSet = true; // We can only transform sra if the high bit is set.
break;
case ISD::ADD:
if (N->getOpcode() != ISD::SHL)
return SDValue(); // only shl(add) not sr[al](add).
HighBitSet = false; // We can only transform sra if the high bit is clear.
break;
}
// We require the RHS of the binop to be a constant and not opaque as well.
ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
if (!BinOpCst) return SDValue();
// FIXME: disable this unless the input to the binop is a shift by a constant
// or is copy/select.Enable this in other cases when figure out it's exactly profitable.
SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL ||
BinOpLHSVal->getOpcode() == ISD::SRA ||
BinOpLHSVal->getOpcode() == ISD::SRL;
bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg ||
BinOpLHSVal->getOpcode() == ISD::SELECT;
if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) &&
!isCopyOrSelect)
return SDValue();
if (isCopyOrSelect && N->hasOneUse())
return SDValue();
EVT VT = N->getValueType(0);
// If this is a signed shift right, and the high bit is modified by the
// logical operation, do not perform the transformation. The highBitSet
// boolean indicates the value of the high bit of the constant which would
// cause it to be modified for this operation.
if (N->getOpcode() == ISD::SRA) {
bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
if (BinOpRHSSignSet != HighBitSet)
return SDValue();
}
if (!TLI.isDesirableToCommuteWithShift(LHS))
return SDValue();
// Fold the constants, shifting the binop RHS by the shift amount.
SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
N->getValueType(0),
LHS->getOperand(1), N->getOperand(1));
assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
// Create the new shift.
SDValue NewShift = DAG.getNode(N->getOpcode(),
SDLoc(LHS->getOperand(0)),
VT, LHS->getOperand(0), N->getOperand(1));
// Create the new binop.
return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
}
SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
assert(N->getOpcode() == ISD::TRUNCATE);
assert(N->getOperand(0).getOpcode() == ISD::AND);
// (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
SDValue N01 = N->getOperand(0).getOperand(1);
if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
SDLoc DL(N);
EVT TruncVT = N->getValueType(0);
SDValue N00 = N->getOperand(0).getOperand(0);
SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
AddToWorklist(Trunc00.getNode());
AddToWorklist(Trunc01.getNode());
return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
}
}
return SDValue();
}
SDValue DAGCombiner::visitRotate(SDNode *N) {
// fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
if (SDValue NewOp1 =
distributeTruncateThroughAnd(N->getOperand(1).getNode()))
return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
N->getOperand(0), NewOp1);
}
return SDValue();
}
SDValue DAGCombiner::visitSHL(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
unsigned OpSizeInBits = VT.getScalarSizeInBits();
// fold vector ops
if (VT.isVector()) {
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
// If setcc produces all-one true value then:
// (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
if (N1CV && N1CV->isConstant()) {
if (N0.getOpcode() == ISD::AND) {
SDValue N00 = N0->getOperand(0);
SDValue N01 = N0->getOperand(1);
BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
TargetLowering::ZeroOrNegativeOneBooleanContent) {
if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
N01CV, N1CV))
return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
}
}
}
}
ConstantSDNode *N1C = isConstOrConstSplat(N1);
// fold (shl c1, c2) -> c1<<c2
ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
if (N0C && N1C && !N1C->isOpaque())
return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
// fold (shl 0, x) -> 0
if (isNullConstant(N0))
return N0;
// fold (shl x, c >= size(x)) -> undef
if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
return DAG.getUNDEF(VT);
// fold (shl x, 0) -> x
if (N1C && N1C->isNullValue())
return N0;
// fold (shl undef, x) -> 0
if (N0.isUndef())
return DAG.getConstant(0, SDLoc(N), VT);
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// if (shl x, c) is known to be zero, return 0
if (DAG.MaskedValueIsZero(SDValue(N, 0),
APInt::getAllOnesValue(OpSizeInBits)))
return DAG.getConstant(0, SDLoc(N), VT);
// fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
if (N1.getOpcode() == ISD::TRUNCATE &&
N1.getOperand(0).getOpcode() == ISD::AND) {
if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
}
if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
// fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
if (N1C && N0.getOpcode() == ISD::SHL) {
if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
SDLoc DL(N);
APInt c1 = N0C1->getAPIntValue();
APInt c2 = N1C->getAPIntValue();
zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
APInt Sum = c1 + c2;
if (Sum.uge(OpSizeInBits))
return DAG.getConstant(0, DL, VT);
return DAG.getNode(
ISD::SHL, DL, VT, N0.getOperand(0),
DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
}
}
// fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
// For this to be valid, the second form must not preserve any of the bits
// that are shifted out by the inner shift in the first form. This means
// the outer shift size must be >= the number of bits added by the ext.
// As a corollary, we don't care what kind of ext it is.
if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
N0.getOpcode() == ISD::ANY_EXTEND ||
N0.getOpcode() == ISD::SIGN_EXTEND) &&
N0.getOperand(0).getOpcode() == ISD::SHL) {
SDValue N0Op0 = N0.getOperand(0);
if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
APInt c1 = N0Op0C1->getAPIntValue();
APInt c2 = N1C->getAPIntValue();
zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
EVT InnerShiftVT = N0Op0.getValueType();
uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
if (c2.uge(OpSizeInBits - InnerShiftSize)) {
SDLoc DL(N0);
APInt Sum = c1 + c2;
if (Sum.uge(OpSizeInBits))
return DAG.getConstant(0, DL, VT);
return DAG.getNode(
ISD::SHL, DL, VT,
DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)),
DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
}
}
}
// fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
// Only fold this if the inner zext has no other uses to avoid increasing
// the total number of instructions.
if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
N0.getOperand(0).getOpcode() == ISD::SRL) {
SDValue N0Op0 = N0.getOperand(0);
if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) {
uint64_t c1 = N0Op0C1->getZExtValue();
uint64_t c2 = N1C->getZExtValue();
if (c1 == c2) {
SDValue NewOp0 = N0.getOperand(0);
EVT CountVT = NewOp0.getOperand(1).getValueType();
SDLoc DL(N);
SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
NewOp0,
DAG.getConstant(c2, DL, CountVT));
AddToWorklist(NewSHL.getNode());
return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
}
}
}
}
// fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
// fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
uint64_t C1 = N0C1->getZExtValue();
uint64_t C2 = N1C->getZExtValue();
SDLoc DL(N);
if (C1 <= C2)
return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
DAG.getConstant(C2 - C1, DL, N1.getValueType()));
return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
DAG.getConstant(C1 - C2, DL, N1.getValueType()));
}
}
// fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
// (and (srl x, (sub c1, c2), MASK)
// Only fold this if the inner shift has no other uses -- if it does, folding
// this will increase the total number of instructions.
if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
uint64_t c1 = N0C1->getZExtValue();
if (c1 < OpSizeInBits) {
uint64_t c2 = N1C->getZExtValue();
APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
SDValue Shift;
if (c2 > c1) {
Mask = Mask.shl(c2 - c1);
SDLoc DL(N);
Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
DAG.getConstant(c2 - c1, DL, N1.getValueType()));
} else {
Mask = Mask.lshr(c1 - c2);
SDLoc DL(N);
Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
DAG.getConstant(c1 - c2, DL, N1.getValueType()));
}
SDLoc DL(N0);
return DAG.getNode(ISD::AND, DL, VT, Shift,
DAG.getConstant(Mask, DL, VT));
}
}
}
// fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
isConstantOrConstantVector(N1, /* No Opaques */ true)) {
SDLoc DL(N);
SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
}
// fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
// Variant of version done on multiply, except mul by a power of 2 is turned
// into a shift.
if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
isConstantOrConstantVector(N1, /* No Opaques */ true) &&
isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
AddToWorklist(Shl0.getNode());
AddToWorklist(Shl1.getNode());
return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
}
// fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
isConstantOrConstantVector(N1, /* No Opaques */ true) &&
isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
if (isConstantOrConstantVector(Shl))
return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
}
if (N1C && !N1C->isOpaque())
if (SDValue NewSHL = visitShiftByConstant(N, N1C))
return NewSHL;
return SDValue();
}
SDValue DAGCombiner::visitSRA(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
unsigned OpSizeInBits = VT.getScalarSizeInBits();
// Arithmetic shifting an all-sign-bit value is a no-op.
if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
return N0;
// fold vector ops
if (VT.isVector())
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
ConstantSDNode *N1C = isConstOrConstSplat(N1);
// fold (sra c1, c2) -> (sra c1, c2)
ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
if (N0C && N1C && !N1C->isOpaque())
return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
// fold (sra 0, x) -> 0
if (isNullConstant(N0))
return N0;
// fold (sra -1, x) -> -1
if (isAllOnesConstant(N0))
return N0;
// fold (sra x, c >= size(x)) -> undef
if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
return DAG.getUNDEF(VT);
// fold (sra x, 0) -> x
if (N1C && N1C->isNullValue())
return N0;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
// sext_inreg.
if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
if (VT.isVector())
ExtVT = EVT::getVectorVT(*DAG.getContext(),
ExtVT, VT.getVectorNumElements());
if ((!LegalOperations ||
TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
N0.getOperand(0), DAG.getValueType(ExtVT));
}
// fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
if (N1C && N0.getOpcode() == ISD::SRA) {
if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
SDLoc DL(N);
APInt c1 = N0C1->getAPIntValue();
APInt c2 = N1C->getAPIntValue();
zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
APInt Sum = c1 + c2;
if (Sum.uge(OpSizeInBits))
Sum = APInt(OpSizeInBits, OpSizeInBits - 1);
return DAG.getNode(
ISD::SRA, DL, VT, N0.getOperand(0),
DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
}
}
// fold (sra (shl X, m), (sub result_size, n))
// -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
// result_size - n != m.
// If truncate is free for the target sext(shl) is likely to result in better
// code.
if (N0.getOpcode() == ISD::SHL && N1C) {
// Get the two constanst of the shifts, CN0 = m, CN = n.
const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
if (N01C) {
LLVMContext &Ctx = *DAG.getContext();
// Determine what the truncate's result bitsize and type would be.
EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
if (VT.isVector())
TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
// Determine the residual right-shift amount.
int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
// If the shift is not a no-op (in which case this should be just a sign
// extend already), the truncated to type is legal, sign_extend is legal
// on that type, and the truncate to that type is both legal and free,
// perform the transform.
if ((ShiftAmt > 0) &&
TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
TLI.isTruncateFree(VT, TruncVT)) {
SDLoc DL(N);
SDValue Amt = DAG.getConstant(ShiftAmt, DL,
getShiftAmountTy(N0.getOperand(0).getValueType()));
SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
N0.getOperand(0), Amt);
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
Shift);
return DAG.getNode(ISD::SIGN_EXTEND, DL,
N->getValueType(0), Trunc);
}
}
}
// fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
if (N1.getOpcode() == ISD::TRUNCATE &&
N1.getOperand(0).getOpcode() == ISD::AND) {
if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
}
// fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
// if c1 is equal to the number of bits the trunc removes
if (N0.getOpcode() == ISD::TRUNCATE &&
(N0.getOperand(0).getOpcode() == ISD::SRL ||
N0.getOperand(0).getOpcode() == ISD::SRA) &&
N0.getOperand(0).hasOneUse() &&
N0.getOperand(0).getOperand(1).hasOneUse() &&
N1C) {
SDValue N0Op0 = N0.getOperand(0);
if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
unsigned LargeShiftVal = LargeShift->getZExtValue();
EVT LargeVT = N0Op0.getValueType();
if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
SDLoc DL(N);
SDValue Amt =
DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
N0Op0.getOperand(0), Amt);
return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
}
}
}
// Simplify, based on bits shifted out of the LHS.
if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
// If the sign bit is known to be zero, switch this to a SRL.
if (DAG.SignBitIsZero(N0))
return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
if (N1C && !N1C->isOpaque())
if (SDValue NewSRA = visitShiftByConstant(N, N1C))
return NewSRA;
return SDValue();
}
SDValue DAGCombiner::visitSRL(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N0.getValueType();
unsigned OpSizeInBits = VT.getScalarSizeInBits();
// fold vector ops
if (VT.isVector())
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
ConstantSDNode *N1C = isConstOrConstSplat(N1);
// fold (srl c1, c2) -> c1 >>u c2
ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
if (N0C && N1C && !N1C->isOpaque())
return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
// fold (srl 0, x) -> 0
if (isNullConstant(N0))
return N0;
// fold (srl x, c >= size(x)) -> undef
if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
return DAG.getUNDEF(VT);
// fold (srl x, 0) -> x
if (N1C && N1C->isNullValue())
return N0;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// if (srl x, c) is known to be zero, return 0
if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
APInt::getAllOnesValue(OpSizeInBits)))
return DAG.getConstant(0, SDLoc(N), VT);
// fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
if (N1C && N0.getOpcode() == ISD::SRL) {
if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
SDLoc DL(N);
APInt c1 = N0C1->getAPIntValue();
APInt c2 = N1C->getAPIntValue();
zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
APInt Sum = c1 + c2;
if (Sum.uge(OpSizeInBits))
return DAG.getConstant(0, DL, VT);
return DAG.getNode(
ISD::SRL, DL, VT, N0.getOperand(0),
DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType()));
}
}
// fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
N0.getOperand(0).getOpcode() == ISD::SRL &&
isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
uint64_t c1 =
cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
uint64_t c2 = N1C->getZExtValue();
EVT InnerShiftVT = N0.getOperand(0).getValueType();
EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
// This is only valid if the OpSizeInBits + c1 = size of inner shift.
if (c1 + OpSizeInBits == InnerShiftSize) {
SDLoc DL(N0);
if (c1 + c2 >= InnerShiftSize)
return DAG.getConstant(0, DL, VT);
return DAG.getNode(ISD::TRUNCATE, DL, VT,
DAG.getNode(ISD::SRL, DL, InnerShiftVT,
N0.getOperand(0)->getOperand(0),
DAG.getConstant(c1 + c2, DL,
ShiftCountVT)));
}
}
// fold (srl (shl x, c), c) -> (and x, cst2)
if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
SDLoc DL(N);
SDValue Mask =
DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
AddToWorklist(Mask.getNode());
return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
}
// fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
// Shifting in all undef bits?
EVT SmallVT = N0.getOperand(0).getValueType();
unsigned BitSize = SmallVT.getScalarSizeInBits();
if (N1C->getZExtValue() >= BitSize)
return DAG.getUNDEF(VT);
if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
uint64_t ShiftAmt = N1C->getZExtValue();
SDLoc DL0(N0);
SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
N0.getOperand(0),
DAG.getConstant(ShiftAmt, DL0,
getShiftAmountTy(SmallVT)));
AddToWorklist(SmallShift.getNode());
APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
SDLoc DL(N);
return DAG.getNode(ISD::AND, DL, VT,
DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
DAG.getConstant(Mask, DL, VT));
}
}
// fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
// bit, which is unmodified by sra.
if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
if (N0.getOpcode() == ISD::SRA)
return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
}
// fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
if (N1C && N0.getOpcode() == ISD::CTLZ &&
N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
APInt KnownZero, KnownOne;
DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
// If any of the input bits are KnownOne, then the input couldn't be all
// zeros, thus the result of the srl will always be zero.
if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
// If all of the bits input the to ctlz node are known to be zero, then
// the result of the ctlz is "32" and the result of the shift is one.
APInt UnknownBits = ~KnownZero;
if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
// Otherwise, check to see if there is exactly one bit input to the ctlz.
if ((UnknownBits & (UnknownBits - 1)) == 0) {
// Okay, we know that only that the single bit specified by UnknownBits
// could be set on input to the CTLZ node. If this bit is set, the SRL
// will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
// to an SRL/XOR pair, which is likely to simplify more.
unsigned ShAmt = UnknownBits.countTrailingZeros();
SDValue Op = N0.getOperand(0);
if (ShAmt) {
SDLoc DL(N0);
Op = DAG.getNode(ISD::SRL, DL, VT, Op,
DAG.getConstant(ShAmt, DL,
getShiftAmountTy(Op.getValueType())));
AddToWorklist(Op.getNode());
}
SDLoc DL(N);
return DAG.getNode(ISD::XOR, DL, VT,
Op, DAG.getConstant(1, DL, VT));
}
}
// fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
if (N1.getOpcode() == ISD::TRUNCATE &&
N1.getOperand(0).getOpcode() == ISD::AND) {
if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
}
// fold operands of srl based on knowledge that the low bits are not
// demanded.
if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
if (N1C && !N1C->isOpaque())
if (SDValue NewSRL = visitShiftByConstant(N, N1C))
return NewSRL;
// Attempt to convert a srl of a load into a narrower zero-extending load.
if (SDValue NarrowLoad = ReduceLoadWidth(N))
return NarrowLoad;
// Here is a common situation. We want to optimize:
//
// %a = ...
// %b = and i32 %a, 2
// %c = srl i32 %b, 1
// brcond i32 %c ...
//
// into
//
// %a = ...
// %b = and %a, 2
// %c = setcc eq %b, 0
// brcond %c ...
//
// However when after the source operand of SRL is optimized into AND, the SRL
// itself may not be optimized further. Look for it and add the BRCOND into
// the worklist.
if (N->hasOneUse()) {
SDNode *Use = *N->use_begin();
if (Use->getOpcode() == ISD::BRCOND)
AddToWorklist(Use);
else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
// Also look pass the truncate.
Use = *Use->use_begin();
if (Use->getOpcode() == ISD::BRCOND)
AddToWorklist(Use);
}
}
return SDValue();
}
SDValue DAGCombiner::visitABS(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (abs c1) -> c2
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
// fold (abs (abs x)) -> (abs x)
if (N0.getOpcode() == ISD::ABS)
return N0;
// fold (abs x) -> x iff not-negative
if (DAG.SignBitIsZero(N0))
return N0;
return SDValue();
}
SDValue DAGCombiner::visitBSWAP(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (bswap c1) -> c2
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
// fold (bswap (bswap x)) -> x
if (N0.getOpcode() == ISD::BSWAP)
return N0->getOperand(0);
return SDValue();
}
SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (bitreverse c1) -> c2
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
// fold (bitreverse (bitreverse x)) -> x
if (N0.getOpcode() == ISD::BITREVERSE)
return N0.getOperand(0);
return SDValue();
}
SDValue DAGCombiner::visitCTLZ(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (ctlz c1) -> c2
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
return SDValue();
}
SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (ctlz_zero_undef c1) -> c2
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
return SDValue();
}
SDValue DAGCombiner::visitCTTZ(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (cttz c1) -> c2
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
return SDValue();
}
SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (cttz_zero_undef c1) -> c2
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
return SDValue();
}
SDValue DAGCombiner::visitCTPOP(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (ctpop c1) -> c2
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
return SDValue();
}
/// \brief Generate Min/Max node
static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
SDValue RHS, SDValue True, SDValue False,
ISD::CondCode CC, const TargetLowering &TLI,
SelectionDAG &DAG) {
if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
return SDValue();
switch (CC) {
case ISD::SETOLT:
case ISD::SETOLE:
case ISD::SETLT:
case ISD::SETLE:
case ISD::SETULT:
case ISD::SETULE: {
unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
if (TLI.isOperationLegal(Opcode, VT))
return DAG.getNode(Opcode, DL, VT, LHS, RHS);
return SDValue();
}
case ISD::SETOGT:
case ISD::SETOGE:
case ISD::SETGT:
case ISD::SETGE:
case ISD::SETUGT:
case ISD::SETUGE: {
unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
if (TLI.isOperationLegal(Opcode, VT))
return DAG.getNode(Opcode, DL, VT, LHS, RHS);
return SDValue();
}
default:
return SDValue();
}
}
SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
SDValue Cond = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
EVT VT = N->getValueType(0);
EVT CondVT = Cond.getValueType();
SDLoc DL(N);
if (!VT.isInteger())
return SDValue();
auto *C1 = dyn_cast<ConstantSDNode>(N1);
auto *C2 = dyn_cast<ConstantSDNode>(N2);
if (!C1 || !C2)
return SDValue();
// Only do this before legalization to avoid conflicting with target-specific
// transforms in the other direction (create a select from a zext/sext). There
// is also a target-independent combine here in DAGCombiner in the other
// direction for (select Cond, -1, 0) when the condition is not i1.
if (CondVT == MVT::i1 && !LegalOperations) {
if (C1->isNullValue() && C2->isOne()) {
// select Cond, 0, 1 --> zext (!Cond)
SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
if (VT != MVT::i1)
NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
return NotCond;
}
if (C1->isNullValue() && C2->isAllOnesValue()) {
// select Cond, 0, -1 --> sext (!Cond)
SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
if (VT != MVT::i1)
NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
return NotCond;
}
if (C1->isOne() && C2->isNullValue()) {
// select Cond, 1, 0 --> zext (Cond)
if (VT != MVT::i1)
Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
return Cond;
}
if (C1->isAllOnesValue() && C2->isNullValue()) {
// select Cond, -1, 0 --> sext (Cond)
if (VT != MVT::i1)
Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
return Cond;
}
// For any constants that differ by 1, we can transform the select into an
// extend and add. Use a target hook because some targets may prefer to
// transform in the other direction.
if (TLI.convertSelectOfConstantsToMath()) {
if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) {
// select Cond, C1, C1-1 --> add (zext Cond), C1-1
if (VT != MVT::i1)
Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
}
if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) {
// select Cond, C1, C1+1 --> add (sext Cond), C1+1
if (VT != MVT::i1)
Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
}
}
return SDValue();
}
// fold (select Cond, 0, 1) -> (xor Cond, 1)
// We can't do this reliably if integer based booleans have different contents
// to floating point based booleans. This is because we can't tell whether we
// have an integer-based boolean or a floating-point-based boolean unless we
// can find the SETCC that produced it and inspect its operands. This is
// fairly easy if C is the SETCC node, but it can potentially be
// undiscoverable (or not reasonably discoverable). For example, it could be
// in another basic block or it could require searching a complicated
// expression.
if (CondVT.isInteger() &&
TLI.getBooleanContents(false, true) ==
TargetLowering::ZeroOrOneBooleanContent &&
TLI.getBooleanContents(false, false) ==
TargetLowering::ZeroOrOneBooleanContent &&
C1->isNullValue() && C2->isOne()) {
SDValue NotCond =
DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
if (VT.bitsEq(CondVT))
return NotCond;
return DAG.getZExtOrTrunc(NotCond, DL, VT);
}
return SDValue();
}
SDValue DAGCombiner::visitSELECT(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
EVT VT = N->getValueType(0);
EVT VT0 = N0.getValueType();
// fold (select C, X, X) -> X
if (N1 == N2)
return N1;
if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
// fold (select true, X, Y) -> X
// fold (select false, X, Y) -> Y
return !N0C->isNullValue() ? N1 : N2;
}
// fold (select X, X, Y) -> (or X, Y)
// fold (select X, 1, Y) -> (or C, Y)
if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
if (SDValue V = foldSelectOfConstants(N))
return V;
// fold (select C, 0, X) -> (and (not C), X)
if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
AddToWorklist(NOTNode.getNode());
return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
}
// fold (select C, X, 1) -> (or (not C), X)
if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
AddToWorklist(NOTNode.getNode());
return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
}
// fold (select X, Y, X) -> (and X, Y)
// fold (select X, Y, 0) -> (and X, Y)
if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
// If we can fold this based on the true/false value, do so.
if (SimplifySelectOps(N, N1, N2))
return SDValue(N, 0); // Don't revisit N.
if (VT0 == MVT::i1) {
// The code in this block deals with the following 2 equivalences:
// select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
// select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
// The target can specify its preferred form with the
// shouldNormalizeToSelectSequence() callback. However we always transform
// to the right anyway if we find the inner select exists in the DAG anyway
// and we always transform to the left side if we know that we can further
// optimize the combination of the conditions.
bool normalizeToSequence
= TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
// select (and Cond0, Cond1), X, Y
// -> select Cond0, (select Cond1, X, Y), Y
if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
SDValue Cond0 = N0->getOperand(0);
SDValue Cond1 = N0->getOperand(1);
SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
N1.getValueType(), Cond1, N1, N2);
if (normalizeToSequence || !InnerSelect.use_empty())
return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
InnerSelect, N2);
}
// select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
SDValue Cond0 = N0->getOperand(0);
SDValue Cond1 = N0->getOperand(1);
SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
N1.getValueType(), Cond1, N1, N2);
if (normalizeToSequence || !InnerSelect.use_empty())
return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
InnerSelect);
}
// select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
SDValue N1_0 = N1->getOperand(0);
SDValue N1_1 = N1->getOperand(1);
SDValue N1_2 = N1->getOperand(2);
if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
// Create the actual and node if we can generate good code for it.
if (!normalizeToSequence) {
SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
N0, N1_0);
return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
N1_1, N2);
}
// Otherwise see if we can optimize the "and" to a better pattern.
if (SDValue Combined = visitANDLike(N0, N1_0, N))
return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
N1_1, N2);
}
}
// select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
SDValue N2_0 = N2->getOperand(0);
SDValue N2_1 = N2->getOperand(1);
SDValue N2_2 = N2->getOperand(2);
if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
// Create the actual or node if we can generate good code for it.
if (!normalizeToSequence) {
SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
N0, N2_0);
return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
N1, N2_2);
}
// Otherwise see if we can optimize to a better pattern.
if (SDValue Combined = visitORLike(N0, N2_0, N))
return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
N1, N2_2);
}
}
}
// select (xor Cond, 1), X, Y -> select Cond, Y, X
if (VT0 == MVT::i1) {
if (N0->getOpcode() == ISD::XOR) {
if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) {
SDValue Cond0 = N0->getOperand(0);
if (C->isOne())
return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(),
Cond0, N2, N1);
}
}
}
// fold selects based on a setcc into other things, such as min/max/abs
if (N0.getOpcode() == ISD::SETCC) {
// select x, y (fcmp lt x, y) -> fminnum x, y
// select x, y (fcmp gt x, y) -> fmaxnum x, y
//
// This is OK if we don't care about what happens if either operand is a
// NaN.
//
// FIXME: Instead of testing for UnsafeFPMath, this should be checking for
// no signed zeros as well as no nans.
const TargetOptions &Options = DAG.getTarget().Options;
if (Options.UnsafeFPMath &&
VT.isFloatingPoint() && N0.hasOneUse() &&
DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
N0.getOperand(1), N1, N2, CC,
TLI, DAG))
return FMinMax;
}
if ((!LegalOperations &&
TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
TLI.isOperationLegal(ISD::SELECT_CC, VT))
return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
N0.getOperand(0), N0.getOperand(1),
N1, N2, N0.getOperand(2));
return SimplifySelect(SDLoc(N), N0, N1, N2);
}
return SDValue();
}
static
std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
SDLoc DL(N);
EVT LoVT, HiVT;
std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
// Split the inputs.
SDValue Lo, Hi, LL, LH, RL, RH;
std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
return std::make_pair(Lo, Hi);
}
// This function assumes all the vselect's arguments are CONCAT_VECTOR
// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
SDLoc DL(N);
SDValue Cond = N->getOperand(0);
SDValue LHS = N->getOperand(1);
SDValue RHS = N->getOperand(2);
EVT VT = N->getValueType(0);
int NumElems = VT.getVectorNumElements();
assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
RHS.getOpcode() == ISD::CONCAT_VECTORS &&
Cond.getOpcode() == ISD::BUILD_VECTOR);
// CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
// binary ones here.
if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
return SDValue();
// We're sure we have an even number of elements due to the
// concat_vectors we have as arguments to vselect.
// Skip BV elements until we find one that's not an UNDEF
// After we find an UNDEF element, keep looping until we get to half the
// length of the BV and see if all the non-undef nodes are the same.
ConstantSDNode *BottomHalf = nullptr;
for (int i = 0; i < NumElems / 2; ++i) {
if (Cond->getOperand(i)->isUndef())
continue;
if (BottomHalf == nullptr)
BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
else if (Cond->getOperand(i).getNode() != BottomHalf)
return SDValue();
}
// Do the same for the second half of the BuildVector
ConstantSDNode *TopHalf = nullptr;
for (int i = NumElems / 2; i < NumElems; ++i) {
if (Cond->getOperand(i)->isUndef())
continue;
if (TopHalf == nullptr)
TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
else if (Cond->getOperand(i).getNode() != TopHalf)
return SDValue();
}
assert(TopHalf && BottomHalf &&
"One half of the selector was all UNDEFs and the other was all the "
"same value. This should have been addressed before this function.");
return DAG.getNode(
ISD::CONCAT_VECTORS, DL, VT,
BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
}
SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
if (Level >= AfterLegalizeTypes)
return SDValue();
MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
SDValue Mask = MSC->getMask();
SDValue Data = MSC->getValue();
SDLoc DL(N);
// If the MSCATTER data type requires splitting and the mask is provided by a
// SETCC, then split both nodes and its operands before legalization. This
// prevents the type legalizer from unrolling SETCC into scalar comparisons
// and enables future optimizations (e.g. min/max pattern matching on X86).
if (Mask.getOpcode() != ISD::SETCC)
return SDValue();
// Check if any splitting is required.
if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
TargetLowering::TypeSplitVector)
return SDValue();
SDValue MaskLo, MaskHi, Lo, Hi;
std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
EVT LoVT, HiVT;
std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
SDValue Chain = MSC->getChain();
EVT MemoryVT = MSC->getMemoryVT();
unsigned Alignment = MSC->getOriginalAlignment();
EVT LoMemVT, HiMemVT;
std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
SDValue DataLo, DataHi;
std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
SDValue BasePtr = MSC->getBasePtr();
SDValue IndexLo, IndexHi;
std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
MachineMemOperand *MMO = DAG.getMachineFunction().
getMachineMemOperand(MSC->getPointerInfo(),
MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
Alignment, MSC->getAAInfo(), MSC->getRanges());
SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
DL, OpsLo, MMO);
SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
DL, OpsHi, MMO);
AddToWorklist(Lo.getNode());
AddToWorklist(Hi.getNode());
return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
}
SDValue DAGCombiner::visitMSTORE(SDNode *N) {
if (Level >= AfterLegalizeTypes)
return SDValue();
MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
SDValue Mask = MST->getMask();
SDValue Data = MST->getValue();
EVT VT = Data.getValueType();
SDLoc DL(N);
// If the MSTORE data type requires splitting and the mask is provided by a
// SETCC, then split both nodes and its operands before legalization. This
// prevents the type legalizer from unrolling SETCC into scalar comparisons
// and enables future optimizations (e.g. min/max pattern matching on X86).
if (Mask.getOpcode() == ISD::SETCC) {
// Check if any splitting is required.
if (TLI.getTypeAction(*DAG.getContext(), VT) !=
TargetLowering::TypeSplitVector)
return SDValue();
SDValue MaskLo, MaskHi, Lo, Hi;
std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
SDValue Chain = MST->getChain();
SDValue Ptr = MST->getBasePtr();
EVT MemoryVT = MST->getMemoryVT();
unsigned Alignment = MST->getOriginalAlignment();
// if Alignment is equal to the vector size,
// take the half of it for the second part
unsigned SecondHalfAlignment =
(Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment;
EVT LoMemVT, HiMemVT;
std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
SDValue DataLo, DataHi;
std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
MachineMemOperand *MMO = DAG.getMachineFunction().
getMachineMemOperand(MST->getPointerInfo(),
MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
Alignment, MST->getAAInfo(), MST->getRanges());
Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
MST->isTruncatingStore(),
MST->isCompressingStore());
Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
MST->isCompressingStore());
MMO = DAG.getMachineFunction().
getMachineMemOperand(MST->getPointerInfo(),
MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
SecondHalfAlignment, MST->getAAInfo(),
MST->getRanges());
Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
MST->isTruncatingStore(),
MST->isCompressingStore());
AddToWorklist(Lo.getNode());
AddToWorklist(Hi.getNode());
return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
}
return SDValue();
}
SDValue DAGCombiner::visitMGATHER(SDNode *N) {
if (Level >= AfterLegalizeTypes)
return SDValue();
MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
SDValue Mask = MGT->getMask();
SDLoc DL(N);
// If the MGATHER result requires splitting and the mask is provided by a
// SETCC, then split both nodes and its operands before legalization. This
// prevents the type legalizer from unrolling SETCC into scalar comparisons
// and enables future optimizations (e.g. min/max pattern matching on X86).
if (Mask.getOpcode() != ISD::SETCC)
return SDValue();
EVT VT = N->getValueType(0);
// Check if any splitting is required.
if (TLI.getTypeAction(*DAG.getContext(), VT) !=
TargetLowering::TypeSplitVector)
return SDValue();
SDValue MaskLo, MaskHi, Lo, Hi;
std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
SDValue Src0 = MGT->getValue();
SDValue Src0Lo, Src0Hi;
std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
EVT LoVT, HiVT;
std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
SDValue Chain = MGT->getChain();
EVT MemoryVT = MGT->getMemoryVT();
unsigned Alignment = MGT->getOriginalAlignment();
EVT LoMemVT, HiMemVT;
std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
SDValue BasePtr = MGT->getBasePtr();
SDValue Index = MGT->getIndex();
SDValue IndexLo, IndexHi;
std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
MachineMemOperand *MMO = DAG.getMachineFunction().
getMachineMemOperand(MGT->getPointerInfo(),
MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
Alignment, MGT->getAAInfo(), MGT->getRanges());
SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
MMO);
SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
MMO);
AddToWorklist(Lo.getNode());
AddToWorklist(Hi.getNode());
// Build a factor node to remember that this load is independent of the
// other one.
Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
Hi.getValue(1));
// Legalized the chain result - switch anything that used the old chain to
// use the new one.
DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
SDValue RetOps[] = { GatherRes, Chain };
return DAG.getMergeValues(RetOps, DL);
}
SDValue DAGCombiner::visitMLOAD(SDNode *N) {
if (Level >= AfterLegalizeTypes)
return SDValue();
MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
SDValue Mask = MLD->getMask();
SDLoc DL(N);
// If the MLOAD result requires splitting and the mask is provided by a
// SETCC, then split both nodes and its operands before legalization. This
// prevents the type legalizer from unrolling SETCC into scalar comparisons
// and enables future optimizations (e.g. min/max pattern matching on X86).
if (Mask.getOpcode() == ISD::SETCC) {
EVT VT = N->getValueType(0);
// Check if any splitting is required.
if (TLI.getTypeAction(*DAG.getContext(), VT) !=
TargetLowering::TypeSplitVector)
return SDValue();
SDValue MaskLo, MaskHi, Lo, Hi;
std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
SDValue Src0 = MLD->getSrc0();
SDValue Src0Lo, Src0Hi;
std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
EVT LoVT, HiVT;
std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
SDValue Chain = MLD->getChain();
SDValue Ptr = MLD->getBasePtr();
EVT MemoryVT = MLD->getMemoryVT();
unsigned Alignment = MLD->getOriginalAlignment();
// if Alignment is equal to the vector size,
// take the half of it for the second part
unsigned SecondHalfAlignment =
(Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
Alignment/2 : Alignment;
EVT LoMemVT, HiMemVT;
std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
MachineMemOperand *MMO = DAG.getMachineFunction().
getMachineMemOperand(MLD->getPointerInfo(),
MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
Alignment, MLD->getAAInfo(), MLD->getRanges());
Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
ISD::NON_EXTLOAD, MLD->isExpandingLoad());
Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
MLD->isExpandingLoad());
MMO = DAG.getMachineFunction().
getMachineMemOperand(MLD->getPointerInfo(),
MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
ISD::NON_EXTLOAD, MLD->isExpandingLoad());
AddToWorklist(Lo.getNode());
AddToWorklist(Hi.getNode());
// Build a factor node to remember that this load is independent of the
// other one.
Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
Hi.getValue(1));
// Legalized the chain result - switch anything that used the old chain to
// use the new one.
DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
SDValue RetOps[] = { LoadRes, Chain };
return DAG.getMergeValues(RetOps, DL);
}
return SDValue();
}
SDValue DAGCombiner::visitVSELECT(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
SDLoc DL(N);
// fold (vselect C, X, X) -> X
if (N1 == N2)
return N1;
// Canonicalize integer abs.
// vselect (setg[te] X, 0), X, -X ->
// vselect (setgt X, -1), X, -X ->
// vselect (setl[te] X, 0), -X, X ->
// Y = sra (X, size(X)-1); xor (add (X, Y), Y)
if (N0.getOpcode() == ISD::SETCC) {
SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
bool isAbs = false;
bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
(ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
if (isAbs) {
EVT VT = LHS.getValueType();
SDValue Shift = DAG.getNode(
ISD::SRA, DL, VT, LHS,
DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
AddToWorklist(Shift.getNode());
AddToWorklist(Add.getNode());
return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
}
}
if (SimplifySelectOps(N, N1, N2))
return SDValue(N, 0); // Don't revisit N.
// Fold (vselect (build_vector all_ones), N1, N2) -> N1
if (ISD::isBuildVectorAllOnes(N0.getNode()))
return N1;
// Fold (vselect (build_vector all_zeros), N1, N2) -> N2
if (ISD::isBuildVectorAllZeros(N0.getNode()))
return N2;
// The ConvertSelectToConcatVector function is assuming both the above
// checks for (vselect (build_vector all{ones,zeros) ...) have been made
// and addressed.
if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
N2.getOpcode() == ISD::CONCAT_VECTORS &&
ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
return CV;
}
return SDValue();
}
SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
SDValue N3 = N->getOperand(3);
SDValue N4 = N->getOperand(4);
ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
// fold select_cc lhs, rhs, x, x, cc -> x
if (N2 == N3)
return N2;
// Determine if the condition we're dealing with is constant
if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
CC, SDLoc(N), false)) {
AddToWorklist(SCC.getNode());
if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
if (!SCCC->isNullValue())
return N2; // cond always true -> true val
else
return N3; // cond always false -> false val
} else if (SCC->isUndef()) {
// When the condition is UNDEF, just return the first operand. This is
// coherent the DAG creation, no setcc node is created in this case
return N2;
} else if (SCC.getOpcode() == ISD::SETCC) {
// Fold to a simpler select_cc
return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
SCC.getOperand(0), SCC.getOperand(1), N2, N3,
SCC.getOperand(2));
}
}
// If we can fold this based on the true/false value, do so.
if (SimplifySelectOps(N, N2, N3))
return SDValue(N, 0); // Don't revisit N.
// fold select_cc into other things, such as min/max/abs
return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
}
SDValue DAGCombiner::visitSETCC(SDNode *N) {
return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
cast<CondCodeSDNode>(N->getOperand(2))->get(),
SDLoc(N));
}
SDValue DAGCombiner::visitSETCCE(SDNode *N) {
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
SDValue Carry = N->getOperand(2);
SDValue Cond = N->getOperand(3);
// If Carry is false, fold to a regular SETCC.
if (Carry.getOpcode() == ISD::CARRY_FALSE)
return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
return SDValue();
}
/// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
/// a build_vector of constants.
/// This function is called by the DAGCombiner when visiting sext/zext/aext
/// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
/// Vector extends are not folded if operations are legal; this is to
/// avoid introducing illegal build_vector dag nodes.
static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
SelectionDAG &DAG, bool LegalTypes,
bool LegalOperations) {
unsigned Opcode = N->getOpcode();
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
&& "Expected EXTEND dag node in input!");
// fold (sext c1) -> c1
// fold (zext c1) -> c1
// fold (aext c1) -> c1
if (isa<ConstantSDNode>(N0))
return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
// fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
// fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
// fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
EVT SVT = VT.getScalarType();
if (!(VT.isVector() &&
(!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
return nullptr;
// We can fold this node into a build_vector.
unsigned VTBits = SVT.getSizeInBits();
unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
SmallVector<SDValue, 8> Elts;
unsigned NumElts = VT.getVectorNumElements();
SDLoc DL(N);
for (unsigned i=0; i != NumElts; ++i) {
SDValue Op = N0->getOperand(i);
if (Op->isUndef()) {
Elts.push_back(DAG.getUNDEF(SVT));
continue;
}
SDLoc DL(Op);
// Get the constant value and if needed trunc it to the size of the type.
// Nodes like build_vector might have constants wider than the scalar type.
APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
else
Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
}
return DAG.getBuildVector(VT, DL, Elts).getNode();
}
// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
// transformation. Returns true if extension are possible and the above
// mentioned transformation is profitable.
static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
unsigned ExtOpc,
SmallVectorImpl<SDNode *> &ExtendNodes,
const TargetLowering &TLI) {
bool HasCopyToRegUses = false;
bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
UE = N0.getNode()->use_end();
UI != UE; ++UI) {
SDNode *User = *UI;
if (User == N)
continue;
if (UI.getUse().getResNo() != N0.getResNo())
continue;
// FIXME: Only extend SETCC N, N and SETCC N, c for now.
if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
// Sign bits will be lost after a zext.
return false;
bool Add = false;
for (unsigned i = 0; i != 2; ++i) {
SDValue UseOp = User->getOperand(i);
if (UseOp == N0)
continue;
if (!isa<ConstantSDNode>(UseOp))
return false;
Add = true;
}
if (Add)
ExtendNodes.push_back(User);
continue;
}
// If truncates aren't free and there are users we can't
// extend, it isn't worthwhile.
if (!isTruncFree)
return false;
// Remember if this value is live-out.
if (User->getOpcode() == ISD::CopyToReg)
HasCopyToRegUses = true;
}
if (HasCopyToRegUses) {
bool BothLiveOut = false;
for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
UI != UE; ++UI) {
SDUse &Use = UI.getUse();
if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
BothLiveOut = true;
break;
}
}
if (BothLiveOut)
// Both unextended and extended values are live out. There had better be
// a good reason for the transformation.
return ExtendNodes.size();
}
return true;
}
void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
SDValue Trunc, SDValue ExtLoad,
const SDLoc &DL, ISD::NodeType ExtType) {
// Extend SetCC uses if necessary.
for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
SDNode *SetCC = SetCCs[i];
SmallVector<SDValue, 4> Ops;
for (unsigned j = 0; j != 2; ++j) {
SDValue SOp = SetCC->getOperand(j);
if (SOp == Trunc)
Ops.push_back(ExtLoad);
else
Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
}
Ops.push_back(SetCC->getOperand(2));
CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
}
}
// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT DstVT = N->getValueType(0);
EVT SrcVT = N0.getValueType();
assert((N->getOpcode() == ISD::SIGN_EXTEND ||
N->getOpcode() == ISD::ZERO_EXTEND) &&
"Unexpected node type (not an extend)!");
// fold (sext (load x)) to multiple smaller sextloads; same for zext.
// For example, on a target with legal v4i32, but illegal v8i32, turn:
// (v8i32 (sext (v8i16 (load x))))
// into:
// (v8i32 (concat_vectors (v4i32 (sextload x)),
// (v4i32 (sextload (x + 16)))))
// Where uses of the original load, i.e.:
// (v8i16 (load x))
// are replaced with:
// (v8i16 (truncate
// (v8i32 (concat_vectors (v4i32 (sextload x)),
// (v4i32 (sextload (x + 16)))))))
//
// This combine is only applicable to illegal, but splittable, vectors.
// All legal types, and illegal non-vector types, are handled elsewhere.
// This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
//
if (N0->getOpcode() != ISD::LOAD)
return SDValue();
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
!N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
!DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
return SDValue();
SmallVector<SDNode *, 4> SetCCs;
if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
return SDValue();
ISD::LoadExtType ExtType =
N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
// Try to split the vector types to get down to legal types.
EVT SplitSrcVT = SrcVT;
EVT SplitDstVT = DstVT;
while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
SplitSrcVT.getVectorNumElements() > 1) {
SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
}
if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
return SDValue();
SDLoc DL(N);
const unsigned NumSplits =
DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
const unsigned Stride = SplitSrcVT.getStoreSize();
SmallVector<SDValue, 4> Loads;
SmallVector<SDValue, 4> Chains;
SDValue BasePtr = LN0->getBasePtr();
for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
const unsigned Offset = Idx * Stride;
const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
SDValue SplitLoad = DAG.getExtLoad(
ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
DAG.getConstant(Stride, DL, BasePtr.getValueType()));
Loads.push_back(SplitLoad.getValue(0));
Chains.push_back(SplitLoad.getValue(1));
}
SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
// Simplify TF.
AddToWorklist(NewChain.getNode());
CombineTo(N, NewValue);
// Replace uses of the original load (before extension)
// with a truncate of the concatenated sextloaded vectors.
SDValue Trunc =
DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
CombineTo(N0.getNode(), Trunc, NewChain);
ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
(ISD::NodeType)N->getOpcode());
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
SDLoc DL(N);
if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
LegalOperations))
return SDValue(Res, 0);
// fold (sext (sext x)) -> (sext x)
// fold (sext (aext x)) -> (sext x)
if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
if (N0.getOpcode() == ISD::TRUNCATE) {
// fold (sext (truncate (load x))) -> (sext (smaller load x))
// fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
SDNode *oye = N0.getOperand(0).getNode();
if (NarrowLoad.getNode() != N0.getNode()) {
CombineTo(N0.getNode(), NarrowLoad);
// CombineTo deleted the truncate, if needed, but not what's under it.
AddToWorklist(oye);
}
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
// See if the value being truncated is already sign extended. If so, just
// eliminate the trunc/sext pair.
SDValue Op = N0.getOperand(0);
unsigned OpBits = Op.getScalarValueSizeInBits();
unsigned MidBits = N0.getScalarValueSizeInBits();
unsigned DestBits = VT.getScalarSizeInBits();
unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
if (OpBits == DestBits) {
// Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
// bits, it is already ready.
if (NumSignBits > DestBits-MidBits)
return Op;
} else if (OpBits < DestBits) {
// Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
// bits, just sext from i32.
if (NumSignBits > OpBits-MidBits)
return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
} else {
// Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
// bits, just truncate to i32.
if (NumSignBits > OpBits-MidBits)
return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
}
// fold (sext (truncate x)) -> (sextinreg x).
if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
N0.getValueType())) {
if (OpBits < DestBits)
Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
else if (OpBits > DestBits)
Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
DAG.getValueType(N0.getValueType()));
}
}
// fold (sext (load x)) -> (sext (truncate (sextload x)))
// Only generate vector extloads when 1) they're legal, and 2) they are
// deemed desirable by the target.
if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
((!LegalOperations && !VT.isVector() &&
!cast<LoadSDNode>(N0)->isVolatile()) ||
TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
bool DoXform = true;
SmallVector<SDNode*, 4> SetCCs;
if (!N0.hasOneUse())
DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
if (VT.isVector())
DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
if (DoXform) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
LN0->getBasePtr(), N0.getValueType(),
LN0->getMemOperand());
CombineTo(N, ExtLoad);
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
N0.getValueType(), ExtLoad);
CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (sext (load x)) to multiple smaller sextloads.
// Only on illegal but splittable vectors.
if (SDValue ExtLoad = CombineExtLoad(N))
return ExtLoad;
// fold (sext (sextload x)) -> (sext (truncate (sextload x)))
// fold (sext ( extload x)) -> (sext (truncate (sextload x)))
if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
EVT MemVT = LN0->getMemoryVT();
if ((!LegalOperations && !LN0->isVolatile()) ||
TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, DL, VT, LN0->getChain(),
LN0->getBasePtr(), MemVT,
LN0->getMemOperand());
CombineTo(N, ExtLoad);
CombineTo(N0.getNode(),
DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
N0.getValueType(), ExtLoad),
ExtLoad.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (sext (and/or/xor (load x), cst)) ->
// (and/or/xor (sextload x), (sext cst))
if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
N0.getOpcode() == ISD::XOR) &&
isa<LoadSDNode>(N0.getOperand(0)) &&
N0.getOperand(1).getOpcode() == ISD::Constant &&
TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
(!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
bool DoXform = true;
SmallVector<SDNode*, 4> SetCCs;
if (!N0.hasOneUse())
DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
SetCCs, TLI);
if (DoXform) {
SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
LN0->getChain(), LN0->getBasePtr(),
LN0->getMemoryVT(),
LN0->getMemOperand());
APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Mask = Mask.sext(VT.getSizeInBits());
SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
ExtLoad, DAG.getConstant(Mask, DL, VT));
SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
SDLoc(N0.getOperand(0)),
N0.getOperand(0).getValueType(), ExtLoad);
CombineTo(N, And);
CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL, ISD::SIGN_EXTEND);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
}
if (N0.getOpcode() == ISD::SETCC) {
SDValue N00 = N0.getOperand(0);
SDValue N01 = N0.getOperand(1);
ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
EVT N00VT = N0.getOperand(0).getValueType();
// sext(setcc) -> sext_in_reg(vsetcc) for vectors.
// Only do this before legalize for now.
if (VT.isVector() && !LegalOperations &&
TLI.getBooleanContents(N00VT) ==
TargetLowering::ZeroOrNegativeOneBooleanContent) {
// On some architectures (such as SSE/NEON/etc) the SETCC result type is
// of the same size as the compared operands. Only optimize sext(setcc())
// if this is the case.
EVT SVT = getSetCCResultType(N00VT);
// We know that the # elements of the results is the same as the
// # elements of the compare (and the # elements of the compare result
// for that matter). Check to see that they are the same size. If so,
// we know that the element size of the sext'd result matches the
// element size of the compare operands.
if (VT.getSizeInBits() == SVT.getSizeInBits())
return DAG.getSetCC(DL, VT, N00, N01, CC);
// If the desired elements are smaller or larger than the source
// elements, we can use a matching integer vector type and then
// truncate/sign extend.
EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
if (SVT == MatchingVecType) {
SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
return DAG.getSExtOrTrunc(VsetCC, DL, VT);
}
}
// sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
// Here, T can be 1 or -1, depending on the type of the setcc and
// getBooleanContents().
unsigned SetCCWidth = N0.getScalarValueSizeInBits();
// To determine the "true" side of the select, we need to know the high bit
// of the value returned by the setcc if it evaluates to true.
// If the type of the setcc is i1, then the true case of the select is just
// sext(i1 1), that is, -1.
// If the type of the setcc is larger (say, i8) then the value of the high
// bit depends on getBooleanContents(), so ask TLI for a real "true" value
// of the appropriate width.
SDValue ExtTrueVal = (SetCCWidth == 1) ? DAG.getAllOnesConstant(DL, VT)
: TLI.getConstTrueVal(DAG, VT, DL);
SDValue Zero = DAG.getConstant(0, DL, VT);
if (SDValue SCC =
SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
return SCC;
if (!VT.isVector()) {
EVT SetCCVT = getSetCCResultType(N00VT);
// Don't do this transform for i1 because there's a select transform
// that would reverse it.
// TODO: We should not do this transform at all without a target hook
// because a sext is likely cheaper than a select?
if (SetCCVT.getScalarSizeInBits() != 1 &&
(!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
}
}
}
// fold (sext x) -> (zext x) if the sign bit is known zero.
if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
DAG.SignBitIsZero(N0))
return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
return SDValue();
}
// isTruncateOf - If N is a truncate of some other value, return true, record
// the value being truncated in Op and which of Op's bits are zero in KnownZero.
// This function computes KnownZero to avoid a duplicated call to
// computeKnownBits in the caller.
static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
APInt &KnownZero) {
APInt KnownOne;
if (N->getOpcode() == ISD::TRUNCATE) {
Op = N->getOperand(0);
DAG.computeKnownBits(Op, KnownZero, KnownOne);
return true;
}
if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
return false;
SDValue Op0 = N->getOperand(0);
SDValue Op1 = N->getOperand(1);
assert(Op0.getValueType() == Op1.getValueType());
if (isNullConstant(Op0))
Op = Op1;
else if (isNullConstant(Op1))
Op = Op0;
else
return false;
DAG.computeKnownBits(Op, KnownZero, KnownOne);
if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
return false;
return true;
}
SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
LegalOperations))
return SDValue(Res, 0);
// fold (zext (zext x)) -> (zext x)
// fold (zext (aext x)) -> (zext x)
if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
N0.getOperand(0));
// fold (zext (truncate x)) -> (zext x) or
// (zext (truncate x)) -> (truncate x)
// This is valid when the truncated bits of x are already zero.
// FIXME: We should extend this to work for vectors too.
SDValue Op;
APInt KnownZero;
if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
APInt TruncatedBits =
(Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
APInt(Op.getValueSizeInBits(), 0) :
APInt::getBitsSet(Op.getValueSizeInBits(),
N0.getValueSizeInBits(),
std::min(Op.getValueSizeInBits(),
VT.getSizeInBits()));
if (TruncatedBits == (KnownZero & TruncatedBits)) {
if (VT.bitsGT(Op.getValueType()))
return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
if (VT.bitsLT(Op.getValueType()))
return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
return Op;
}
}
// fold (zext (truncate (load x))) -> (zext (smaller load x))
// fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
if (N0.getOpcode() == ISD::TRUNCATE) {
if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
SDNode *oye = N0.getOperand(0).getNode();
if (NarrowLoad.getNode() != N0.getNode()) {
CombineTo(N0.getNode(), NarrowLoad);
// CombineTo deleted the truncate, if needed, but not what's under it.
AddToWorklist(oye);
}
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (zext (truncate x)) -> (and x, mask)
if (N0.getOpcode() == ISD::TRUNCATE) {
// fold (zext (truncate (load x))) -> (zext (smaller load x))
// fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
SDNode *oye = N0.getOperand(0).getNode();
if (NarrowLoad.getNode() != N0.getNode()) {
CombineTo(N0.getNode(), NarrowLoad);
// CombineTo deleted the truncate, if needed, but not what's under it.
AddToWorklist(oye);
}
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
EVT SrcVT = N0.getOperand(0).getValueType();
EVT MinVT = N0.getValueType();
// Try to mask before the extension to avoid having to generate a larger mask,
// possibly over several sub-vectors.
if (SrcVT.bitsLT(VT)) {
if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
SDValue Op = N0.getOperand(0);
Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
AddToWorklist(Op.getNode());
return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
}
}
if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
SDValue Op = N0.getOperand(0);
if (SrcVT.bitsLT(VT)) {
Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
AddToWorklist(Op.getNode());
} else if (SrcVT.bitsGT(VT)) {
Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
AddToWorklist(Op.getNode());
}
return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
}
}
// Fold (zext (and (trunc x), cst)) -> (and x, cst),
// if either of the casts is not free.
if (N0.getOpcode() == ISD::AND &&
N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
N0.getOperand(1).getOpcode() == ISD::Constant &&
(!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
N0.getValueType()) ||
!TLI.isZExtFree(N0.getValueType(), VT))) {
SDValue X = N0.getOperand(0).getOperand(0);
if (X.getValueType().bitsLT(VT)) {
X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
} else if (X.getValueType().bitsGT(VT)) {
X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
}
APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Mask = Mask.zext(VT.getSizeInBits());
SDLoc DL(N);
return DAG.getNode(ISD::AND, DL, VT,
X, DAG.getConstant(Mask, DL, VT));
}
// fold (zext (load x)) -> (zext (truncate (zextload x)))
// Only generate vector extloads when 1) they're legal, and 2) they are
// deemed desirable by the target.
if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
((!LegalOperations && !VT.isVector() &&
!cast<LoadSDNode>(N0)->isVolatile()) ||
TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
bool DoXform = true;
SmallVector<SDNode*, 4> SetCCs;
if (!N0.hasOneUse())
DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
if (VT.isVector())
DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
if (DoXform) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
LN0->getChain(),
LN0->getBasePtr(), N0.getValueType(),
LN0->getMemOperand());
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
N0.getValueType(), ExtLoad);
CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
ISD::ZERO_EXTEND);
CombineTo(N, ExtLoad);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (zext (load x)) to multiple smaller zextloads.
// Only on illegal but splittable vectors.
if (SDValue ExtLoad = CombineExtLoad(N))
return ExtLoad;
// fold (zext (and/or/xor (load x), cst)) ->
// (and/or/xor (zextload x), (zext cst))
// Unless (and (load x) cst) will match as a zextload already and has
// additional users.
if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
N0.getOpcode() == ISD::XOR) &&
isa<LoadSDNode>(N0.getOperand(0)) &&
N0.getOperand(1).getOpcode() == ISD::Constant &&
TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
(!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
bool DoXform = true;
SmallVector<SDNode*, 4> SetCCs;
if (!N0.hasOneUse()) {
if (N0.getOpcode() == ISD::AND) {
auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
auto NarrowLoad = false;
EVT LoadResultTy = AndC->getValueType(0);
EVT ExtVT, LoadedVT;
if (isAndLoadExtLoad(AndC, LN0, LoadResultTy, ExtVT, LoadedVT,
NarrowLoad))
DoXform = false;
}
if (DoXform)
DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0),
ISD::ZERO_EXTEND, SetCCs, TLI);
}
if (DoXform) {
SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
LN0->getChain(), LN0->getBasePtr(),
LN0->getMemoryVT(),
LN0->getMemOperand());
APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Mask = Mask.zext(VT.getSizeInBits());
SDLoc DL(N);
SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
ExtLoad, DAG.getConstant(Mask, DL, VT));
SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
SDLoc(N0.getOperand(0)),
N0.getOperand(0).getValueType(), ExtLoad);
CombineTo(N, And);
CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
ISD::ZERO_EXTEND);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
}
// fold (zext (zextload x)) -> (zext (truncate (zextload x)))
// fold (zext ( extload x)) -> (zext (truncate (zextload x)))
if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
EVT MemVT = LN0->getMemoryVT();
if ((!LegalOperations && !LN0->isVolatile()) ||
TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
LN0->getChain(),
LN0->getBasePtr(), MemVT,
LN0->getMemOperand());
CombineTo(N, ExtLoad);
CombineTo(N0.getNode(),
DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
ExtLoad),
ExtLoad.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
if (N0.getOpcode() == ISD::SETCC) {
// Only do this before legalize for now.
if (!LegalOperations && VT.isVector() &&
N0.getValueType().getVectorElementType() == MVT::i1) {
EVT N00VT = N0.getOperand(0).getValueType();
if (getSetCCResultType(N00VT) == N0.getValueType())
return SDValue();
// We know that the # elements of the results is the same as the #
// elements of the compare (and the # elements of the compare result for
// that matter). Check to see that they are the same size. If so, we know
// that the element size of the sext'd result matches the element size of
// the compare operands.
SDLoc DL(N);
SDValue VecOnes = DAG.getConstant(1, DL, VT);
if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
// zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
N0.getOperand(1), N0.getOperand(2));
return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes);
}
// If the desired elements are smaller or larger than the source
// elements we can use a matching integer vector type and then
// truncate/sign extend.
EVT MatchingElementType = EVT::getIntegerVT(
*DAG.getContext(), N00VT.getScalarSizeInBits());
EVT MatchingVectorType = EVT::getVectorVT(
*DAG.getContext(), MatchingElementType, N00VT.getVectorNumElements());
SDValue VsetCC =
DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
N0.getOperand(1), N0.getOperand(2));
return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT),
VecOnes);
}
// zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
SDLoc DL(N);
if (SDValue SCC = SimplifySelectCC(
DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
DAG.getConstant(0, DL, VT),
cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
return SCC;
}
// (zext (shl (zext x), cst)) -> (shl (zext x), cst)
if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
isa<ConstantSDNode>(N0.getOperand(1)) &&
N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
N0.hasOneUse()) {
SDValue ShAmt = N0.getOperand(1);
unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
if (N0.getOpcode() == ISD::SHL) {
SDValue InnerZExt = N0.getOperand(0);
// If the original shl may be shifting out bits, do not perform this
// transformation.
unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
InnerZExt.getOperand(0).getValueSizeInBits();
if (ShAmtVal > KnownZeroBits)
return SDValue();
}
SDLoc DL(N);
// Ensure that the shift amount is wide enough for the shifted value.
if (VT.getSizeInBits() >= 256)
ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
return DAG.getNode(N0.getOpcode(), DL, VT,
DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
ShAmt);
}
return SDValue();
}
SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
LegalOperations))
return SDValue(Res, 0);
// fold (aext (aext x)) -> (aext x)
// fold (aext (zext x)) -> (zext x)
// fold (aext (sext x)) -> (sext x)
if (N0.getOpcode() == ISD::ANY_EXTEND ||
N0.getOpcode() == ISD::ZERO_EXTEND ||
N0.getOpcode() == ISD::SIGN_EXTEND)
return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
// fold (aext (truncate (load x))) -> (aext (smaller load x))
// fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
if (N0.getOpcode() == ISD::TRUNCATE) {
if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
SDNode *oye = N0.getOperand(0).getNode();
if (NarrowLoad.getNode() != N0.getNode()) {
CombineTo(N0.getNode(), NarrowLoad);
// CombineTo deleted the truncate, if needed, but not what's under it.
AddToWorklist(oye);
}
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (aext (truncate x))
if (N0.getOpcode() == ISD::TRUNCATE) {
SDValue TruncOp = N0.getOperand(0);
if (TruncOp.getValueType() == VT)
return TruncOp; // x iff x size == zext size.
if (TruncOp.getValueType().bitsGT(VT))
return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
}
// Fold (aext (and (trunc x), cst)) -> (and x, cst)
// if the trunc is not free.
if (N0.getOpcode() == ISD::AND &&
N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
N0.getOperand(1).getOpcode() == ISD::Constant &&
!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
N0.getValueType())) {
SDLoc DL(N);
SDValue X = N0.getOperand(0).getOperand(0);
if (X.getValueType().bitsLT(VT)) {
X = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
} else if (X.getValueType().bitsGT(VT)) {
X = DAG.getNode(ISD::TRUNCATE, DL, VT, X);
}
APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Mask = Mask.zext(VT.getSizeInBits());
return DAG.getNode(ISD::AND, DL, VT,
X, DAG.getConstant(Mask, DL, VT));
}
// fold (aext (load x)) -> (aext (truncate (extload x)))
// None of the supported targets knows how to perform load and any_ext
// on vectors in one instruction. We only perform this transformation on
// scalars.
if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
ISD::isUNINDEXEDLoad(N0.getNode()) &&
TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
bool DoXform = true;
SmallVector<SDNode*, 4> SetCCs;
if (!N0.hasOneUse())
DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
if (DoXform) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
LN0->getChain(),
LN0->getBasePtr(), N0.getValueType(),
LN0->getMemOperand());
CombineTo(N, ExtLoad);
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
N0.getValueType(), ExtLoad);
CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
ISD::ANY_EXTEND);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
// fold (aext (zextload x)) -> (aext (truncate (zextload x)))
// fold (aext (sextload x)) -> (aext (truncate (sextload x)))
// fold (aext ( extload x)) -> (aext (truncate (extload x)))
if (N0.getOpcode() == ISD::LOAD &&
!ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
N0.hasOneUse()) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
ISD::LoadExtType ExtType = LN0->getExtensionType();
EVT MemVT = LN0->getMemoryVT();
if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
VT, LN0->getChain(), LN0->getBasePtr(),
MemVT, LN0->getMemOperand());
CombineTo(N, ExtLoad);
CombineTo(N0.getNode(),
DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
N0.getValueType(), ExtLoad),
ExtLoad.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
if (N0.getOpcode() == ISD::SETCC) {
// For vectors:
// aext(setcc) -> vsetcc
// aext(setcc) -> truncate(vsetcc)
// aext(setcc) -> aext(vsetcc)
// Only do this before legalize for now.
if (VT.isVector() && !LegalOperations) {
EVT N0VT = N0.getOperand(0).getValueType();
// We know that the # elements of the results is the same as the
// # elements of the compare (and the # elements of the compare result
// for that matter). Check to see that they are the same size. If so,
// we know that the element size of the sext'd result matches the
// element size of the compare operands.
if (VT.getSizeInBits() == N0VT.getSizeInBits())
return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
N0.getOperand(1),
cast<CondCodeSDNode>(N0.getOperand(2))->get());
// If the desired elements are smaller or larger than the source
// elements we can use a matching integer vector type and then
// truncate/any extend
else {
EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
SDValue VsetCC =
DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
N0.getOperand(1),
cast<CondCodeSDNode>(N0.getOperand(2))->get());
return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
}
}
// aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
SDLoc DL(N);
if (SDValue SCC = SimplifySelectCC(
DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
DAG.getConstant(0, DL, VT),
cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
return SCC;
}
return SDValue();
}
SDValue DAGCombiner::visitAssertZext(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT EVT = cast<VTSDNode>(N1)->getVT();
// fold (assertzext (assertzext x, vt), vt) -> (assertzext x, vt)
if (N0.getOpcode() == ISD::AssertZext &&
EVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
return N0;
return SDValue();
}
/// See if the specified operand can be simplified with the knowledge that only
/// the bits specified by Mask are used. If so, return the simpler operand,
/// otherwise return a null SDValue.
///
/// (This exists alongside SimplifyDemandedBits because GetDemandedBits can
/// simplify nodes with multiple uses more aggressively.)
SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
switch (V.getOpcode()) {
default: break;
case ISD::Constant: {
const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
assert(CV && "Const value should be ConstSDNode.");
const APInt &CVal = CV->getAPIntValue();
APInt NewVal = CVal & Mask;
if (NewVal != CVal)
return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
break;
}
case ISD::OR:
case ISD::XOR:
// If the LHS or RHS don't contribute bits to the or, drop them.
if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
return V.getOperand(1);
if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
return V.getOperand(0);
break;
case ISD::SRL:
// Only look at single-use SRLs.
if (!V.getNode()->hasOneUse())
break;
if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
// See if we can recursively simplify the LHS.
unsigned Amt = RHSC->getZExtValue();
// Watch out for shift count overflow though.
if (Amt >= Mask.getBitWidth()) break;
APInt NewMask = Mask << Amt;
if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
SimplifyLHS, V.getOperand(1));
}
break;
case ISD::AND: {
// X & -1 -> X (ignoring bits which aren't demanded).
ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
if (AndVal && (AndVal->getAPIntValue() & Mask) == Mask)
return V.getOperand(0);
break;
}
}
return SDValue();
}
/// If the result of a wider load is shifted to right of N bits and then
/// truncated to a narrower type and where N is a multiple of number of bits of
/// the narrower type, transform it to a narrower load from address + N / num of
/// bits of new type. If the result is to be extended, also fold the extension
/// to form a extending load.
SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
unsigned Opc = N->getOpcode();
ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
EVT ExtVT = VT;
// This transformation isn't valid for vector loads.
if (VT.isVector())
return SDValue();
// Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
// extended to VT.
if (Opc == ISD::SIGN_EXTEND_INREG) {
ExtType = ISD::SEXTLOAD;
ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
} else if (Opc == ISD::SRL) {
// Another special-case: SRL is basically zero-extending a narrower value.
ExtType = ISD::ZEXTLOAD;
N0 = SDValue(N, 0);
ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
if (!N01) return SDValue();
ExtVT = EVT::getIntegerVT(*DAG.getContext(),
VT.getSizeInBits() - N01->getZExtValue());
}
if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
return SDValue();
unsigned EVTBits = ExtVT.getSizeInBits();
// Do not generate loads of non-round integer types since these can
// be expensive (and would be wrong if the type is not byte sized).
if (!ExtVT.isRound())
return SDValue();
unsigned ShAmt = 0;
if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
ShAmt = N01->getZExtValue();
// Is the shift amount a multiple of size of VT?
if ((ShAmt & (EVTBits-1)) == 0) {
N0 = N0.getOperand(0);
// Is the load width a multiple of size of VT?
if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0)
return SDValue();
}
// At this point, we must have a load or else we can't do the transform.
if (!isa<LoadSDNode>(N0)) return SDValue();
// Because a SRL must be assumed to *need* to zero-extend the high bits
// (as opposed to anyext the high bits), we can't combine the zextload
// lowering of SRL and an sextload.
if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
return SDValue();
// If the shift amount is larger than the input type then we're not
// accessing any of the loaded bytes. If the load was a zextload/extload
// then the result of the shift+trunc is zero/undef (handled elsewhere).
if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
return SDValue();
}
}
// If the load is shifted left (and the result isn't shifted back right),
// we can fold the truncate through the shift.
unsigned ShLeftAmt = 0;
if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
ShLeftAmt = N01->getZExtValue();
N0 = N0.getOperand(0);
}
}
// If we haven't found a load, we can't narrow it. Don't transform one with
// multiple uses, this would require adding a new load.
if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
return SDValue();
// Don't change the width of a volatile load.
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
if (LN0->isVolatile())
return SDValue();
// Verify that we are actually reducing a load width here.
if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
return SDValue();
// For the transform to be legal, the load must produce only two values
// (the value loaded and the chain). Don't transform a pre-increment
// load, for example, which produces an extra value. Otherwise the
// transformation is not equivalent, and the downstream logic to replace
// uses gets things wrong.
if (LN0->getNumValues() > 2)
return SDValue();
// If the load that we're shrinking is an extload and we're not just
// discarding the extension we can't simply shrink the load. Bail.
// TODO: It would be possible to merge the extensions in some cases.
if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
return SDValue();
if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
return SDValue();
EVT PtrType = N0.getOperand(1).getValueType();
if (PtrType == MVT::Untyped || PtrType.isExtended())
// It's not possible to generate a constant of extended or untyped type.
return SDValue();
// For big endian targets, we need to adjust the offset to the pointer to
// load the correct bytes.
if (DAG.getDataLayout().isBigEndian()) {
unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
}
uint64_t PtrOff = ShAmt / 8;
unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
SDLoc DL(LN0);
// The original load itself didn't wrap, so an offset within it doesn't.
SDNodeFlags Flags;
Flags.setNoUnsignedWrap(true);
SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
PtrType, LN0->getBasePtr(),
DAG.getConstant(PtrOff, DL, PtrType),
&Flags);
AddToWorklist(NewPtr.getNode());
SDValue Load;
if (ExtType == ISD::NON_EXTLOAD)
Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
else
Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr,
LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
NewAlign, LN0->getMemOperand()->getFlags(),
LN0->getAAInfo());
// Replace the old load's chain with the new load's chain.
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
// Shift the result left, if we've swallowed a left shift.
SDValue Result = Load;
if (ShLeftAmt != 0) {
EVT ShImmTy = getShiftAmountTy(Result.getValueType());
if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
ShImmTy = VT;
// If the shift amount is as large as the result size (but, presumably,
// no larger than the source) then the useful bits of the result are
// zero; we can't simply return the shortened shift, because the result
// of that operation is undefined.
SDLoc DL(N0);
if (ShLeftAmt >= VT.getSizeInBits())
Result = DAG.getConstant(0, DL, VT);
else
Result = DAG.getNode(ISD::SHL, DL, VT,
Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
}
// Return the new loaded value.
return Result;
}
SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
EVT EVT = cast<VTSDNode>(N1)->getVT();
unsigned VTBits = VT.getScalarSizeInBits();
unsigned EVTBits = EVT.getScalarSizeInBits();
if (N0.isUndef())
return DAG.getUNDEF(VT);
// fold (sext_in_reg c1) -> c1
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
// If the input is already sign extended, just drop the extension.
if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
return N0;
// fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
N0.getOperand(0), N1);
// fold (sext_in_reg (sext x)) -> (sext x)
// fold (sext_in_reg (aext x)) -> (sext x)
// if x is small enough.
if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
SDValue N00 = N0.getOperand(0);
if (N00.getScalarValueSizeInBits() <= EVTBits &&
(!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
}
// fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_in_reg x)
if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) &&
N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) {
if (!LegalOperations ||
TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))
return DAG.getSignExtendVectorInReg(N0.getOperand(0), SDLoc(N), VT);
}
// fold (sext_in_reg (zext x)) -> (sext x)
// iff we are extending the source sign bit.
if (N0.getOpcode() == ISD::ZERO_EXTEND) {
SDValue N00 = N0.getOperand(0);
if (N00.getScalarValueSizeInBits() == EVTBits &&
(!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
}
// fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1)))
return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType());
// fold operands of sext_in_reg based on knowledge that the top bits are not
// demanded.
if (SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
// fold (sext_in_reg (load x)) -> (smaller sextload x)
// fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
if (SDValue NarrowLoad = ReduceLoadWidth(N))
return NarrowLoad;
// fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
// fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
// We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
if (N0.getOpcode() == ISD::SRL) {
if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
// We can turn this into an SRA iff the input to the SRL is already sign
// extended enough.
unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
return DAG.getNode(ISD::SRA, SDLoc(N), VT,
N0.getOperand(0), N0.getOperand(1));
}
}
// fold (sext_inreg (extload x)) -> (sextload x)
if (ISD::isEXTLoad(N0.getNode()) &&
ISD::isUNINDEXEDLoad(N0.getNode()) &&
EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
LN0->getChain(),
LN0->getBasePtr(), EVT,
LN0->getMemOperand());
CombineTo(N, ExtLoad);
CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
AddToWorklist(ExtLoad.getNode());
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
// fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
N0.hasOneUse() &&
EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
LN0->getChain(),
LN0->getBasePtr(), EVT,
LN0->getMemOperand());
CombineTo(N, ExtLoad);
CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
// Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
N0.getOperand(1), false))
return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
BSwap, N1);
}
return SDValue();
}
SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
if (N0.isUndef())
return DAG.getUNDEF(VT);
if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
LegalOperations))
return SDValue(Res, 0);
return SDValue();
}
SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
if (N0.isUndef())
return DAG.getUNDEF(VT);
if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
LegalOperations))
return SDValue(Res, 0);
return SDValue();
}
SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
bool isLE = DAG.getDataLayout().isLittleEndian();
// noop truncate
if (N0.getValueType() == N->getValueType(0))
return N0;
// fold (truncate c1) -> c1
if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
// fold (truncate (truncate x)) -> (truncate x)
if (N0.getOpcode() == ISD::TRUNCATE)
return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
// fold (truncate (ext x)) -> (ext x) or (truncate x) or x
if (N0.getOpcode() == ISD::ZERO_EXTEND ||
N0.getOpcode() == ISD::SIGN_EXTEND ||
N0.getOpcode() == ISD::ANY_EXTEND) {
// if the source is smaller than the dest, we still need an extend.
if (N0.getOperand(0).getValueType().bitsLT(VT))
return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
// if the source is larger than the dest, than we just need the truncate.
if (N0.getOperand(0).getValueType().bitsGT(VT))
return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
// if the source and dest are the same type, we can drop both the extend
// and the truncate.
return N0.getOperand(0);
}
// If this is anyext(trunc), don't fold it, allow ourselves to be folded.
if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
return SDValue();
// Fold extract-and-trunc into a narrow extract. For example:
// i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
// i32 y = TRUNCATE(i64 x)
// -- becomes --
// v16i8 b = BITCAST (v2i64 val)
// i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
//
// Note: We only run this optimization after type legalization (which often
// creates this pattern) and before operation legalization after which
// we need to be more careful about the vector instructions that we generate.
if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
EVT VecTy = N0.getOperand(0).getValueType();
EVT ExTy = N0.getValueType();
EVT TrTy = N->getValueType(0);
unsigned NumElem = VecTy.getVectorNumElements();
unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
SDValue EltNo = N0->getOperand(1);
if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
SDLoc DL(N);
return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
DAG.getBitcast(NVT, N0.getOperand(0)),
DAG.getConstant(Index, DL, IndexTy));
}
}
// trunc (select c, a, b) -> select c, (trunc a), (trunc b)
if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
EVT SrcVT = N0.getValueType();
if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
TLI.isTruncateFree(SrcVT, VT)) {
SDLoc SL(N0);
SDValue Cond = N0.getOperand(0);
SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
}
}
// trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
(!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) &&
TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
if (const ConstantSDNode *CAmt = isConstOrConstSplat(N0.getOperand(1))) {
uint64_t Amt = CAmt->getZExtValue();
unsigned Size = VT.getScalarSizeInBits();
if (Amt < Size) {
SDLoc SL(N);
EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
return DAG.getNode(ISD::SHL, SL, VT, Trunc,
DAG.getConstant(Amt, SL, AmtVT));
}
}
}
// Fold a series of buildvector, bitcast, and truncate if possible.
// For example fold
// (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
// (2xi32 (buildvector x, y)).
if (Level == AfterLegalizeVectorOps && VT.isVector() &&
N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
N0.getOperand(0).hasOneUse()) {
SDValue BuildVect = N0.getOperand(0);
EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
EVT TruncVecEltTy = VT.getVectorElementType();
// Check that the element types match.
if (BuildVectEltTy == TruncVecEltTy) {
// Now we only need to compute the offset of the truncated elements.
unsigned BuildVecNumElts = BuildVect.getNumOperands();
unsigned TruncVecNumElts = VT.getVectorNumElements();
unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
"Invalid number of elements");
SmallVector<SDValue, 8> Opnds;
for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
Opnds.push_back(BuildVect.getOperand(i));
return DAG.getBuildVector(VT, SDLoc(N), Opnds);
}
}
// See if we can simplify the input to this truncate through knowledge that
// only the low bits are being used.
// For example "trunc (or (shl x, 8), y)" // -> trunc y
// Currently we only perform this optimization on scalars because vectors
// may have different active low bits.
if (!VT.isVector()) {
if (SDValue Shorter =
GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
VT.getSizeInBits())))
return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
}
// fold (truncate (load x)) -> (smaller load x)
// fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
if (SDValue Reduced = ReduceLoadWidth(N))
return Reduced;
// Handle the case where the load remains an extending load even
// after truncation.
if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
if (!LN0->isVolatile() &&
LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
VT, LN0->getChain(), LN0->getBasePtr(),
LN0->getMemoryVT(),
LN0->getMemOperand());
DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
return NewLoad;
}
}
}
// fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
// where ... are all 'undef'.
if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
SmallVector<EVT, 8> VTs;
SDValue V;
unsigned Idx = 0;
unsigned NumDefs = 0;
for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
SDValue X = N0.getOperand(i);
if (!X.isUndef()) {
V = X;
Idx = i;
NumDefs++;
}
// Stop if more than one members are non-undef.
if (NumDefs > 1)
break;
VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
VT.getVectorElementType(),
X.getValueType().getVectorNumElements()));
}
if (NumDefs == 0)
return DAG.getUNDEF(VT);
if (NumDefs == 1) {
assert(V.getNode() && "The single defined operand is empty!");
SmallVector<SDValue, 8> Opnds;
for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
if (i != Idx) {
Opnds.push_back(DAG.getUNDEF(VTs[i]));
continue;
}
SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
AddToWorklist(NV.getNode());
Opnds.push_back(NV);
}
return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
}
}
// Fold truncate of a bitcast of a vector to an extract of the low vector
// element.
//
// e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, 0
if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
SDValue VecSrc = N0.getOperand(0);
EVT SrcVT = VecSrc.getValueType();
if (SrcVT.isVector() && SrcVT.getScalarType() == VT &&
(!LegalOperations ||
TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) {
SDLoc SL(N);
EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT,
VecSrc, DAG.getConstant(0, SL, IdxVT));
}
}
// Simplify the operands using demanded-bits information.
if (!VT.isVector() &&
SimplifyDemandedBits(SDValue(N, 0)))
return SDValue(N, 0);
// (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
// When the adde's carry is not used.
if (N0.getOpcode() == ISD::ADDE && N0.hasOneUse() &&
!N0.getNode()->hasAnyUseOfValue(1) &&
(!LegalOperations || TLI.isOperationLegal(ISD::ADDE, VT))) {
SDLoc SL(N);
auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
return DAG.getNode(ISD::ADDE, SL, DAG.getVTList(VT, MVT::Glue),
X, Y, N0.getOperand(2));
}
return SDValue();
}
static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
SDValue Elt = N->getOperand(i);
if (Elt.getOpcode() != ISD::MERGE_VALUES)
return Elt.getNode();
return Elt.getOperand(Elt.getResNo()).getNode();
}
/// build_pair (load, load) -> load
/// if load locations are consecutive.
SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
assert(N->getOpcode() == ISD::BUILD_PAIR);
LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
LD1->getAddressSpace() != LD2->getAddressSpace())
return SDValue();
EVT LD1VT = LD1->getValueType(0);
unsigned LD1Bytes = LD1VT.getSizeInBits() / 8;
if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() &&
DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) {
unsigned Align = LD1->getAlignment();
unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
VT.getTypeForEVT(*DAG.getContext()));
if (NewAlign <= Align &&
(!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
LD1->getPointerInfo(), Align);
}
return SDValue();
}
static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
// On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
// and Lo parts; on big-endian machines it doesn't.
return DAG.getDataLayout().isBigEndian() ? 1 : 0;
}
static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
const TargetLowering &TLI) {
// If this is not a bitcast to an FP type or if the target doesn't have
// IEEE754-compliant FP logic, we're done.
EVT VT = N->getValueType(0);
if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
return SDValue();
// TODO: Use splat values for the constant-checking below and remove this
// restriction.
SDValue N0 = N->getOperand(0);
EVT SourceVT = N0.getValueType();
if (SourceVT.isVector())
return SDValue();
unsigned FPOpcode;
APInt SignMask;
switch (N0.getOpcode()) {
case ISD::AND:
FPOpcode = ISD::FABS;
SignMask = ~APInt::getSignBit(SourceVT.getSizeInBits());
break;
case ISD::XOR:
FPOpcode = ISD::FNEG;
SignMask = APInt::getSignBit(SourceVT.getSizeInBits());
break;
// TODO: ISD::OR --> ISD::FNABS?
default:
return SDValue();
}
// Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
// Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
SDValue LogicOp0 = N0.getOperand(0);
ConstantSDNode *LogicOp1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
LogicOp0.getOpcode() == ISD::BITCAST &&
LogicOp0->getOperand(0).getValueType() == VT)
return DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0->getOperand(0));
return SDValue();
}
SDValue DAGCombiner::visitBITCAST(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
if (N0.isUndef())
return DAG.getUNDEF(VT);
// If the input is a BUILD_VECTOR with all constant elements, fold this now.
// Only do this before legalize, since afterward the target may be depending
// on the bitconvert.
// First check to see if this is all constant.
if (!LegalTypes &&
N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
VT.isVector()) {
bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
EVT DestEltVT = N->getValueType(0).getVectorElementType();
assert(!DestEltVT.isVector() &&
"Element type of vector ValueType must not be vector!");
if (isSimple)
return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
}
// If the input is a constant, let getNode fold it.
if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
// If we can't allow illegal operations, we need to check that this is just
// a fp -> int or int -> conversion and that the resulting operation will
// be legal.
if (!LegalOperations ||
(isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
(isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
TLI.isOperationLegal(ISD::Constant, VT)))
return DAG.getBitcast(VT, N0);
}
// (conv (conv x, t1), t2) -> (conv x, t2)
if (N0.getOpcode() == ISD::BITCAST)
return DAG.getBitcast(VT, N0.getOperand(0));
// fold (conv (load x)) -> (load (conv*)x)
// If the resultant load doesn't need a higher alignment than the original!
if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
// Do not change the width of a volatile load.
!cast<LoadSDNode>(N0)->isVolatile() &&
// Do not remove the cast if the types differ in endian layout.
TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
(!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
unsigned OrigAlign = LN0->getAlignment();
bool Fast = false;
if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
LN0->getAddressSpace(), OrigAlign, &Fast) &&
Fast) {
SDValue Load =
DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
LN0->getPointerInfo(), OrigAlign,
LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
return Load;
}
}
if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
return V;
// fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
// fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
//
// For ppc_fp128:
// fold (bitcast (fneg x)) ->
// flipbit = signbit
// (xor (bitcast x) (build_pair flipbit, flipbit))
//
// fold (bitcast (fabs x)) ->
// flipbit = (and (extract_element (bitcast x), 0), signbit)
// (xor (bitcast x) (build_pair flipbit, flipbit))
// This often reduces constant pool loads.
if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
(N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
N0.getNode()->hasOneUse() && VT.isInteger() &&
!VT.isVector() && !N0.getValueType().isVector()) {
SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
AddToWorklist(NewConv.getNode());
SDLoc DL(N);
if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
assert(VT.getSizeInBits() == 128);
SDValue SignBit = DAG.getConstant(
APInt::getSignBit(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
SDValue FlipBit;
if (N0.getOpcode() == ISD::FNEG) {
FlipBit = SignBit;
AddToWorklist(FlipBit.getNode());
} else {
assert(N0.getOpcode() == ISD::FABS);
SDValue Hi =
DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
SDLoc(NewConv)));
AddToWorklist(Hi.getNode());
FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
AddToWorklist(FlipBit.getNode());
}
SDValue FlipBits =
DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
AddToWorklist(FlipBits.getNode());
return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
}
APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
if (N0.getOpcode() == ISD::FNEG)
return DAG.getNode(ISD::XOR, DL, VT,
NewConv, DAG.getConstant(SignBit, DL, VT));
assert(N0.getOpcode() == ISD::FABS);
return DAG.getNode(ISD::AND, DL, VT,
NewConv, DAG.getConstant(~SignBit, DL, VT));
}
// fold (bitconvert (fcopysign cst, x)) ->
// (or (and (bitconvert x), sign), (and cst, (not sign)))
// Note that we don't handle (copysign x, cst) because this can always be
// folded to an fneg or fabs.
//
// For ppc_fp128:
// fold (bitcast (fcopysign cst, x)) ->
// flipbit = (and (extract_element
// (xor (bitcast cst), (bitcast x)), 0),
// signbit)
// (xor (bitcast cst) (build_pair flipbit, flipbit))
if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
isa<ConstantFPSDNode>(N0.getOperand(0)) &&
VT.isInteger() && !VT.isVector()) {
unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
if (isTypeLegal(IntXVT)) {
SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
AddToWorklist(X.getNode());
// If X has a different width than the result/lhs, sext it or truncate it.
unsigned VTWidth = VT.getSizeInBits();
if (OrigXWidth < VTWidth) {
X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
AddToWorklist(X.getNode());
} else if (OrigXWidth > VTWidth) {
// To get the sign bit in the right place, we have to shift it right
// before truncating.
SDLoc DL(X);
X = DAG.getNode(ISD::SRL, DL,
X.getValueType(), X,
DAG.getConstant(OrigXWidth-VTWidth, DL,
X.getValueType()));
AddToWorklist(X.getNode());
X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
AddToWorklist(X.getNode());
}
if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
APInt SignBit = APInt::getSignBit(VT.getSizeInBits() / 2);
SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
AddToWorklist(Cst.getNode());
SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
AddToWorklist(X.getNode());
SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
AddToWorklist(XorResult.getNode());
SDValue XorResult64 = DAG.getNode(
ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
SDLoc(XorResult)));
AddToWorklist(XorResult64.getNode());
SDValue FlipBit =
DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
AddToWorklist(FlipBit.getNode());
SDValue FlipBits =
DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
AddToWorklist(FlipBits.getNode());
return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
}
APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
X = DAG.getNode(ISD::AND, SDLoc(X), VT,
X, DAG.getConstant(SignBit, SDLoc(X), VT));
AddToWorklist(X.getNode());
SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
AddToWorklist(Cst.getNode());
return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
}
}
// bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
if (N0.getOpcode() == ISD::BUILD_PAIR)
if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
return CombineLD;
// Remove double bitcasts from shuffles - this is often a legacy of
// XformToShuffleWithZero being used to combine bitmaskings (of
// float vectors bitcast to integer vectors) into shuffles.
// bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
!(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
// If operands are a bitcast, peek through if it casts the original VT.
// If operands are a constant, just bitcast back to original VT.
auto PeekThroughBitcast = [&](SDValue Op) {
if (Op.getOpcode() == ISD::BITCAST &&
Op.getOperand(0).getValueType() == VT)
return SDValue(Op.getOperand(0));
if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
return DAG.getBitcast(VT, Op);
return SDValue();
};
SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
if (!(SV0 && SV1))
return SDValue();
int MaskScale =
VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
SmallVector<int, 8> NewMask;
for (int M : SVN->getMask())
for (int i = 0; i != MaskScale; ++i)
NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
if (!LegalMask) {
std::swap(SV0, SV1);
ShuffleVectorSDNode::commuteMask(NewMask);
LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
}
if (LegalMask)
return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
}
return SDValue();
}
SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
EVT VT = N->getValueType(0);
return CombineConsecutiveLoads(N, VT);
}
/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
/// operands. DstEltVT indicates the destination element value type.
SDValue DAGCombiner::
ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
// If this is already the right type, we're done.
if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
unsigned SrcBitSize = SrcEltVT.getSizeInBits();
unsigned DstBitSize = DstEltVT.getSizeInBits();
// If this is a conversion of N elements of one type to N elements of another
// type, convert each element. This handles FP<->INT cases.
if (SrcBitSize == DstBitSize) {
EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
BV->getValueType(0).getVectorNumElements());
// Due to the FP element handling below calling this routine recursively,
// we can end up with a scalar-to-vector node here.
if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
DAG.getBitcast(DstEltVT, BV->getOperand(0)));
SmallVector<SDValue, 8> Ops;
for (SDValue Op : BV->op_values()) {
// If the vector element type is not legal, the BUILD_VECTOR operands
// are promoted and implicitly truncated. Make that explicit here.
if (Op.getValueType() != SrcEltVT)
Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
Ops.push_back(DAG.getBitcast(DstEltVT, Op));
AddToWorklist(Ops.back().getNode());
}
return DAG.getBuildVector(VT, SDLoc(BV), Ops);
}
// Otherwise, we're growing or shrinking the elements. To avoid having to
// handle annoying details of growing/shrinking FP values, we convert them to
// int first.
if (SrcEltVT.isFloatingPoint()) {
// Convert the input float vector to a int vector where the elements are the
// same sizes.
EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
SrcEltVT = IntVT;
}
// Now we know the input is an integer vector. If the output is a FP type,
// convert to integer first, then to FP of the right size.
if (DstEltVT.isFloatingPoint()) {
EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
// Next, convert to FP elements of the same size.
return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
}
SDLoc DL(BV);
// Okay, we know the src/dst types are both integers of differing types.
// Handling growing first.
assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
if (SrcBitSize < DstBitSize) {
unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
SmallVector<SDValue, 8> Ops;
for (unsigned i = 0, e = BV->getNumOperands(); i != e;
i += NumInputsPerOutput) {
bool isLE = DAG.getDataLayout().isLittleEndian();
APInt NewBits = APInt(DstBitSize, 0);
bool EltIsUndef = true;
for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
// Shift the previously computed bits over.
NewBits <<= SrcBitSize;
SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
if (Op.isUndef()) continue;
EltIsUndef = false;
NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
zextOrTrunc(SrcBitSize).zext(DstBitSize);
}
if (EltIsUndef)
Ops.push_back(DAG.getUNDEF(DstEltVT));
else
Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
}
EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
return DAG.getBuildVector(VT, DL, Ops);
}
// Finally, this must be the case where we are shrinking elements: each input
// turns into multiple outputs.
unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
NumOutputsPerInput*BV->getNumOperands());
SmallVector<SDValue, 8> Ops;
for (const SDValue &Op : BV->op_values()) {
if (Op.isUndef()) {
Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
continue;
}
APInt OpVal = cast<ConstantSDNode>(Op)->
getAPIntValue().zextOrTrunc(SrcBitSize);
for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
APInt ThisVal = OpVal.trunc(DstBitSize);
Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
OpVal = OpVal.lshr(DstBitSize);
}
// For big endian targets, swap the order of the pieces of each element.
if (DAG.getDataLayout().isBigEndian())
std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
}
return DAG.getBuildVector(VT, DL, Ops);
}
static bool isContractable(SDNode *N) {
SDNodeFlags F = cast<BinaryWithFlagsSDNode>(N)->Flags;
return F.hasAllowContract() || F.hasUnsafeAlgebra();
}
/// Try to perform FMA combining on a given FADD node.
SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
SDLoc SL(N);
const TargetOptions &Options = DAG.getTarget().Options;
// Floating-point multiply-add with intermediate rounding.
bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
// Floating-point multiply-add without intermediate rounding.
bool HasFMA =
TLI.isFMAFasterThanFMulAndFAdd(VT) &&
(!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
// No valid opcode, do not combine.
if (!HasFMAD && !HasFMA)
return SDValue();
bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
Options.UnsafeFPMath || HasFMAD);
// If the addition is not contractable, do not combine.
if (!AllowFusionGlobally && !isContractable(N))
return SDValue();
const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
return SDValue();
// Always prefer FMAD to FMA for precision.
unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
bool LookThroughFPExt = TLI.isFPExtFree(VT);
// Is the node an FMUL and contractable either due to global flags or
// SDNodeFlags.
auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
if (N.getOpcode() != ISD::FMUL)
return false;
return AllowFusionGlobally || isContractable(N.getNode());
};
// If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
// prefer to fold the multiply with fewer uses.
if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
if (N0.getNode()->use_size() > N1.getNode()->use_size())
std::swap(N0, N1);
}
// fold (fadd (fmul x, y), z) -> (fma x, y, z)
if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
return DAG.getNode(PreferredFusedOpcode, SL, VT,
N0.getOperand(0), N0.getOperand(1), N1);
}
// fold (fadd x, (fmul y, z)) -> (fma y, z, x)
// Note: Commutes FADD operands.
if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
return DAG.getNode(PreferredFusedOpcode, SL, VT,
N1.getOperand(0), N1.getOperand(1), N0);
}
// Look through FP_EXTEND nodes to do more combining.
if (LookThroughFPExt) {
// fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
if (N0.getOpcode() == ISD::FP_EXTEND) {
SDValue N00 = N0.getOperand(0);
if (isContractableFMUL(N00))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N00.getOperand(0)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N00.getOperand(1)), N1);
}
// fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
// Note: Commutes FADD operands.
if (N1.getOpcode() == ISD::FP_EXTEND) {
SDValue N10 = N1.getOperand(0);
if (isContractableFMUL(N10))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N10.getOperand(0)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N10.getOperand(1)), N0);
}
}
// More folding opportunities when target permits.
if (Aggressive) {
// fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
// FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
// are currently only supported on binary nodes.
if (Options.UnsafeFPMath &&
N0.getOpcode() == PreferredFusedOpcode &&
N0.getOperand(2).getOpcode() == ISD::FMUL &&
N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
return DAG.getNode(PreferredFusedOpcode, SL, VT,
N0.getOperand(0), N0.getOperand(1),
DAG.getNode(PreferredFusedOpcode, SL, VT,
N0.getOperand(2).getOperand(0),
N0.getOperand(2).getOperand(1),
N1));
}
// fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
// FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
// are currently only supported on binary nodes.
if (Options.UnsafeFPMath &&
N1->getOpcode() == PreferredFusedOpcode &&
N1.getOperand(2).getOpcode() == ISD::FMUL &&
N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) {
return DAG.getNode(PreferredFusedOpcode, SL, VT,
N1.getOperand(0), N1.getOperand(1),
DAG.getNode(PreferredFusedOpcode, SL, VT,
N1.getOperand(2).getOperand(0),
N1.getOperand(2).getOperand(1),
N0));
}
if (LookThroughFPExt) {
// fold (fadd (fma x, y, (fpext (fmul u, v))), z)
// -> (fma x, y, (fma (fpext u), (fpext v), z))
auto FoldFAddFMAFPExtFMul = [&] (
SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
Z));
};
if (N0.getOpcode() == PreferredFusedOpcode) {
SDValue N02 = N0.getOperand(2);
if (N02.getOpcode() == ISD::FP_EXTEND) {
SDValue N020 = N02.getOperand(0);
if (isContractableFMUL(N020))
return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
N020.getOperand(0), N020.getOperand(1),
N1);
}
}
// fold (fadd (fpext (fma x, y, (fmul u, v))), z)
// -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
// FIXME: This turns two single-precision and one double-precision
// operation into two double-precision operations, which might not be
// interesting for all targets, especially GPUs.
auto FoldFAddFPExtFMAFMul = [&] (
SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
Z));
};
if (N0.getOpcode() == ISD::FP_EXTEND) {
SDValue N00 = N0.getOperand(0);
if (N00.getOpcode() == PreferredFusedOpcode) {
SDValue N002 = N00.getOperand(2);
if (isContractableFMUL(N002))
return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
N002.getOperand(0), N002.getOperand(1),
N1);
}
}
// fold (fadd x, (fma y, z, (fpext (fmul u, v)))
// -> (fma y, z, (fma (fpext u), (fpext v), x))
if (N1.getOpcode() == PreferredFusedOpcode) {
SDValue N12 = N1.getOperand(2);
if (N12.getOpcode() == ISD::FP_EXTEND) {
SDValue N120 = N12.getOperand(0);
if (isContractableFMUL(N120))
return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
N120.getOperand(0), N120.getOperand(1),
N0);
}
}
// fold (fadd x, (fpext (fma y, z, (fmul u, v)))
// -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
// FIXME: This turns two single-precision and one double-precision
// operation into two double-precision operations, which might not be
// interesting for all targets, especially GPUs.
if (N1.getOpcode() == ISD::FP_EXTEND) {
SDValue N10 = N1.getOperand(0);
if (N10.getOpcode() == PreferredFusedOpcode) {
SDValue N102 = N10.getOperand(2);
if (isContractableFMUL(N102))
return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
N102.getOperand(0), N102.getOperand(1),
N0);
}
}
}
}
return SDValue();
}
/// Try to perform FMA combining on a given FSUB node.
SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
SDLoc SL(N);
const TargetOptions &Options = DAG.getTarget().Options;
// Floating-point multiply-add with intermediate rounding.
bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
// Floating-point multiply-add without intermediate rounding.
bool HasFMA =
TLI.isFMAFasterThanFMulAndFAdd(VT) &&
(!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
// No valid opcode, do not combine.
if (!HasFMAD && !HasFMA)
return SDValue();
bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
Options.UnsafeFPMath || HasFMAD);
// If the subtraction is not contractable, do not combine.
if (!AllowFusionGlobally && !isContractable(N))
return SDValue();
const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo();
if (STI && STI->generateFMAsInMachineCombiner(OptLevel))
return SDValue();
// Always prefer FMAD to FMA for precision.
unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
bool LookThroughFPExt = TLI.isFPExtFree(VT);
// Is the node an FMUL and contractable either due to global flags or
// SDNodeFlags.
auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
if (N.getOpcode() != ISD::FMUL)
return false;
return AllowFusionGlobally || isContractable(N.getNode());
};
// fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
return DAG.getNode(PreferredFusedOpcode, SL, VT,
N0.getOperand(0), N0.getOperand(1),
DAG.getNode(ISD::FNEG, SL, VT, N1));
}
// fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
// Note: Commutes FSUB operands.
if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse()))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT,
N1.getOperand(0)),
N1.getOperand(1), N0);
// fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
(Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
SDValue N00 = N0.getOperand(0).getOperand(0);
SDValue N01 = N0.getOperand(0).getOperand(1);
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
DAG.getNode(ISD::FNEG, SL, VT, N1));
}
// Look through FP_EXTEND nodes to do more combining.
if (LookThroughFPExt) {
// fold (fsub (fpext (fmul x, y)), z)
// -> (fma (fpext x), (fpext y), (fneg z))
if (N0.getOpcode() == ISD::FP_EXTEND) {
SDValue N00 = N0.getOperand(0);
if (isContractableFMUL(N00))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N00.getOperand(0)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N00.getOperand(1)),
DAG.getNode(ISD::FNEG, SL, VT, N1));
}
// fold (fsub x, (fpext (fmul y, z)))
// -> (fma (fneg (fpext y)), (fpext z), x)
// Note: Commutes FSUB operands.
if (N1.getOpcode() == ISD::FP_EXTEND) {
SDValue N10 = N1.getOperand(0);
if (isContractableFMUL(N10))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N10.getOperand(0))),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N10.getOperand(1)),
N0);
}
// fold (fsub (fpext (fneg (fmul, x, y))), z)
// -> (fneg (fma (fpext x), (fpext y), z))
// Note: This could be removed with appropriate canonicalization of the
// input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
// orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
// from implementing the canonicalization in visitFSUB.
if (N0.getOpcode() == ISD::FP_EXTEND) {
SDValue N00 = N0.getOperand(0);
if (N00.getOpcode() == ISD::FNEG) {
SDValue N000 = N00.getOperand(0);
if (isContractableFMUL(N000)) {
return DAG.getNode(ISD::FNEG, SL, VT,
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N000.getOperand(0)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N000.getOperand(1)),
N1));
}
}
}
// fold (fsub (fneg (fpext (fmul, x, y))), z)
// -> (fneg (fma (fpext x)), (fpext y), z)
// Note: This could be removed with appropriate canonicalization of the
// input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
// orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
// from implementing the canonicalization in visitFSUB.
if (N0.getOpcode() == ISD::FNEG) {
SDValue N00 = N0.getOperand(0);
if (N00.getOpcode() == ISD::FP_EXTEND) {
SDValue N000 = N00.getOperand(0);
if (isContractableFMUL(N000)) {
return DAG.getNode(ISD::FNEG, SL, VT,
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N000.getOperand(0)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N000.getOperand(1)),
N1));
}
}
}
}
// More folding opportunities when target permits.
if (Aggressive) {
// fold (fsub (fma x, y, (fmul u, v)), z)
// -> (fma x, y (fma u, v, (fneg z)))
// FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
// are currently only supported on binary nodes.
if (Options.UnsafeFPMath && N0.getOpcode() == PreferredFusedOpcode &&
isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() &&
N0.getOperand(2)->hasOneUse()) {
return DAG.getNode(PreferredFusedOpcode, SL, VT,
N0.getOperand(0), N0.getOperand(1),
DAG.getNode(PreferredFusedOpcode, SL, VT,
N0.getOperand(2).getOperand(0),
N0.getOperand(2).getOperand(1),
DAG.getNode(ISD::FNEG, SL, VT,
N1)));
}
// fold (fsub x, (fma y, z, (fmul u, v)))
// -> (fma (fneg y), z, (fma (fneg u), v, x))
// FIXME: The UnsafeAlgebra flag should be propagated to FMA/FMAD, but FMF
// are currently only supported on binary nodes.
if (Options.UnsafeFPMath && N1.getOpcode() == PreferredFusedOpcode &&
isContractableFMUL(N1.getOperand(2))) {
SDValue N20 = N1.getOperand(2).getOperand(0);
SDValue N21 = N1.getOperand(2).getOperand(1);
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT,
N1.getOperand(0)),
N1.getOperand(1),
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT, N20),
N21, N0));
}
if (LookThroughFPExt) {
// fold (fsub (fma x, y, (fpext (fmul u, v))), z)
// -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
if (N0.getOpcode() == PreferredFusedOpcode) {
SDValue N02 = N0.getOperand(2);
if (N02.getOpcode() == ISD::FP_EXTEND) {
SDValue N020 = N02.getOperand(0);
if (isContractableFMUL(N020))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
N0.getOperand(0), N0.getOperand(1),
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N020.getOperand(0)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N020.getOperand(1)),
DAG.getNode(ISD::FNEG, SL, VT,
N1)));
}
}
// fold (fsub (fpext (fma x, y, (fmul u, v))), z)
// -> (fma (fpext x), (fpext y),
// (fma (fpext u), (fpext v), (fneg z)))
// FIXME: This turns two single-precision and one double-precision
// operation into two double-precision operations, which might not be
// interesting for all targets, especially GPUs.
if (N0.getOpcode() == ISD::FP_EXTEND) {
SDValue N00 = N0.getOperand(0);
if (N00.getOpcode() == PreferredFusedOpcode) {
SDValue N002 = N00.getOperand(2);
if (isContractableFMUL(N002))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N00.getOperand(0)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N00.getOperand(1)),
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N002.getOperand(0)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N002.getOperand(1)),
DAG.getNode(ISD::FNEG, SL, VT,
N1)));
}
}
// fold (fsub x, (fma y, z, (fpext (fmul u, v))))
// -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
if (N1.getOpcode() == PreferredFusedOpcode &&
N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
SDValue N120 = N1.getOperand(2).getOperand(0);
if (isContractableFMUL(N120)) {
SDValue N1200 = N120.getOperand(0);
SDValue N1201 = N120.getOperand(1);
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
N1.getOperand(1),
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL,
VT, N1200)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N1201),
N0));
}
}
// fold (fsub x, (fpext (fma y, z, (fmul u, v))))
// -> (fma (fneg (fpext y)), (fpext z),
// (fma (fneg (fpext u)), (fpext v), x))
// FIXME: This turns two single-precision and one double-precision
// operation into two double-precision operations, which might not be
// interesting for all targets, especially GPUs.
if (N1.getOpcode() == ISD::FP_EXTEND &&
N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
SDValue N100 = N1.getOperand(0).getOperand(0);
SDValue N101 = N1.getOperand(0).getOperand(1);
SDValue N102 = N1.getOperand(0).getOperand(2);
if (isContractableFMUL(N102)) {
SDValue N1020 = N102.getOperand(0);
SDValue N1021 = N102.getOperand(1);
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N100)),
DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT,
DAG.getNode(ISD::FP_EXTEND, SL,
VT, N1020)),
DAG.getNode(ISD::FP_EXTEND, SL, VT,
N1021),
N0));
}
}
}
}
return SDValue();
}
/// Try to perform FMA combining on a given FMUL node based on the distributive
/// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
/// subtraction instead of addition).
SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
SDLoc SL(N);
assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
const TargetOptions &Options = DAG.getTarget().Options;
// The transforms below are incorrect when x == 0 and y == inf, because the
// intermediate multiplication produces a nan.
if (!Options.NoInfsFPMath)
return SDValue();
// Floating-point multiply-add without intermediate rounding.
bool HasFMA =
(Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
TLI.isFMAFasterThanFMulAndFAdd(VT) &&
(!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
// Floating-point multiply-add with intermediate rounding. This can result
// in a less precise result due to the changed rounding order.
bool HasFMAD = Options.UnsafeFPMath &&
(LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
// No valid opcode, do not combine.
if (!HasFMAD && !HasFMA)
return SDValue();
// Always prefer FMAD to FMA for precision.
unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
// fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
// fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
auto FuseFADD = [&](SDValue X, SDValue Y) {
if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
if (XC1 && XC1->isExactlyValue(+1.0))
return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
if (XC1 && XC1->isExactlyValue(-1.0))
return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
DAG.getNode(ISD::FNEG, SL, VT, Y));
}
return SDValue();
};
if (SDValue FMA = FuseFADD(N0, N1))
return FMA;
if (SDValue FMA = FuseFADD(N1, N0))
return FMA;
// fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
// fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
// fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
// fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
auto FuseFSUB = [&](SDValue X, SDValue Y) {
if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
if (XC0 && XC0->isExactlyValue(+1.0))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
Y);
if (XC0 && XC0->isExactlyValue(-1.0))
return DAG.getNode(PreferredFusedOpcode, SL, VT,
DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
DAG.getNode(ISD::FNEG, SL, VT, Y));
auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
if (XC1 && XC1->isExactlyValue(+1.0))
return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
DAG.getNode(ISD::FNEG, SL, VT, Y));
if (XC1 && XC1->isExactlyValue(-1.0))
return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
}
return SDValue();
};
if (SDValue FMA = FuseFSUB(N0, N1))
return FMA;
if (SDValue FMA = FuseFSUB(N1, N0))
return FMA;
return SDValue();
}
SDValue DAGCombiner::visitFADD(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
EVT VT = N->getValueType(0);
SDLoc DL(N);
const TargetOptions &Options = DAG.getTarget().Options;
const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
// fold vector ops
if (VT.isVector())
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (fadd c1, c2) -> c1 + c2
if (N0CFP && N1CFP)
return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
// canonicalize constant to RHS
if (N0CFP && !N1CFP)
return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// fold (fadd A, (fneg B)) -> (fsub A, B)
if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
return DAG.getNode(ISD::FSUB, DL, VT, N0,
GetNegatedExpression(N1, DAG, LegalOperations), Flags);
// fold (fadd (fneg A), B) -> (fsub B, A)
if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
return DAG.getNode(ISD::FSUB, DL, VT, N1,
GetNegatedExpression(N0, DAG, LegalOperations), Flags);
// FIXME: Auto-upgrade the target/function-level option.
if (Options.NoSignedZerosFPMath || N->getFlags()->hasNoSignedZeros()) {
// fold (fadd A, 0) -> A
if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
if (N1C->isZero())
return N0;
}
// If 'unsafe math' is enabled, fold lots of things.
if (Options.UnsafeFPMath) {
// No FP constant should be created after legalization as Instruction
// Selection pass has a hard time dealing with FP constants.
bool AllowNewConst = (Level < AfterLegalizeDAG);
// fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
Flags),
Flags);
// If allowed, fold (fadd (fneg x), x) -> 0.0
if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
return DAG.getConstantFP(0.0, DL, VT);
// If allowed, fold (fadd x, (fneg x)) -> 0.0
if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
return DAG.getConstantFP(0.0, DL, VT);
// We can fold chains of FADD's of the same value into multiplications.
// This transform is not safe in general because we are reducing the number
// of rounding steps.
if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
if (N0.getOpcode() == ISD::FMUL) {
bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
// (fadd (fmul x, c), x) -> (fmul x, c+1)
if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
DAG.getConstantFP(1.0, DL, VT), Flags);
return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
}
// (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
N1.getOperand(0) == N1.getOperand(1) &&
N0.getOperand(0) == N1.getOperand(0)) {
SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
DAG.getConstantFP(2.0, DL, VT), Flags);
return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
}
}
if (N1.getOpcode() == ISD::FMUL) {
bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
// (fadd x, (fmul x, c)) -> (fmul x, c+1)
if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
DAG.getConstantFP(1.0, DL, VT), Flags);
return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
}
// (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
N0.getOperand(0) == N0.getOperand(1) &&
N1.getOperand(0) == N0.getOperand(0)) {
SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
DAG.getConstantFP(2.0, DL, VT), Flags);
return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
}
}
if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
// (fadd (fadd x, x), x) -> (fmul x, 3.0)
if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
(N0.getOperand(0) == N1)) {
return DAG.getNode(ISD::FMUL, DL, VT,
N1, DAG.getConstantFP(3.0, DL, VT), Flags);
}
}
if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
// (fadd x, (fadd x, x)) -> (fmul x, 3.0)
if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
N1.getOperand(0) == N0) {
return DAG.getNode(ISD::FMUL, DL, VT,
N0, DAG.getConstantFP(3.0, DL, VT), Flags);
}
}
// (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
if (AllowNewConst &&
N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
N0.getOperand(0) == N0.getOperand(1) &&
N1.getOperand(0) == N1.getOperand(1) &&
N0.getOperand(0) == N1.getOperand(0)) {
return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
DAG.getConstantFP(4.0, DL, VT), Flags);
}
}
} // enable-unsafe-fp-math
// FADD -> FMA combines:
if (SDValue Fused = visitFADDForFMACombine(N)) {
AddToWorklist(Fused.getNode());
return Fused;
}
return SDValue();
}
SDValue DAGCombiner::visitFSUB(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
EVT VT = N->getValueType(0);
SDLoc DL(N);
const TargetOptions &Options = DAG.getTarget().Options;
const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
// fold vector ops
if (VT.isVector())
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (fsub c1, c2) -> c1-c2
if (N0CFP && N1CFP)
return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags);
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
// fold (fsub A, (fneg B)) -> (fadd A, B)
if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
return DAG.getNode(ISD::FADD, DL, VT, N0,
GetNegatedExpression(N1, DAG, LegalOperations), Flags);
// FIXME: Auto-upgrade the target/function-level option.
if (Options.NoSignedZerosFPMath || N->getFlags()->hasNoSignedZeros()) {
// (fsub 0, B) -> -B
if (N0CFP && N0CFP->isZero()) {
if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
return GetNegatedExpression(N1, DAG, LegalOperations);
if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags);
}
}
// If 'unsafe math' is enabled, fold lots of things.
if (Options.UnsafeFPMath) {
// (fsub A, 0) -> A
if (N1CFP && N1CFP->isZero())
return N0;
// (fsub x, x) -> 0.0
if (N0 == N1)
return DAG.getConstantFP(0.0f, DL, VT);
// (fsub x, (fadd x, y)) -> (fneg y)
// (fsub x, (fadd y, x)) -> (fneg y)
if (N1.getOpcode() == ISD::FADD) {
SDValue N10 = N1->getOperand(0);
SDValue N11 = N1->getOperand(1);
if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
return GetNegatedExpression(N11, DAG, LegalOperations);
if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
return GetNegatedExpression(N10, DAG, LegalOperations);
}
}
// FSUB -> FMA combines:
if (SDValue Fused = visitFSUBForFMACombine(N)) {
AddToWorklist(Fused.getNode());
return Fused;
}
return SDValue();
}
SDValue DAGCombiner::visitFMUL(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
EVT VT = N->getValueType(0);
SDLoc DL(N);
const TargetOptions &Options = DAG.getTarget().Options;
const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
// fold vector ops
if (VT.isVector()) {
// This just handles C1 * C2 for vectors. Other vector folds are below.
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
}
// fold (fmul c1, c2) -> c1*c2
if (N0CFP && N1CFP)
return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
// canonicalize constant to RHS
if (isConstantFPBuildVectorOrConstantFP(N0) &&
!isConstantFPBuildVectorOrConstantFP(N1))
return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
// fold (fmul A, 1.0) -> A
if (N1CFP && N1CFP->isExactlyValue(1.0))
return N0;
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
if (Options.UnsafeFPMath) {
// fold (fmul A, 0) -> 0
if (N1CFP && N1CFP->isZero())
return N1;
// fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
if (N0.getOpcode() == ISD::FMUL) {
// Fold scalars or any vector constants (not just splats).
// This fold is done in general by InstCombine, but extra fmul insts
// may have been generated during lowering.
SDValue N00 = N0.getOperand(0);
SDValue N01 = N0.getOperand(1);
auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
// Check 1: Make sure that the first operand of the inner multiply is NOT
// a constant. Otherwise, we may induce infinite looping.
if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
// Check 2: Make sure that the second operand of the inner multiply and
// the second operand of the outer multiply are constants.
if ((N1CFP && isConstOrConstSplatFP(N01)) ||
(BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
}
}
}
// fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
// Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
// during an early run of DAGCombiner can prevent folding with fmuls
// inserted during lowering.
if (N0.getOpcode() == ISD::FADD &&
(N0.getOperand(0) == N0.getOperand(1)) &&
N0.hasOneUse()) {
const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
}
}
// fold (fmul X, 2.0) -> (fadd X, X)
if (N1CFP && N1CFP->isExactlyValue(+2.0))
return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
// fold (fmul X, -1.0) -> (fneg X)
if (N1CFP && N1CFP->isExactlyValue(-1.0))
if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
return DAG.getNode(ISD::FNEG, DL, VT, N0);
// fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
// Both can be negated for free, check to see if at least one is cheaper
// negated.
if (LHSNeg == 2 || RHSNeg == 2)
return DAG.getNode(ISD::FMUL, DL, VT,
GetNegatedExpression(N0, DAG, LegalOperations),
GetNegatedExpression(N1, DAG, LegalOperations),
Flags);
}
}
// FMUL -> FMA combines:
if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
AddToWorklist(Fused.getNode());
return Fused;
}
return SDValue();
}
SDValue DAGCombiner::visitFMA(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
EVT VT = N->getValueType(0);
SDLoc DL(N);
const TargetOptions &Options = DAG.getTarget().Options;
// Constant fold FMA.
if (isa<ConstantFPSDNode>(N0) &&
isa<ConstantFPSDNode>(N1) &&
isa<ConstantFPSDNode>(N2)) {
return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
}
if (Options.UnsafeFPMath) {
if (N0CFP && N0CFP->isZero())
return N2;
if (N1CFP && N1CFP->isZero())
return N2;
}
// TODO: The FMA node should have flags that propagate to these nodes.
if (N0CFP && N0CFP->isExactlyValue(1.0))
return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
if (N1CFP && N1CFP->isExactlyValue(1.0))
return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
// Canonicalize (fma c, x, y) -> (fma x, c, y)
if (isConstantFPBuildVectorOrConstantFP(N0) &&
!isConstantFPBuildVectorOrConstantFP(N1))
return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
// TODO: FMA nodes should have flags that propagate to the created nodes.
// For now, create a Flags object for use with all unsafe math transforms.
SDNodeFlags Flags;
Flags.setUnsafeAlgebra(true);
if (Options.UnsafeFPMath) {
// (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
isConstantFPBuildVectorOrConstantFP(N1) &&
isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
return DAG.getNode(ISD::FMUL, DL, VT, N0,
DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1),
&Flags), &Flags);
}
// (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
if (N0.getOpcode() == ISD::FMUL &&
isConstantFPBuildVectorOrConstantFP(N1) &&
isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
return DAG.getNode(ISD::FMA, DL, VT,
N0.getOperand(0),
DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1),
&Flags),
N2);
}
}
// (fma x, 1, y) -> (fadd x, y)
// (fma x, -1, y) -> (fadd (fneg x), y)
if (N1CFP) {
if (N1CFP->isExactlyValue(1.0))
// TODO: The FMA node should have flags that propagate to this node.
return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
if (N1CFP->isExactlyValue(-1.0) &&
(!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
AddToWorklist(RHSNeg.getNode());
// TODO: The FMA node should have flags that propagate to this node.
return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
}
}
if (Options.UnsafeFPMath) {
// (fma x, c, x) -> (fmul x, (c+1))
if (N1CFP && N0 == N2) {
return DAG.getNode(ISD::FMUL, DL, VT, N0,
DAG.getNode(ISD::FADD, DL, VT, N1,
DAG.getConstantFP(1.0, DL, VT), &Flags),
&Flags);
}
// (fma x, c, (fneg x)) -> (fmul x, (c-1))
if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
return DAG.getNode(ISD::FMUL, DL, VT, N0,
DAG.getNode(ISD::FADD, DL, VT, N1,
DAG.getConstantFP(-1.0, DL, VT), &Flags),
&Flags);
}
}
return SDValue();
}
// Combine multiple FDIVs with the same divisor into multiple FMULs by the
// reciprocal.
// E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
// Notice that this is not always beneficial. One reason is different targets
// may have different costs for FDIV and FMUL, so sometimes the cost of two
// FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
// is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
const SDNodeFlags *Flags = N->getFlags();
if (!UnsafeMath && !Flags->hasAllowReciprocal())
return SDValue();
// Skip if current node is a reciprocal.
SDValue N0 = N->getOperand(0);
ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
if (N0CFP && N0CFP->isExactlyValue(1.0))
return SDValue();
// Exit early if the target does not want this transform or if there can't
// possibly be enough uses of the divisor to make the transform worthwhile.
SDValue N1 = N->getOperand(1);
unsigned MinUses = TLI.combineRepeatedFPDivisors();
if (!MinUses || N1->use_size() < MinUses)
return SDValue();
// Find all FDIV users of the same divisor.
// Use a set because duplicates may be present in the user list.
SetVector<SDNode *> Users;
for (auto *U : N1->uses()) {
if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
// This division is eligible for optimization only if global unsafe math
// is enabled or if this division allows reciprocal formation.
if (UnsafeMath || U->getFlags()->hasAllowReciprocal())
Users.insert(U);
}
}
// Now that we have the actual number of divisor uses, make sure it meets
// the minimum threshold specified by the target.
if (Users.size() < MinUses)
return SDValue();
EVT VT = N->getValueType(0);
SDLoc DL(N);
SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
// Dividend / Divisor -> Dividend * Reciprocal
for (auto *U : Users) {
SDValue Dividend = U->getOperand(0);
if (Dividend != FPOne) {
SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
Reciprocal, Flags);
CombineTo(U, NewNode);
} else if (U != Reciprocal.getNode()) {
// In the absence of fast-math-flags, this user node is always the
// same node as Reciprocal, but with FMF they may be different nodes.
CombineTo(U, Reciprocal);
}
}
return SDValue(N, 0); // N was replaced.
}
SDValue DAGCombiner::visitFDIV(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
EVT VT = N->getValueType(0);
SDLoc DL(N);
const TargetOptions &Options = DAG.getTarget().Options;
SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
// fold vector ops
if (VT.isVector())
if (SDValue FoldedVOp = SimplifyVBinOp(N))
return FoldedVOp;
// fold (fdiv c1, c2) -> c1/c2
if (N0CFP && N1CFP)
return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
if (Options.UnsafeFPMath) {
// fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
if (N1CFP) {
// Compute the reciprocal 1.0 / c2.
const APFloat &N1APF = N1CFP->getValueAPF();
APFloat Recip(N1APF.getSemantics(), 1); // 1.0
APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
// Only do the transform if the reciprocal is a legal fp immediate that
// isn't too nasty (eg NaN, denormal, ...).
if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
(!LegalOperations ||
// FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
// backend)... we should handle this gracefully after Legalize.
// TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
TLI.isFPImmLegal(Recip, VT)))
return DAG.getNode(ISD::FMUL, DL, VT, N0,
DAG.getConstantFP(Recip, DL, VT), Flags);
}
// If this FDIV is part of a reciprocal square root, it may be folded
// into a target-specific square root estimate instruction.
if (N1.getOpcode() == ISD::FSQRT) {
if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) {
return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
}
} else if (N1.getOpcode() == ISD::FP_EXTEND &&
N1.getOperand(0).getOpcode() == ISD::FSQRT) {
if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
Flags)) {
RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
AddToWorklist(RV.getNode());
return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
}
} else if (N1.getOpcode() == ISD::FP_ROUND &&
N1.getOperand(0).getOpcode() == ISD::FSQRT) {
if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0),
Flags)) {
RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
AddToWorklist(RV.getNode());
return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
}
} else if (N1.getOpcode() == ISD::FMUL) {
// Look through an FMUL. Even though this won't remove the FDIV directly,
// it's still worthwhile to get rid of the FSQRT if possible.
SDValue SqrtOp;
SDValue OtherOp;
if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
SqrtOp = N1.getOperand(0);
OtherOp = N1.getOperand(1);
} else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
SqrtOp = N1.getOperand(1);
OtherOp = N1.getOperand(0);
}
if (SqrtOp.getNode()) {
// We found a FSQRT, so try to make this fold:
// x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
AddToWorklist(RV.getNode());
return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
}
}
}
// Fold into a reciprocal estimate and multiply instead of a real divide.
if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
AddToWorklist(RV.getNode());
return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
}
}
// (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
// Both can be negated for free, check to see if at least one is cheaper
// negated.
if (LHSNeg == 2 || RHSNeg == 2)
return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
GetNegatedExpression(N0, DAG, LegalOperations),
GetNegatedExpression(N1, DAG, LegalOperations),
Flags);
}
}
if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
return CombineRepeatedDivisors;
return SDValue();
}
SDValue DAGCombiner::visitFREM(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
EVT VT = N->getValueType(0);
// fold (frem c1, c2) -> fmod(c1,c2)
if (N0CFP && N1CFP)
return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
&cast<BinaryWithFlagsSDNode>(N)->Flags);
if (SDValue NewSel = foldBinOpIntoSelect(N))
return NewSel;
return SDValue();
}
SDValue DAGCombiner::visitFSQRT(SDNode *N) {
if (!DAG.getTarget().Options.UnsafeFPMath)
return SDValue();
SDValue N0 = N->getOperand(0);
if (TLI.isFsqrtCheap(N0, DAG))
return SDValue();
// TODO: FSQRT nodes should have flags that propagate to the created nodes.
// For now, create a Flags object for use with all unsafe math transforms.
SDNodeFlags Flags;
Flags.setUnsafeAlgebra(true);
return buildSqrtEstimate(N0, &Flags);
}
/// copysign(x, fp_extend(y)) -> copysign(x, y)
/// copysign(x, fp_round(y)) -> copysign(x, y)
static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
SDValue N1 = N->getOperand(1);
if ((N1.getOpcode() == ISD::FP_EXTEND ||
N1.getOpcode() == ISD::FP_ROUND)) {
// Do not optimize out type conversion of f128 type yet.
// For some targets like x86_64, configuration is changed to keep one f128
// value in one SSE register, but instruction selection cannot handle
// FCOPYSIGN on SSE registers yet.
EVT N1VT = N1->getValueType(0);
EVT N1Op0VT = N1->getOperand(0)->getValueType(0);
return (N1VT == N1Op0VT || N1Op0VT != MVT::f128);
}
return false;
}
SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
EVT VT = N->getValueType(0);
if (N0CFP && N1CFP) // Constant fold
return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
if (N1CFP) {
const APFloat &V = N1CFP->getValueAPF();
// copysign(x, c1) -> fabs(x) iff ispos(c1)
// copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
if (!V.isNegative()) {
if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
} else {
if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
}
}
// copysign(fabs(x), y) -> copysign(x, y)
// copysign(fneg(x), y) -> copysign(x, y)
// copysign(copysign(x,z), y) -> copysign(x, y)
if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
N0.getOpcode() == ISD::FCOPYSIGN)
return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
// copysign(x, abs(y)) -> abs(x)
if (N1.getOpcode() == ISD::FABS)
return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
// copysign(x, copysign(y,z)) -> copysign(x, z)
if (N1.getOpcode() == ISD::FCOPYSIGN)
return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
// copysign(x, fp_extend(y)) -> copysign(x, y)
// copysign(x, fp_round(y)) -> copysign(x, y)
if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
return SDValue();
}
SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
EVT OpVT = N0.getValueType();
// fold (sint_to_fp c1) -> c1fp
if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
// ...but only if the target supports immediate floating-point values
(!LegalOperations ||
TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
// If the input is a legal type, and SINT_TO_FP is not legal on this target,
// but UINT_TO_FP is legal on this target, try to convert.
if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
// If the sign bit is known to be zero, we can change this to UINT_TO_FP.
if (DAG.SignBitIsZero(N0))
return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
}
// The next optimizations are desirable only if SELECT_CC can be lowered.
if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
// fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
!VT.isVector() &&
(!LegalOperations ||
TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
SDLoc DL(N);
SDValue Ops[] =
{ N0.getOperand(0), N0.getOperand(1),
DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
N0.getOperand(2) };
return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
}
// fold (sint_to_fp (zext (setcc x, y, cc))) ->
// (select_cc x, y, 1.0, 0.0,, cc)
if (N0.getOpcode() == ISD::ZERO_EXTEND &&
N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
(!LegalOperations ||
TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
SDLoc DL(N);
SDValue Ops[] =
{ N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
N0.getOperand(0).getOperand(2) };
return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
}
}
return SDValue();
}
SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
EVT OpVT = N0.getValueType();
// fold (uint_to_fp c1) -> c1fp
if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
// ...but only if the target supports immediate floating-point values
(!LegalOperations ||
TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
// If the input is a legal type, and UINT_TO_FP is not legal on this target,
// but SINT_TO_FP is legal on this target, try to convert.
if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
// If the sign bit is known to be zero, we can change this to SINT_TO_FP.
if (DAG.SignBitIsZero(N0))
return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
}
// The next optimizations are desirable only if SELECT_CC can be lowered.
if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
// fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
(!LegalOperations ||
TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
SDLoc DL(N);
SDValue Ops[] =
{ N0.getOperand(0), N0.getOperand(1),
DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
N0.getOperand(2) };
return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
}
}
return SDValue();
}
// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
return SDValue();
SDValue Src = N0.getOperand(0);
EVT SrcVT = Src.getValueType();
bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
// We can safely assume the conversion won't overflow the output range,
// because (for example) (uint8_t)18293.f is undefined behavior.
// Since we can assume the conversion won't overflow, our decision as to
// whether the input will fit in the float should depend on the minimum
// of the input range and output range.
// This means this is also safe for a signed input and unsigned output, since
// a negative input would lead to undefined behavior.
unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
unsigned ActualSize = std::min(InputSize, OutputSize);
const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
// We can only fold away the float conversion if the input range can be
// represented exactly in the float range.
if (APFloat::semanticsPrecision(sem) >= ActualSize) {
if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND;
return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
}
if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
return DAG.getBitcast(VT, Src);
}
return SDValue();
}
SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (fp_to_sint c1fp) -> c1
if (isConstantFPBuildVectorOrConstantFP(N0))
return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
return FoldIntToFPToInt(N, DAG);
}
SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (fp_to_uint c1fp) -> c1
if (isConstantFPBuildVectorOrConstantFP(N0))
return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
return FoldIntToFPToInt(N, DAG);
}
SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
EVT VT = N->getValueType(0);
// fold (fp_round c1fp) -> c1fp
if (N0CFP)
return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
// fold (fp_round (fp_extend x)) -> x
if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
return N0.getOperand(0);
// fold (fp_round (fp_round x)) -> (fp_round x)
if (N0.getOpcode() == ISD::FP_ROUND) {
const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
// Skip this folding if it results in an fp_round from f80 to f16.
//
// f80 to f16 always generates an expensive (and as yet, unimplemented)
// libcall to __truncxfhf2 instead of selecting native f16 conversion
// instructions from f32 or f64. Moreover, the first (value-preserving)
// fp_round from f80 to either f32 or f64 may become a NOP in platforms like
// x86.
if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
return SDValue();
// If the first fp_round isn't a value preserving truncation, it might
// introduce a tie in the second fp_round, that wouldn't occur in the
// single-step fp_round we want to fold to.
// In other words, double rounding isn't the same as rounding.
// Also, this is a value preserving truncation iff both fp_round's are.
if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
SDLoc DL(N);
return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
}
}
// fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
N0.getOperand(0), N1);
AddToWorklist(Tmp.getNode());
return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Tmp, N0.getOperand(1));
}
return SDValue();
}
SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
// fold (fp_round_inreg c1fp) -> c1fp
if (N0CFP && isTypeLegal(EVT)) {
SDLoc DL(N);
SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
}
return SDValue();
}
SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
if (N->hasOneUse() &&
N->use_begin()->getOpcode() == ISD::FP_ROUND)
return SDValue();
// fold (fp_extend c1fp) -> c1fp
if (isConstantFPBuildVectorOrConstantFP(N0))
return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
// fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
if (N0.getOpcode() == ISD::FP16_TO_FP &&
TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
// Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
// value of X.
if (N0.getOpcode() == ISD::FP_ROUND
&& N0.getConstantOperandVal(1) == 1) {
SDValue In = N0.getOperand(0);
if (In.getValueType() == VT) return In;
if (VT.bitsLT(In.getValueType()))
return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
In, N0.getOperand(1));
return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
}
// fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
LoadSDNode *LN0 = cast<LoadSDNode>(N0);
SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
LN0->getChain(),
LN0->getBasePtr(), N0.getValueType(),
LN0->getMemOperand());
CombineTo(N, ExtLoad);
CombineTo(N0.getNode(),
DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
N0.getValueType(), ExtLoad,
DAG.getIntPtrConstant(1, SDLoc(N0))),
ExtLoad.getValue(1));
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
return SDValue();
}
SDValue DAGCombiner::visitFCEIL(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (fceil c1) -> fceil(c1)
if (isConstantFPBuildVectorOrConstantFP(N0))
return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
return SDValue();
}
SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (ftrunc c1) -> ftrunc(c1)
if (isConstantFPBuildVectorOrConstantFP(N0))
return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
return SDValue();
}
SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (ffloor c1) -> ffloor(c1)
if (isConstantFPBuildVectorOrConstantFP(N0))
return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
return SDValue();
}
// FIXME: FNEG and FABS have a lot in common; refactor.
SDValue DAGCombiner::visitFNEG(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// Constant fold FNEG.
if (isConstantFPBuildVectorOrConstantFP(N0))
return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
&DAG.getTarget().Options))
return GetNegatedExpression(N0, DAG, LegalOperations);
// Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
// constant pool values.
if (!TLI.isFNegFree(VT) &&
N0.getOpcode() == ISD::BITCAST &&
N0.getNode()->hasOneUse()) {
SDValue Int = N0.getOperand(0);
EVT IntVT = Int.getValueType();
if (IntVT.isInteger() && !IntVT.isVector()) {
APInt SignMask;
if (N0.getValueType().isVector()) {
// For a vector, get a mask such as 0x80... per scalar element
// and splat it.
SignMask = APInt::getSignBit(N0.getScalarValueSizeInBits());
SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
} else {
// For a scalar, just generate 0x80...
SignMask = APInt::getSignBit(IntVT.getSizeInBits());
}
SDLoc DL0(N0);
Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
DAG.getConstant(SignMask, DL0, IntVT));
AddToWorklist(Int.getNode());
return DAG.getBitcast(VT, Int);
}
}
// (fneg (fmul c, x)) -> (fmul -c, x)
if (N0.getOpcode() == ISD::FMUL &&
(N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
if (CFP1) {
APFloat CVal = CFP1->getValueAPF();
CVal.changeSign();
if (Level >= AfterLegalizeDAG &&
(TLI.isFPImmLegal(CVal, VT) ||
TLI.isOperationLegal(ISD::ConstantFP, VT)))
return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
DAG.getNode(ISD::FNEG, SDLoc(N), VT,
N0.getOperand(1)),
&cast<BinaryWithFlagsSDNode>(N0)->Flags);
}
}
return SDValue();
}
SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
if (N0CFP && N1CFP) {
const APFloat &C0 = N0CFP->getValueAPF();
const APFloat &C1 = N1CFP->getValueAPF();
return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
}
// Canonicalize to constant on RHS.
if (isConstantFPBuildVectorOrConstantFP(N0) &&
!isConstantFPBuildVectorOrConstantFP(N1))
return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
return SDValue();
}
SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
EVT VT = N->getValueType(0);
const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
if (N0CFP && N1CFP) {
const APFloat &C0 = N0CFP->getValueAPF();
const APFloat &C1 = N1CFP->getValueAPF();
return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
}
// Canonicalize to constant on RHS.
if (isConstantFPBuildVectorOrConstantFP(N0) &&
!isConstantFPBuildVectorOrConstantFP(N1))
return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
return SDValue();
}
SDValue DAGCombiner::visitFABS(SDNode *N) {
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fold (fabs c1) -> fabs(c1)
if (isConstantFPBuildVectorOrConstantFP(N0))
return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
// fold (fabs (fabs x)) -> (fabs x)
if (N0.getOpcode() == ISD::FABS)
return N->getOperand(0);
// fold (fabs (fneg x)) -> (fabs x)
// fold (fabs (fcopysign x, y)) -> (fabs x)
if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
// Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
// constant pool values.
if (!TLI.isFAbsFree(VT) &&
N0.getOpcode() == ISD::BITCAST &&
N0.getNode()->hasOneUse()) {
SDValue Int = N0.getOperand(0);
EVT IntVT = Int.getValueType();
if (IntVT.isInteger() && !IntVT.isVector()) {
APInt SignMask;
if (N0.getValueType().isVector()) {
// For a vector, get a mask such as 0x7f... per scalar element
// and splat it.
SignMask = ~APInt::getSignBit(N0.getScalarValueSizeInBits());
SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
} else {
// For a scalar, just generate 0x7f...
SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
}
SDLoc DL(N0);
Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
DAG.getConstant(SignMask, DL, IntVT));
AddToWorklist(Int.getNode());
return DAG.getBitcast(N->getValueType(0), Int);
}
}
return SDValue();
}
SDValue DAGCombiner::visitBRCOND(SDNode *N) {
SDValue Chain = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
// If N is a constant we could fold this into a fallthrough or unconditional
// branch. However that doesn't happen very often in normal code, because
// Instcombine/SimplifyCFG should have handled the available opportunities.
// If we did this folding here, it would be necessary to update the
// MachineBasicBlock CFG, which is awkward.
// fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
// on the target.
if (N1.getOpcode() == ISD::SETCC &&
TLI.isOperationLegalOrCustom(ISD::BR_CC,
N1.getOperand(0).getValueType())) {
return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Chain, N1.getOperand(2),
N1.getOperand(0), N1.getOperand(1), N2);
}
if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
(N1.getOperand(0).hasOneUse() &&
N1.getOperand(0).getOpcode() == ISD::SRL))) {
SDNode *Trunc = nullptr;
if (N1.getOpcode() == ISD::TRUNCATE) {
// Look pass the truncate.
Trunc = N1.getNode();
N1 = N1.getOperand(0);
}
// Match this pattern so that we can generate simpler code:
//
// %a = ...
// %b = and i32 %a, 2
// %c = srl i32 %b, 1
// brcond i32 %c ...
//
// into
//
// %a = ...
// %b = and i32 %a, 2
// %c = setcc eq %b, 0
// brcond %c ...
//
// This applies only when the AND constant value has one bit set and the
// SRL constant is equal to the log2 of the AND constant. The back-end is
// smart enough to convert the result into a TEST/JMP sequence.
SDValue Op0 = N1.getOperand(0);
SDValue Op1 = N1.getOperand(1);
if (Op0.getOpcode() == ISD::AND &&
Op1.getOpcode() == ISD::Constant) {
SDValue AndOp1 = Op0.getOperand(1);
if (AndOp1.getOpcode() == ISD::Constant) {
const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
if (AndConst.isPowerOf2() &&
cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
SDLoc DL(N);
SDValue SetCC =
DAG.getSetCC(DL,
getSetCCResultType(Op0.getValueType()),
Op0, DAG.getConstant(0, DL, Op0.getValueType()),
ISD::SETNE);
SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
MVT::Other, Chain, SetCC, N2);
// Don't add the new BRCond into the worklist or else SimplifySelectCC
// will convert it back to (X & C1) >> C2.
CombineTo(N, NewBRCond, false);
// Truncate is dead.
if (Trunc)
deleteAndRecombine(Trunc);
// Replace the uses of SRL with SETCC
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
deleteAndRecombine(N1.getNode());
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
}
if (Trunc)
// Restore N1 if the above transformation doesn't match.
N1 = N->getOperand(1);
}
// Transform br(xor(x, y)) -> br(x != y)
// Transform br(xor(xor(x,y), 1)) -> br (x == y)
if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
SDNode *TheXor = N1.getNode();
SDValue Op0 = TheXor->getOperand(0);
SDValue Op1 = TheXor->getOperand(1);
if (Op0.getOpcode() == Op1.getOpcode()) {
// Avoid missing important xor optimizations.
if (SDValue Tmp = visitXOR(TheXor)) {
if (Tmp.getNode() != TheXor) {
DEBUG(dbgs() << "\nReplacing.8 ";
TheXor->dump(&DAG);
dbgs() << "\nWith: ";
Tmp.getNode()->dump(&DAG);
dbgs() << '\n');
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
deleteAndRecombine(TheXor);
return DAG.getNode(ISD::BRCOND, SDLoc(N),
MVT::Other, Chain, Tmp, N2);
}
// visitXOR has changed XOR's operands or replaced the XOR completely,
// bail out.
return SDValue(N, 0);
}
}
if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
bool Equal = false;
if (isOneConstant(Op0) && Op0.hasOneUse() &&
Op0.getOpcode() == ISD::XOR) {
TheXor = Op0.getNode();
Equal = true;
}
EVT SetCCVT = N1.getValueType();
if (LegalTypes)
SetCCVT = getSetCCResultType(SetCCVT);
SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
SetCCVT,
Op0, Op1,
Equal ? ISD::SETEQ : ISD::SETNE);
// Replace the uses of XOR with SETCC
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
deleteAndRecombine(N1.getNode());
return DAG.getNode(ISD::BRCOND, SDLoc(N),
MVT::Other, Chain, SetCC, N2);
}
}
return SDValue();
}
// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
//
SDValue DAGCombiner::visitBR_CC(SDNode *N) {
CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
// If N is a constant we could fold this into a fallthrough or unconditional
// branch. However that doesn't happen very often in normal code, because
// Instcombine/SimplifyCFG should have handled the available opportunities.
// If we did this folding here, it would be necessary to update the
// MachineBasicBlock CFG, which is awkward.
// Use SimplifySetCC to simplify SETCC's.
SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
CondLHS, CondRHS, CC->get(), SDLoc(N),
false);
if (Simp.getNode()) AddToWorklist(Simp.getNode());
// fold to a simpler setcc
if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
N->getOperand(0), Simp.getOperand(2),
Simp.getOperand(0), Simp.getOperand(1),
N->getOperand(4));
return SDValue();
}
/// Return true if 'Use' is a load or a store that uses N as its base pointer
/// and that N may be folded in the load / store addressing mode.
static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
SelectionDAG &DAG,
const TargetLowering &TLI) {
EVT VT;
unsigned AS;
if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
return false;
VT = LD->getMemoryVT();
AS = LD->getAddressSpace();
} else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
return false;
VT = ST->getMemoryVT();
AS = ST->getAddressSpace();
} else
return false;
TargetLowering::AddrMode AM;
if (N->getOpcode() == ISD::ADD) {
ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
if (Offset)
// [reg +/- imm]
AM.BaseOffs = Offset->getSExtValue();
else
// [reg +/- reg]
AM.Scale = 1;
} else if (N->getOpcode() == ISD::SUB) {
ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
if (Offset)
// [reg +/- imm]
AM.BaseOffs = -Offset->getSExtValue();
else
// [reg +/- reg]
AM.Scale = 1;
} else
return false;
return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
VT.getTypeForEVT(*DAG.getContext()), AS);
}
/// Try turning a load/store into a pre-indexed load/store when the base
/// pointer is an add or subtract and it has other uses besides the load/store.
/// After the transformation, the new indexed load/store has effectively folded
/// the add/subtract in and all of its other uses are redirected to the
/// new load/store.
bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
if (Level < AfterLegalizeDAG)
return false;
bool isLoad = true;
SDValue Ptr;
EVT VT;
if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
if (LD->isIndexed())
return false;
VT = LD->getMemoryVT();
if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
!TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
return false;
Ptr = LD->getBasePtr();
} else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
if (ST->isIndexed())
return false;
VT = ST->getMemoryVT();
if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
!TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
return false;
Ptr = ST->getBasePtr();
isLoad = false;
} else {
return false;
}
// If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
// out. There is no reason to make this a preinc/predec.
if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Ptr.getNode()->hasOneUse())
return false;
// Ask the target to do addressing mode selection.
SDValue BasePtr;
SDValue Offset;
ISD::MemIndexedMode AM = ISD::UNINDEXED;
if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
return false;
// Backends without true r+i pre-indexed forms may need to pass a
// constant base with a variable offset so that constant coercion
// will work with the patterns in canonical form.
bool Swapped = false;
if (isa<ConstantSDNode>(BasePtr)) {
std::swap(BasePtr, Offset);
Swapped = true;
}
// Don't create a indexed load / store with zero offset.
if (isNullConstant(Offset))
return false;
// Try turning it into a pre-indexed load / store except when:
// 1) The new base ptr is a frame index.
// 2) If N is a store and the new base ptr is either the same as or is a
// predecessor of the value being stored.
// 3) Another use of old base ptr is a predecessor of N. If ptr is folded
// that would create a cycle.
// 4) All uses are load / store ops that use it as old base ptr.
// Check #1. Preinc'ing a frame index would require copying the stack pointer
// (plus the implicit offset) to a register to preinc anyway.
if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
return false;
// Check #2.
if (!isLoad) {
SDValue Val = cast<StoreSDNode>(N)->getValue();
if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
return false;
}
// Caches for hasPredecessorHelper.
SmallPtrSet<const SDNode *, 32> Visited;
SmallVector<const SDNode *, 16> Worklist;
Worklist.push_back(N);
// If the offset is a constant, there may be other adds of constants that
// can be folded with this one. We should do this to avoid having to keep
// a copy of the original base pointer.
SmallVector<SDNode *, 16> OtherUses;
if (isa<ConstantSDNode>(Offset))
for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
UE = BasePtr.getNode()->use_end();
UI != UE; ++UI) {
SDUse &Use = UI.getUse();
// Skip the use that is Ptr and uses of other results from BasePtr's
// node (important for nodes that return multiple results).
if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
continue;
if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
continue;
if (Use.getUser()->getOpcode() != ISD::ADD &&
Use.getUser()->getOpcode() != ISD::SUB) {
OtherUses.clear();
break;
}
SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
if (!isa<ConstantSDNode>(Op1)) {
OtherUses.clear();
break;
}
// FIXME: In some cases, we can be smarter about this.
if (Op1.getValueType() != Offset.getValueType()) {
OtherUses.clear();
break;
}
OtherUses.push_back(Use.getUser());
}
if (Swapped)
std::swap(BasePtr, Offset);
// Now check for #3 and #4.
bool RealUse = false;
for (SDNode *Use : Ptr.getNode()->uses()) {
if (Use == N)
continue;
if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
return false;
// If Ptr may be folded in addressing mode of other use, then it's
// not profitable to do this transformation.
if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
RealUse = true;
}
if (!RealUse)
return false;
SDValue Result;
if (isLoad)
Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
BasePtr, Offset, AM);
else
Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
BasePtr, Offset, AM);
++PreIndexedNodes;
++NodesCombined;
DEBUG(dbgs() << "\nReplacing.4 ";
N->dump(&DAG);
dbgs() << "\nWith: ";
Result.getNode()->dump(&DAG);
dbgs() << '\n');
WorklistRemover DeadNodes(*this);
if (isLoad) {
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
} else {
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
}
// Finally, since the node is now dead, remove it from the graph.
deleteAndRecombine(N);
if (Swapped)
std::swap(BasePtr, Offset);
// Replace other uses of BasePtr that can be updated to use Ptr
for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
unsigned OffsetIdx = 1;
if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
OffsetIdx = 0;
assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
BasePtr.getNode() && "Expected BasePtr operand");
// We need to replace ptr0 in the following expression:
// x0 * offset0 + y0 * ptr0 = t0
// knowing that
// x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
//
// where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
// indexed load/store and the expresion that needs to be re-written.
//
// Therefore, we have:
// t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
ConstantSDNode *CN =
cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
int X0, X1, Y0, Y1;
const APInt &Offset0 = CN->getAPIntValue();
APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
APInt CNV = Offset0;
if (X0 < 0) CNV = -CNV;
if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
else CNV = CNV - Offset1;
SDLoc DL(OtherUses[i]);
// We can now generate the new expression.
SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
SDValue NewUse = DAG.getNode(Opcode,
DL,
OtherUses[i]->getValueType(0), NewOp1, NewOp2);
DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
deleteAndRecombine(OtherUses[i]);
}
// Replace the uses of Ptr with uses of the updated base value.
DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
deleteAndRecombine(Ptr.getNode());
return true;
}
/// Try to combine a load/store with a add/sub of the base pointer node into a
/// post-indexed load/store. The transformation folded the add/subtract into the
/// new indexed load/store effectively and all of its uses are redirected to the
/// new load/store.
bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
if (Level < AfterLegalizeDAG)
return false;
bool isLoad = true;
SDValue Ptr;
EVT VT;
if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
if (LD->isIndexed())
return false;
VT = LD->getMemoryVT();
if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
!TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
return false;
Ptr = LD->getBasePtr();
} else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
if (ST->isIndexed())
return false;
VT = ST->getMemoryVT();
if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
!TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
return false;
Ptr = ST->getBasePtr();
isLoad = false;
} else {
return false;
}
if (Ptr.getNode()->hasOneUse())
return false;
for (SDNode *Op : Ptr.getNode()->uses()) {
if (Op == N ||
(Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
continue;
SDValue BasePtr;
SDValue Offset;
ISD::MemIndexedMode AM = ISD::UNINDEXED;
if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
// Don't create a indexed load / store with zero offset.
if (isNullConstant(Offset))
continue;
// Try turning it into a post-indexed load / store except when
// 1) All uses are load / store ops that use it as base ptr (and
// it may be folded as addressing mmode).
// 2) Op must be independent of N, i.e. Op is neither a predecessor
// nor a successor of N. Otherwise, if Op is folded that would
// create a cycle.
if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
continue;
// Check for #1.
bool TryNext = false;
for (SDNode *Use : BasePtr.getNode()->uses()) {
if (Use == Ptr.getNode())
continue;
// If all the uses are load / store addresses, then don't do the
// transformation.
if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
bool RealUse = false;
for (SDNode *UseUse : Use->uses()) {
if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
RealUse = true;
}
if (!RealUse) {
TryNext = true;
break;
}
}
}
if (TryNext)
continue;
// Check for #2
if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
SDValue Result = isLoad
? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
BasePtr, Offset, AM)
: DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
BasePtr, Offset, AM);
++PostIndexedNodes;
++NodesCombined;
DEBUG(dbgs() << "\nReplacing.5 ";
N->dump(&DAG);
dbgs() << "\nWith: ";
Result.getNode()->dump(&DAG);
dbgs() << '\n');
WorklistRemover DeadNodes(*this);
if (isLoad) {
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
} else {
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
}
// Finally, since the node is now dead, remove it from the graph.
deleteAndRecombine(N);
// Replace the uses of Use with uses of the updated base value.
DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Result.getValue(isLoad ? 1 : 0));
deleteAndRecombine(Op);
return true;
}
}
}
return false;
}
/// \brief Return the base-pointer arithmetic from an indexed \p LD.
SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
ISD::MemIndexedMode AM = LD->getAddressingMode();
assert(AM != ISD::UNINDEXED);
SDValue BP = LD->getOperand(1);
SDValue Inc = LD->getOperand(2);
// Some backends use TargetConstants for load offsets, but don't expect
// TargetConstants in general ADD nodes. We can convert these constants into
// regular Constants (if the constant is not opaque).
assert((Inc.getOpcode() != ISD::TargetConstant ||
!cast<ConstantSDNode>(Inc)->isOpaque()) &&
"Cannot split out indexing using opaque target constants");
if (Inc.getOpcode() == ISD::TargetConstant) {
ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
ConstInc->getValueType(0));
}
unsigned Opc =
(AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
}
SDValue DAGCombiner::visitLOAD(SDNode *N) {
LoadSDNode *LD = cast<LoadSDNode>(N);
SDValue Chain = LD->getChain();
SDValue Ptr = LD->getBasePtr();
// If load is not volatile and there are no uses of the loaded value (and
// the updated indexed value in case of indexed loads), change uses of the
// chain value into uses of the chain input (i.e. delete the dead load).
if (!LD->isVolatile()) {
if (N->getValueType(1) == MVT::Other) {
// Unindexed loads.
if (!N->hasAnyUseOfValue(0)) {
// It's not safe to use the two value CombineTo variant here. e.g.
// v1, chain2 = load chain1, loc
// v2, chain3 = load chain2, loc
// v3 = add v2, c
// Now we replace use of chain2 with chain1. This makes the second load
// isomorphic to the one we are deleting, and thus makes this load live.
DEBUG(dbgs() << "\nReplacing.6 ";
N->dump(&DAG);
dbgs() << "\nWith chain: ";
Chain.getNode()->dump(&DAG);
dbgs() << "\n");
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
AddUsersToWorklist(Chain.getNode());
if (N->use_empty())
deleteAndRecombine(N);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
} else {
// Indexed loads.
assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
// If this load has an opaque TargetConstant offset, then we cannot split
// the indexing into an add/sub directly (that TargetConstant may not be
// valid for a different type of node, and we cannot convert an opaque
// target constant into a regular constant).
bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
if (!N->hasAnyUseOfValue(0) &&
((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
SDValue Undef = DAG.getUNDEF(N->getValueType(0));
SDValue Index;
if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Index = SplitIndexingFromLoad(LD);
// Try to fold the base pointer arithmetic into subsequent loads and
// stores.
AddUsersToWorklist(N);
} else
Index = DAG.getUNDEF(N->getValueType(1));
DEBUG(dbgs() << "\nReplacing.7 ";
N->dump(&DAG);
dbgs() << "\nWith: ";
Undef.getNode()->dump(&DAG);
dbgs() << " and 2 other values\n");
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
deleteAndRecombine(N);
return SDValue(N, 0); // Return N so it doesn't get rechecked!
}
}
}
// If this load is directly stored, replace the load value with the stored
// value.
// TODO: Handle store large -> read small portion.
// TODO: Handle TRUNCSTORE/LOADEXT
if (OptLevel != CodeGenOpt::None &&
ISD::isNormalLoad(N) && !LD->isVolatile()) {
if (ISD::isNON_TRUNCStore(Chain.getNode())) {
StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
if (PrevST->getBasePtr() == Ptr &&
PrevST->getValue().getValueType() == N->getValueType(0))
return CombineTo(N, PrevST->getOperand(1), Chain);
}
}
// Try to infer better alignment information than the load already has.
if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
if (Align > LD->getMemOperand()->getBaseAlignment()) {
SDValue NewLoad = DAG.getExtLoad(
LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
LD->getPointerInfo(), LD->getMemoryVT(), Align,
LD->getMemOperand()->getFlags(), LD->getAAInfo());
if (NewLoad.getNode() != N)
return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
}
}
}
if (LD->isUnindexed()) {
// Walk up chain skipping non-aliasing memory nodes.
SDValue BetterChain = FindBetterChain(N, Chain);
// If there is a better chain.
if (Chain != BetterChain) {
SDValue ReplLoad;
// Replace the chain to void dependency.
if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
BetterChain, Ptr, LD->getMemOperand());
} else {
ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
LD->getValueType(0),
BetterChain, Ptr, LD->getMemoryVT(),
LD->getMemOperand());
}
// Create token factor to keep old chain connected.
SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
MVT::Other, Chain, ReplLoad.getValue(1));
// Make sure the new and old chains are cleaned up.
AddToWorklist(Token.getNode());
// Replace uses with load result and token factor. Don't add users
// to work list.
return CombineTo(N, ReplLoad.getValue(0), Token, false);
}
}
// Try transforming N to an indexed load.
if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
return SDValue(N, 0);
// Try to slice up N to more direct loads if the slices are mapped to
// different register banks or pairing can take place.
if (SliceUpLoad(N))
return SDValue(N, 0);
return SDValue();
}
namespace {
/// \brief Helper structure used to slice a load in smaller loads.
/// Basically a slice is obtained from the following sequence:
/// Origin = load Ty1, Base
/// Shift = srl Ty1 Origin, CstTy Amount
/// Inst = trunc Shift to Ty2
///
/// Then, it will be rewriten into:
/// Slice = load SliceTy, Base + SliceOffset
/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
///
/// SliceTy is deduced from the number of bits that are actually used to
/// build Inst.
struct LoadedSlice {
/// \brief Helper structure used to compute the cost of a slice.
struct Cost {
/// Are we optimizing for code size.
bool ForCodeSize;
/// Various cost.
unsigned Loads;
unsigned Truncates;
unsigned CrossRegisterBanksCopies;
unsigned ZExts;
unsigned Shift;
Cost(bool ForCodeSize = false)
: ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
/// \brief Get the cost of one isolated slice.
Cost(const LoadedSlice &LS, bool ForCodeSize = false)
: ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
EVT TruncType = LS.Inst->getValueType(0);
EVT LoadedType = LS.getLoadedType();
if (TruncType != LoadedType &&
!LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
ZExts = 1;
}
/// \brief Account for slicing gain in the current cost.
/// Slicing provide a few gains like removing a shift or a
/// truncate. This method allows to grow the cost of the original
/// load with the gain from this slice.
void addSliceGain(const LoadedSlice &LS) {
// Each slice saves a truncate.
const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
LS.Inst->getValueType(0)))
++Truncates;
// If there is a shift amount, this slice gets rid of it.
if (LS.Shift)
++Shift;
// If this slice can merge a cross register bank copy, account for it.
if (LS.canMergeExpensiveCrossRegisterBankCopy())
++CrossRegisterBanksCopies;
}
Cost &operator+=(const Cost &RHS) {
Loads += RHS.Loads;
Truncates += RHS.Truncates;
CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
ZExts += RHS.ZExts;
Shift += RHS.Shift;
return *this;
}
bool operator==(const Cost &RHS) const {
return Loads == RHS.Loads && Truncates == RHS.Truncates &&
CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
ZExts == RHS.ZExts && Shift == RHS.Shift;
}
bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
bool operator<(const Cost &RHS) const {
// Assume cross register banks copies are as expensive as loads.
// FIXME: Do we want some more target hooks?
unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
// Unless we are optimizing for code size, consider the
// expensive operation first.
if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
return ExpensiveOpsLHS < ExpensiveOpsRHS;
return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
(RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
}
bool operator>(const Cost &RHS) const { return RHS < *this; }
bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
};
// The last instruction that represent the slice. This should be a
// truncate instruction.
SDNode *Inst;
// The original load instruction.
LoadSDNode *Origin;
// The right shift amount in bits from the original load.
unsigned Shift;
// The DAG from which Origin came from.
// This is used to get some contextual information about legal types, etc.
SelectionDAG *DAG;
LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
unsigned Shift = 0, SelectionDAG *DAG = nullptr)
: Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
/// \brief Get the bits used in a chunk of bits \p BitWidth large.
/// \return Result is \p BitWidth and has used bits set to 1 and
/// not used bits set to 0.
APInt getUsedBits() const {
// Reproduce the trunc(lshr) sequence:
// - Start from the truncated value.
// - Zero extend to the desired bit width.
// - Shift left.
assert(Origin && "No original load to compare against.");
unsigned BitWidth = Origin->getValueSizeInBits(0);
assert(Inst && "This slice is not bound to an instruction");
assert(Inst->getValueSizeInBits(0) <= BitWidth &&
"Extracted slice is bigger than the whole type!");
APInt UsedBits(Inst->getValueSizeInBits(0), 0);
UsedBits.setAllBits();
UsedBits = UsedBits.zext(BitWidth);
UsedBits <<= Shift;
return UsedBits;
}
/// \brief Get the size of the slice to be loaded in bytes.
unsigned getLoadedSize() const {
unsigned SliceSize = getUsedBits().countPopulation();
assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
return SliceSize / 8;
}
/// \brief Get the type that will be loaded for this slice.
/// Note: This may not be the final type for the slice.
EVT getLoadedType() const {
assert(DAG && "Missing context");
LLVMContext &Ctxt = *DAG->getContext();
return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
}
/// \brief Get the alignment of the load used for this slice.
unsigned getAlignment() const {
unsigned Alignment = Origin->getAlignment();
unsigned Offset = getOffsetFromBase();
if (Offset != 0)
Alignment = MinAlign(Alignment, Alignment + Offset);
return Alignment;
}
/// \brief Check if this slice can be rewritten with legal operations.
bool isLegal() const {
// An invalid slice is not legal.
if (!Origin || !Inst || !DAG)
return false;
// Offsets are for indexed load only, we do not handle that.
if (!Origin->getOffset().isUndef())
return false;
const TargetLowering &TLI = DAG->getTargetLoweringInfo();
// Check that the type is legal.
EVT SliceType = getLoadedType();
if (!TLI.isTypeLegal(SliceType))
return false;
// Check that the load is legal for this type.
if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
return false;
// Check that the offset can be computed.
// 1. Check its type.
EVT PtrType = Origin->getBasePtr().getValueType();
if (PtrType == MVT::Untyped || PtrType.isExtended())
return false;
// 2. Check that it fits in the immediate.
if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
return false;
// 3. Check that the computation is legal.
if (!TLI.isOperationLegal(ISD::ADD, PtrType))
return false;
// Check that the zext is legal if it needs one.
EVT TruncateType = Inst->getValueType(0);
if (TruncateType != SliceType &&
!TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
return false;
return true;
}
/// \brief Get the offset in bytes of this slice in the original chunk of
/// bits.
/// \pre DAG != nullptr.
uint64_t getOffsetFromBase() const {
assert(DAG && "Missing context.");
bool IsBigEndian = DAG->getDataLayout().isBigEndian();
assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
uint64_t Offset = Shift / 8;
unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
"The size of the original loaded type is not a multiple of a"
" byte.");
// If Offset is bigger than TySizeInBytes, it means we are loading all
// zeros. This should have been optimized before in the process.
assert(TySizeInBytes > Offset &&
"Invalid shift amount for given loaded size");
if (IsBigEndian)
Offset = TySizeInBytes - Offset - getLoadedSize();
return Offset;
}
/// \brief Generate the sequence of instructions to load the slice
/// represented by this object and redirect the uses of this slice to
/// this new sequence of instructions.
/// \pre this->Inst && this->Origin are valid Instructions and this
/// object passed the legal check: LoadedSlice::isLegal returned true.
/// \return The last instruction of the sequence used to load the slice.
SDValue loadSlice() const {
assert(Inst && Origin && "Unable to replace a non-existing slice.");
const SDValue &OldBaseAddr = Origin->getBasePtr();
SDValue BaseAddr = OldBaseAddr;
// Get the offset in that chunk of bytes w.r.t. the endianness.
int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
assert(Offset >= 0 && "Offset too big to fit in int64_t!");
if (Offset) {
// BaseAddr = BaseAddr + Offset.
EVT ArithType = BaseAddr.getValueType();
SDLoc DL(Origin);
BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
DAG->getConstant(Offset, DL, ArithType));
}
// Create the type of the loaded slice according to its size.
EVT SliceType = getLoadedType();
// Create the load for the slice.
SDValue LastInst =
DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
Origin->getPointerInfo().getWithOffset(Offset),
getAlignment(), Origin->getMemOperand()->getFlags());
// If the final type is not the same as the loaded type, this means that
// we have to pad with zero. Create a zero extend for that.
EVT FinalType = Inst->getValueType(0);
if (SliceType != FinalType)
LastInst =
DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
return LastInst;
}
/// \brief Check if this slice can be merged with an expensive cross register
/// bank copy. E.g.,
/// i = load i32
/// f = bitcast i32 i to float
bool canMergeExpensiveCrossRegisterBankCopy() const {
if (!Inst || !Inst->hasOneUse())
return false;
SDNode *Use = *Inst->use_begin();
if (Use->getOpcode() != ISD::BITCAST)
return false;
assert(DAG && "Missing context");
const TargetLowering &TLI = DAG->getTargetLoweringInfo();
EVT ResVT = Use->getValueType(0);
const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
const TargetRegisterClass *ArgRC =
TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
return false;
// At this point, we know that we perform a cross-register-bank copy.
// Check if it is expensive.
const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
// Assume bitcasts are cheap, unless both register classes do not
// explicitly share a common sub class.
if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
return false;
// Check if it will be merged with the load.
// 1. Check the alignment constraint.
unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
ResVT.getTypeForEVT(*DAG->getContext()));
if (RequiredAlignment > getAlignment())
return false;
// 2. Check that the load is a legal operation for that type.
if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
return false;
// 3. Check that we do not have a zext in the way.
if (Inst->getValueType(0) != getLoadedType())
return false;
return true;
}
};
}
/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
/// \p UsedBits looks like 0..0 1..1 0..0.
static bool areUsedBitsDense(const APInt &UsedBits) {
// If all the bits are one, this is dense!
if (UsedBits.isAllOnesValue())
return true;
// Get rid of the unused bits on the right.
APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
// Get rid of the unused bits on the left.
if (NarrowedUsedBits.countLeadingZeros())
NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
// Check that the chunk of bits is completely used.
return NarrowedUsedBits.isAllOnesValue();
}
/// \brief Check whether or not \p First and \p Second are next to each other
/// in memory. This means that there is no hole between the bits loaded
/// by \p First and the bits loaded by \p Second.
static bool areSlicesNextToEachOther(const LoadedSlice &First,
const LoadedSlice &Second) {
assert(First.Origin == Second.Origin && First.Origin &&
"Unable to match different memory origins.");
APInt UsedBits = First.getUsedBits();
assert((UsedBits & Second.getUsedBits()) == 0 &&
"Slices are not supposed to overlap.");
UsedBits |= Second.getUsedBits();
return areUsedBitsDense(UsedBits);
}
/// \brief Adjust the \p GlobalLSCost according to the target
/// paring capabilities and the layout of the slices.
/// \pre \p GlobalLSCost should account for at least as many loads as
/// there is in the slices in \p LoadedSlices.
static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
LoadedSlice::Cost &GlobalLSCost) {
unsigned NumberOfSlices = LoadedSlices.size();
// If there is less than 2 elements, no pairing is possible.
if (NumberOfSlices < 2)
return;
// Sort the slices so that elements that are likely to be next to each
// other in memory are next to each other in the list.
std::sort(LoadedSlices.begin(), LoadedSlices.end(),
[](const LoadedSlice &LHS, const LoadedSlice &RHS) {
assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
});
const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
// First (resp. Second) is the first (resp. Second) potentially candidate
// to be placed in a paired load.
const LoadedSlice *First = nullptr;
const LoadedSlice *Second = nullptr;
for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
// Set the beginning of the pair.
First = Second) {
Second = &LoadedSlices[CurrSlice];
// If First is NULL, it means we start a new pair.
// Get to the next slice.
if (!First)
continue;
EVT LoadedType = First->getLoadedType();
// If the types of the slices are different, we cannot pair them.
if (LoadedType != Second->getLoadedType())
continue;
// Check if the target supplies paired loads for this type.
unsigned RequiredAlignment = 0;
if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
// move to the next pair, this type is hopeless.
Second = nullptr;
continue;
}
// Check if we meet the alignment requirement.
if (RequiredAlignment > First->getAlignment())
continue;
// Check that both loads are next to each other in memory.
if (!areSlicesNextToEachOther(*First, *Second))
continue;
assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
--GlobalLSCost.Loads;
// Move to the next pair.
Second = nullptr;
}
}
/// \brief Check the profitability of all involved LoadedSlice.
/// Currently, it is considered profitable if there is exactly two
/// involved slices (1) which are (2) next to each other in memory, and
/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
///
/// Note: The order of the elements in \p LoadedSlices may be modified, but not
/// the elements themselves.
///
/// FIXME: When the cost model will be mature enough, we can relax
/// constraints (1) and (2).
static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
const APInt &UsedBits, bool ForCodeSize) {
unsigned NumberOfSlices = LoadedSlices.size();
if (StressLoadSlicing)
return NumberOfSlices > 1;
// Check (1).
if (NumberOfSlices != 2)
return false;
// Check (2).
if (!areUsedBitsDense(UsedBits))
return false;
// Check (3).
LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
// The original code has one big load.
OrigCost.Loads = 1;
for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
const LoadedSlice &LS = LoadedSlices[CurrSlice];
// Accumulate the cost of all the slices.
LoadedSlice::Cost SliceCost(LS, ForCodeSize);
GlobalSlicingCost += SliceCost;
// Account as cost in the original configuration the gain obtained
// with the current slices.
OrigCost.addSliceGain(LS);
}
// If the target supports paired load, adjust the cost accordingly.
adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
return OrigCost > GlobalSlicingCost;
}
/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
/// operations, split it in the various pieces being extracted.
///
/// This sort of thing is introduced by SROA.
/// This slicing takes care not to insert overlapping loads.
/// \pre LI is a simple load (i.e., not an atomic or volatile load).
bool DAGCombiner::SliceUpLoad(SDNode *N) {
if (Level < AfterLegalizeDAG)
return false;
LoadSDNode *LD = cast<LoadSDNode>(N);
if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
!LD->getValueType(0).isInteger())
return false;
// Keep track of already used bits to detect overlapping values.
// In that case, we will just abort the transformation.
APInt UsedBits(LD->getValueSizeInBits(0), 0);
SmallVector<LoadedSlice, 4> LoadedSlices;
// Check if this load is used as several smaller chunks of bits.
// Basically, look for uses in trunc or trunc(lshr) and record a new chain
// of computation for each trunc.
for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
UI != UIEnd; ++UI) {
// Skip the uses of the chain.
if (UI.getUse().getResNo() != 0)
continue;
SDNode *User = *UI;
unsigned Shift = 0;
// Check if this is a trunc(lshr).
if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
isa<ConstantSDNode>(User->getOperand(1))) {
Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
User = *User->use_begin();
}
// At this point, User is a Truncate, iff we encountered, trunc or
// trunc(lshr).
if (User->getOpcode() != ISD::TRUNCATE)
return false;
// The width of the type must be a power of 2 and greater than 8-bits.
// Otherwise the load cannot be represented in LLVM IR.
// Moreover, if we shifted with a non-8-bits multiple, the slice
// will be across several bytes. We do not support that.
unsigned Width = User->getValueSizeInBits(0);
if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
return 0;
// Build the slice for this chain of computations.
LoadedSlice LS(User, LD, Shift, &DAG);
APInt CurrentUsedBits = LS.getUsedBits();
// Check if this slice overlaps with another.
if ((CurrentUsedBits & UsedBits) != 0)
return false;
// Update the bits used globally.
UsedBits |= CurrentUsedBits;
// Check if the new slice would be legal.
if (!LS.isLegal())
return false;
// Record the slice.
LoadedSlices.push_back(LS);
}
// Abort slicing if it does not seem to be profitable.
if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
return false;
++SlicedLoads;
// Rewrite each chain to use an independent load.
// By construction, each chain can be represented by a unique load.
// Prepare the argument for the new token factor for all the slices.
SmallVector<SDValue, 8> ArgChains;
for (SmallVectorImpl<LoadedSlice>::const_iterator
LSIt = LoadedSlices.begin(),
LSItEnd = LoadedSlices.end();
LSIt != LSItEnd; ++LSIt) {
SDValue SliceInst = LSIt->loadSlice();
CombineTo(LSIt->Inst, SliceInst, true);
if (SliceInst.getOpcode() != ISD::LOAD)
SliceInst = SliceInst.getOperand(0);
assert(SliceInst->getOpcode() == ISD::LOAD &&
"It takes more than a zext to get to the loaded slice!!");
ArgChains.push_back(SliceInst.getValue(1));
}
SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
ArgChains);
DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
AddToWorklist(Chain.getNode());
return true;
}
/// Check to see if V is (and load (ptr), imm), where the load is having
/// specific bytes cleared out. If so, return the byte size being masked out
/// and the shift amount.
static std::pair<unsigned, unsigned>
CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
std::pair<unsigned, unsigned> Result(0, 0);
// Check for the structure we're looking for.
if (V->getOpcode() != ISD::AND ||
!isa<ConstantSDNode>(V->getOperand(1)) ||
!ISD::isNormalLoad(V->getOperand(0).getNode()))
return Result;
// Check the chain and pointer.
LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
// The store should be chained directly to the load or be an operand of a
// tokenfactor.
if (LD == Chain.getNode())
; // ok.
else if (Chain->getOpcode() != ISD::TokenFactor)
return Result; // Fail.
else {
bool isOk = false;
for (const SDValue &ChainOp : Chain->op_values())
if (ChainOp.getNode() == LD) {
isOk = true;
break;
}
if (!isOk) return Result;
}
// This only handles simple types.
if (V.getValueType() != MVT::i16 &&
V.getValueType() != MVT::i32 &&
V.getValueType() != MVT::i64)
return Result;
// Check the constant mask. Invert it so that the bits being masked out are
// 0 and the bits being kept are 1. Use getSExtValue so that leading bits
// follow the sign bit for uniformity.
uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
unsigned NotMaskLZ = countLeadingZeros(NotMask);
if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
unsigned NotMaskTZ = countTrailingZeros(NotMask);
if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
if (NotMaskLZ == 64) return Result; // All zero mask.
// See if we have a continuous run of bits. If so, we have 0*1+0*
if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
return Result;
// Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
if (V.getValueType() != MVT::i64 && NotMaskLZ)
NotMaskLZ -= 64-V.getValueSizeInBits();
unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
switch (MaskedBytes) {
case 1:
case 2:
case 4: break;
default: return Result; // All one mask, or 5-byte mask.
}
// Verify that the first bit starts at a multiple of mask so that the access
// is aligned the same as the access width.
if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Result.first = MaskedBytes;
Result.second = NotMaskTZ/8;
return Result;
}
/// Check to see if IVal is something that provides a value as specified by
/// MaskInfo. If so, replace the specified store with a narrower store of
/// truncated IVal.
static SDNode *
ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
SDValue IVal, StoreSDNode *St,
DAGCombiner *DC) {
unsigned NumBytes = MaskInfo.first;
unsigned ByteShift = MaskInfo.second;
SelectionDAG &DAG = DC->getDAG();
// Check to see if IVal is all zeros in the part being masked in by the 'or'
// that uses this. If not, this is not a replacement.
APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
ByteShift*8, (ByteShift+NumBytes)*8);
if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
// Check that it is legal on the target to do this. It is legal if the new
// VT we're shrinking to (i8/i16/i32) is legal or we're still before type
// legalization.
MVT VT = MVT::getIntegerVT(NumBytes*8);
if (!DC->isTypeLegal(VT))
return nullptr;
// Okay, we can do this! Replace the 'St' store with a store of IVal that is
// shifted by ByteShift and truncated down to NumBytes.
if (ByteShift) {
SDLoc DL(IVal);
IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
DAG.getConstant(ByteShift*8, DL,
DC->getShiftAmountTy(IVal.getValueType())));
}
// Figure out the offset for the store and the alignment of the access.
unsigned StOffset;
unsigned NewAlign = St->getAlignment();
if (DAG.getDataLayout().isLittleEndian())
StOffset = ByteShift;
else
StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
SDValue Ptr = St->getBasePtr();
if (StOffset) {
SDLoc DL(IVal);
Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
NewAlign = MinAlign(NewAlign, StOffset);
}
// Truncate down to the new size.
IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
++OpsNarrowed;
return DAG
.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
St->getPointerInfo().getWithOffset(StOffset), NewAlign)
.getNode();
}
/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
/// narrowing the load and store if it would end up being a win for performance
/// or code size.
SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
StoreSDNode *ST = cast<StoreSDNode>(N);
if (ST->isVolatile())
return SDValue();
SDValue Chain = ST->getChain();
SDValue Value = ST->getValue();
SDValue Ptr = ST->getBasePtr();
EVT VT = Value.getValueType();
if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
return SDValue();
unsigned Opc = Value.getOpcode();
// If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
// is a byte mask indicating a consecutive number of bytes, check to see if
// Y is known to provide just those bytes. If so, we try to replace the
// load + replace + store sequence with a single (narrower) store, which makes
// the load dead.
if (Opc == ISD::OR) {
std::pair<unsigned, unsigned> MaskedLoad;
MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
if (MaskedLoad.first)
if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
Value.getOperand(1), ST,this))
return SDValue(NewST, 0);
// Or is commutative, so try swapping X and Y.
MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
if (MaskedLoad.first)
if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
Value.getOperand(0), ST,this))
return SDValue(NewST, 0);
}
if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
Value.getOperand(1).getOpcode() != ISD::Constant)
return SDValue();
SDValue N0 = Value.getOperand(0);
if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Chain == SDValue(N0.getNode(), 1)) {
LoadSDNode *LD = cast<LoadSDNode>(N0);
if (LD->getBasePtr() != Ptr ||
LD->getPointerInfo().getAddrSpace() !=
ST->getPointerInfo().getAddrSpace())
return SDValue();
// Find the type to narrow it the load / op / store to.
SDValue N1 = Value.getOperand(1);
unsigned BitWidth = N1.getValueSizeInBits();
APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
if (Opc == ISD::AND)
Imm ^= APInt::getAllOnesValue(BitWidth);
if (Imm == 0 || Imm.isAllOnesValue())
return SDValue();
unsigned ShAmt = Imm.countTrailingZeros();
unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
unsigned NewBW = NextPowerOf2(MSB - ShAmt);
EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
// The narrowing should be profitable, the load/store operation should be
// legal (or custom) and the store size should be equal to the NewVT width.
while (NewBW < BitWidth &&
(NewVT.getStoreSizeInBits() != NewBW ||
!TLI.isOperationLegalOrCustom(Opc, NewVT) ||
!TLI.isNarrowingProfitable(VT, NewVT))) {
NewBW = NextPowerOf2(NewBW);
NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
}
if (NewBW >= BitWidth)
return SDValue();
// If the lsb changed does not start at the type bitwidth boundary,
// start at the previous one.
if (ShAmt % NewBW)
ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
std::min(BitWidth, ShAmt + NewBW));
if ((Imm & Mask) == Imm) {
APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
if (Opc == ISD::AND)
NewImm ^= APInt::getAllOnesValue(NewBW);
uint64_t PtrOff = ShAmt / 8;
// For big endian targets, we need to adjust the offset to the pointer to
// load the correct bytes.
if (DAG.getDataLayout().isBigEndian())
PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
return SDValue();
SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Ptr.getValueType(), Ptr,
DAG.getConstant(PtrOff, SDLoc(LD),
Ptr.getValueType()));
SDValue NewLD =
DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
LD->getMemOperand()->getFlags(), LD->getAAInfo());
SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
DAG.getConstant(NewImm, SDLoc(Value),
NewVT));
SDValue NewST =
DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
AddToWorklist(NewPtr.getNode());
AddToWorklist(NewLD.getNode());
AddToWorklist(NewVal.getNode());
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
++OpsNarrowed;
return NewST;
}
}
return SDValue();
}
/// For a given floating point load / store pair, if the load value isn't used
/// by any other operations, then consider transforming the pair to integer
/// load / store operations if the target deems the transformation profitable.
SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
StoreSDNode *ST = cast<StoreSDNode>(N);
SDValue Chain = ST->getChain();
SDValue Value = ST->getValue();
if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
Value.hasOneUse() &&
Chain == SDValue(Value.getNode(), 1)) {
LoadSDNode *LD = cast<LoadSDNode>(Value);
EVT VT = LD->getMemoryVT();
if (!VT.isFloatingPoint() ||
VT != ST->getMemoryVT() ||
LD->isNonTemporal() ||
ST->isNonTemporal() ||
LD->getPointerInfo().getAddrSpace() != 0 ||
ST->getPointerInfo().getAddrSpace() != 0)
return SDValue();
EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
!TLI.isOperationLegal(ISD::STORE, IntVT) ||
!TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
!TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
return SDValue();
unsigned LDAlign = LD->getAlignment();
unsigned STAlign = ST->getAlignment();
Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
if (LDAlign < ABIAlign || STAlign < ABIAlign)
return SDValue();
SDValue NewLD =
DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
LD->getPointerInfo(), LDAlign);
SDValue NewST =
DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(),
ST->getPointerInfo(), STAlign);
AddToWorklist(NewLD.getNode());
AddToWorklist(NewST.getNode());
WorklistRemover DeadNodes(*this);
DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
++LdStFP2Int;
return NewST;
}
return SDValue();
}
// This is a helper function for visitMUL to check the profitability
// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
// MulNode is the original multiply, AddNode is (add x, c1),
// and ConstNode is c2.
//
// If the (add x, c1) has multiple uses, we could increase
// the number of adds if we make this transformation.
// It would only be worth doing this if we can remove a
// multiply in the process. Check for that here.
// To illustrate:
// (A + c1) * c3
// (A + c2) * c3
// We're checking for cases where we have common "c3 * A" expressions.
bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
SDValue &AddNode,
SDValue &ConstNode) {
APInt Val;
// If the add only has one use, this would be OK to do.
if (AddNode.getNode()->hasOneUse())
return true;
// Walk all the users of the constant with which we're multiplying.
for (SDNode *Use : ConstNode->uses()) {
if (Use == MulNode) // This use is the one we're on right now. Skip it.
continue;
if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
SDNode *OtherOp;
SDNode *MulVar = AddNode.getOperand(0).getNode();
// OtherOp is what we're multiplying against the constant.
if (Use->getOperand(0) == ConstNode)
OtherOp = Use->getOperand(1).getNode();
else
OtherOp = Use->getOperand(0).getNode();
// Check to see if multiply is with the same operand of our "add".
//
// ConstNode = CONST
// Use = ConstNode * A <-- visiting Use. OtherOp is A.
// ...
// AddNode = (A + c1) <-- MulVar is A.
// = AddNode * ConstNode <-- current visiting instruction.
//
// If we make this transformation, we will have a common
// multiply (ConstNode * A) that we can save.
if (OtherOp == MulVar)
return true;
// Now check to see if a future expansion will give us a common
// multiply.
//
// ConstNode = CONST
// AddNode = (A + c1)
// ... = AddNode * ConstNode <-- current visiting instruction.
// ...
// OtherOp = (A + c2)
// Use = OtherOp * ConstNode <-- visiting Use.
//
// If we make this transformation, we will have a common
// multiply (CONST * A) after we also do the same transformation
// to the "t2" instruction.
if (OtherOp->getOpcode() == ISD::ADD &&
DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
OtherOp->getOperand(0).getNode() == MulVar)
return true;
}
}
// Didn't find a case where this would be profitable.
return false;
}
bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
unsigned NumStores, bool IsConstantSrc, bool UseVector) {
// Make sure we have something to merge.
if (NumStores < 2)
return false;
int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
// The latest Node in the DAG.
SDLoc DL(StoreNodes[0].MemNode);
SDValue StoredVal;
if (UseVector) {
bool IsVec = MemVT.isVector();
unsigned Elts = NumStores;
if (IsVec) {
// When merging vector stores, get the total number of elements.
Elts *= MemVT.getVectorNumElements();
}
// Get the type for the merged vector store.
EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
if (IsConstantSrc) {
SmallVector<SDValue, 8> BuildVector;
for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
SDValue Val = St->getValue();
if (MemVT.getScalarType().isInteger())
if (auto *CFP = dyn_cast<ConstantFPSDNode>(St->getValue()))
Val = DAG.getConstant(
(uint32_t)CFP->getValueAPF().bitcastToAPInt().getZExtValue(),
SDLoc(CFP), MemVT);
BuildVector.push_back(Val);
}
StoredVal = DAG.getBuildVector(Ty, DL, BuildVector);
} else {
SmallVector<SDValue, 8> Ops;
for (unsigned i = 0; i < NumStores; ++i) {
StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
SDValue Val = St->getValue();
// All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
if (Val.getValueType() != MemVT)
return false;
Ops.push_back(Val);
}
// Build the extracted vector elements back into a vector.
StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
DL, Ty, Ops); }
} else {
// We should always use a vector store when merging extracted vector
// elements, so this path implies a store of constants.
assert(IsConstantSrc && "Merged vector elements should use vector store");
unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
APInt StoreInt(SizeInBits, 0);
// Construct a single integer constant which is made of the smaller
// constant inputs.
bool IsLE = DAG.getDataLayout().isLittleEndian();
for (unsigned i = 0; i < NumStores; ++i) {
unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
SDValue Val = St->getValue();
StoreInt <<= ElementSizeBytes * 8;
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
StoreInt |= C->getAPIntValue().zext(SizeInBits);
} else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
} else {
llvm_unreachable("Invalid constant element type");
}
}
// Create the new Load and Store operations.
EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
}
SmallVector<SDValue, 8> Chains;
// Gather all Chains we're inheriting. As generally all chains are
// equal, do minor check to remove obvious redundancies.
Chains.push_back(StoreNodes[0].MemNode->getChain());
for (unsigned i = 1; i < NumStores; ++i)
if (StoreNodes[0].MemNode->getChain() != StoreNodes[i].MemNode->getChain())
Chains.push_back(StoreNodes[i].MemNode->getChain());
LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
FirstInChain->getBasePtr(),
FirstInChain->getPointerInfo(),
FirstInChain->getAlignment());
// Replace all merged stores with the new store.
for (unsigned i = 0; i < NumStores; ++i)
CombineTo(StoreNodes[i].MemNode, NewStore);
AddToWorklist(NewChain.getNode());
return true;
}
void DAGCombiner::getStoreMergeCandidates(
StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes) {
// This holds the base pointer, index, and the offset in bytes from the base
// pointer.
BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
EVT MemVT = St->getMemoryVT();
// We must have a base and an offset.
if (!BasePtr.Base.getNode())
return;
// Do not handle stores to undef base pointers.
if (BasePtr.Base.isUndef())
return;
// We looking for a root node which is an ancestor to all mergable
// stores. We search up through a load, to our root and then down
// through all children. For instance we will find Store{1,2,3} if
// St is Store1, Store2. or Store3 where the root is not a load
// which always true for nonvolatile ops. TODO: Expand
// the search to find all valid candidates through multiple layers of loads.
//
// Root
// |-------|-------|
// Load Load Store3
// | |
// Store1 Store2
//
// FIXME: We should be able to climb and
// descend TokenFactors to find candidates as well.
SDNode *RootNode = (St->getChain()).getNode();
// Set of Parents of Candidates
std::set<SDNode *> CandidateParents;
if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
RootNode = Ldn->getChain().getNode();
for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I)
if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain
CandidateParents.insert(*I);
} else
CandidateParents.insert(RootNode);
bool IsLoadSrc = isa<LoadSDNode>(St->getValue());
bool IsConstantSrc = isa<ConstantSDNode>(St->getValue()) ||
isa<ConstantFPSDNode>(St->getValue());
bool IsExtractVecSrc =
(St->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
St->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
auto CorrectValueKind = [&](StoreSDNode *Other) -> bool {
if (IsLoadSrc)
return isa<LoadSDNode>(Other->getValue());
if (IsConstantSrc)
return (isa<ConstantSDNode>(Other->getValue()) ||
isa<ConstantFPSDNode>(Other->getValue()));
if (IsExtractVecSrc)
return (Other->getValue().getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
Other->getValue().getOpcode() == ISD::EXTRACT_SUBVECTOR);
return false;
};
// check all parents of mergable children
for (auto P = CandidateParents.begin(); P != CandidateParents.end(); ++P)
for (auto I = (*P)->use_begin(), E = (*P)->use_end(); I != E; ++I)
if (I.getOperandNo() == 0)
if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
if (OtherST->isVolatile() || OtherST->isIndexed())
continue;
// We can merge constant floats to equivalent integers
if (OtherST->getMemoryVT() != MemVT)
if (!(MemVT.isInteger() && MemVT.bitsEq(OtherST->getMemoryVT()) &&
isa<ConstantFPSDNode>(OtherST->getValue())))
continue;
BaseIndexOffset Ptr =
BaseIndexOffset::match(OtherST->getBasePtr(), DAG);
if (Ptr.equalBaseIndex(BasePtr) && CorrectValueKind(OtherST))
StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset));
}
}
// We need to check that merging these stores does not cause a loop
// in the DAG. Any store candidate may depend on another candidate
// indirectly through its operand (we already consider dependencies
// through the chain). Check in parallel by searching up from
// non-chain operands of candidates.
bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
SmallVectorImpl<MemOpLink> &StoreNodes) {
SmallPtrSet<const SDNode *, 16> Visited;
SmallVector<const SDNode *, 8> Worklist;
// search ops of store candidates
for (unsigned i = 0; i < StoreNodes.size(); ++i) {
SDNode *n = StoreNodes[i].MemNode;
// Potential loops may happen only through non-chain operands
for (unsigned j = 1; j < n->getNumOperands(); ++j)
Worklist.push_back(n->getOperand(j).getNode());
}
// search through DAG. We can stop early if we find a storenode
for (unsigned i = 0; i < StoreNodes.size(); ++i) {
if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist))
return false;
}
return true;
}
bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) {
if (OptLevel == CodeGenOpt::None)
return false;
EVT MemVT = St->getMemoryVT();
int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
return false;
bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
Attribute::NoImplicitFloat);
// This function cannot currently deal with non-byte-sized memory sizes.
if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
return false;
if (!MemVT.isSimple())
return false;
// Perform an early exit check. Do not bother looking at stored values that
// are not constants, loads, or extracted vector elements.
SDValue StoredVal = St->getValue();
bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
isa<ConstantFPSDNode>(StoredVal);
bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
return false;
// Don't merge vectors into wider vectors if the source data comes from loads.
// TODO: This restriction can be lifted by using logic similar to the
// ExtractVecSrc case.
if (MemVT.isVector() && IsLoadSrc)
return false;
SmallVector<MemOpLink, 8> StoreNodes;
// Find potential store merge candidates by searching through chain sub-DAG
getStoreMergeCandidates(St, StoreNodes);
// Check if there is anything to merge.
if (StoreNodes.size() < 2)
return false;
// Check that we can merge these candidates without causing a cycle
if (!checkMergeStoreCandidatesForDependencies(StoreNodes))
return false;
// Sort the memory operands according to their distance from the
// base pointer.
std::sort(StoreNodes.begin(), StoreNodes.end(),
[](MemOpLink LHS, MemOpLink RHS) {
return LHS.OffsetFromBase < RHS.OffsetFromBase;
});
// Scan the memory operations on the chain and find the first non-consecutive
// store memory address.
unsigned NumConsecutiveStores = 0;
int64_t StartAddress = StoreNodes[0].OffsetFromBase;
// Check that the addresses are consecutive starting from the second
// element in the list of stores.
for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
if (CurrAddress - StartAddress != (ElementSizeBytes * i))
break;
NumConsecutiveStores = i + 1;
}
if (NumConsecutiveStores < 2)
return false;
// The node with the lowest store address.
LLVMContext &Context = *DAG.getContext();
const DataLayout &DL = DAG.getDataLayout();
// Store the constants into memory as one consecutive store.
if (IsConstantSrc) {
bool RV = false;
while (NumConsecutiveStores > 1) {
LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
unsigned FirstStoreAS = FirstInChain->getAddressSpace();
unsigned FirstStoreAlign = FirstInChain->getAlignment();
unsigned LastLegalType = 0;
unsigned LastLegalVectorType = 0;
bool NonZero = false;
for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
SDValue StoredVal = ST->getValue();
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
NonZero |= !C->isNullValue();
} else if (ConstantFPSDNode *C =
dyn_cast<ConstantFPSDNode>(StoredVal)) {
NonZero |= !C->getConstantFPValue()->isNullValue();
} else {
// Non-constant.
break;
}
// Find a legal type for the constant store.
unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
bool IsFast = false;
if (TLI.isTypeLegal(StoreTy) &&
TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
FirstStoreAlign, &IsFast) &&
IsFast) {
LastLegalType = i + 1;
// Or check whether a truncstore is legal.
} else if (TLI.getTypeAction(Context, StoreTy) ==
TargetLowering::TypePromoteInteger) {
EVT LegalizedStoredValueTy =
TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
FirstStoreAS, FirstStoreAlign, &IsFast) &&
IsFast) {
LastLegalType = i + 1;
}
}
// We only use vectors if the constant is known to be zero or the target
// allows it and the function is not marked with the noimplicitfloat
// attribute.
if ((!NonZero ||
TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
!NoVectors) {
// Find a legal type for the vector store.
EVT Ty = EVT::getVectorVT(Context, MemVT, i + 1);
if (TLI.isTypeLegal(Ty) && TLI.canMergeStoresTo(Ty) &&
TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
FirstStoreAlign, &IsFast) &&
IsFast)
LastLegalVectorType = i + 1;
}
}
// Check if we found a legal integer type that creates a meaningful merge.
if (LastLegalType < 2 && LastLegalVectorType < 2)
break;
bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
bool Merged = MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
true, UseVector);
if (!Merged)
break;
// Remove merged stores for next iteration.
StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
RV = true;
NumConsecutiveStores -= NumElem;
}
return RV;
}
// When extracting multiple vector elements, try to store them
// in one vector store rather than a sequence of scalar stores.
if (IsExtractVecSrc) {
LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
unsigned FirstStoreAS = FirstInChain->getAddressSpace();
unsigned FirstStoreAlign = FirstInChain->getAlignment();
unsigned NumStoresToMerge = 0;
bool IsVec = MemVT.isVector();
for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
unsigned StoreValOpcode = St->getValue().getOpcode();
// This restriction could be loosened.
// Bail out if any stored values are not elements extracted from a vector.
// It should be possible to handle mixed sources, but load sources need
// more careful handling (see the block of code below that handles
// consecutive loads).
if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
return false;
// Find a legal type for the vector store.
unsigned Elts = i + 1;
if (IsVec) {
// When merging vector stores, get the total number of elements.
Elts *= MemVT.getVectorNumElements();
}
EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
bool IsFast;
if (TLI.isTypeLegal(Ty) &&
TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
FirstStoreAlign, &IsFast) && IsFast)
NumStoresToMerge = i + 1;
}
return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
false, true);
}
// Below we handle the case of multiple consecutive stores that
// come from multiple consecutive loads. We merge them into a single
// wide load and a single wide store.
// Look for load nodes which are used by the stored values.
SmallVector<MemOpLink, 8> LoadNodes;
// Find acceptable loads. Loads need to have the same chain (token factor),
// must not be zext, volatile, indexed, and they must be consecutive.
BaseIndexOffset LdBasePtr;
for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
if (!Ld) break;
// Loads must only have one use.
if (!Ld->hasNUsesOfValue(1, 0))
break;
// The memory operands must not be volatile.
if (Ld->isVolatile() || Ld->isIndexed())
break;
// We do not accept ext loads.
if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
break;
// The stored memory type must be the same.
if (Ld->getMemoryVT() != MemVT)
break;
BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr(), DAG);
// If this is not the first ptr that we check.
if (LdBasePtr.Base.getNode()) {
// The base ptr must be the same.
if (!LdPtr.equalBaseIndex(LdBasePtr))
break;
} else {
// Check that all other base pointers are the same as this one.
LdBasePtr = LdPtr;
}
// We found a potential memory operand to merge.
LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset));
}
if (LoadNodes.size() < 2)
return false;
// If we have load/store pair instructions and we only have two values,
// don't bother.
unsigned RequiredAlignment;
if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
St->getAlignment() >= RequiredAlignment)
return false;
LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
unsigned FirstStoreAS = FirstInChain->getAddressSpace();
unsigned FirstStoreAlign = FirstInChain->getAlignment();
LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
unsigned FirstLoadAS = FirstLoad->getAddressSpace();
unsigned FirstLoadAlign = FirstLoad->getAlignment();
// Scan the memory operations on the chain and find the first non-consecutive
// load memory address. These variables hold the index in the store node
// array.
unsigned LastConsecutiveLoad = 0;
// This variable refers to the size and not index in the array.
unsigned LastLegalVectorType = 0;
unsigned LastLegalIntegerType = 0;
StartAddress = LoadNodes[0].OffsetFromBase;
SDValue FirstChain = FirstLoad->getChain();
for (unsigned i = 1; i < LoadNodes.size(); ++i) {
// All loads must share the same chain.
if (LoadNodes[i].MemNode->getChain() != FirstChain)
break;
int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
if (CurrAddress - StartAddress != (ElementSizeBytes * i))
break;
LastConsecutiveLoad = i;
// Find a legal type for the vector store.
EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
bool IsFastSt, IsFastLd;
if (TLI.isTypeLegal(StoreTy) &&
TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
FirstStoreAlign, &IsFastSt) && IsFastSt &&
TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
FirstLoadAlign, &IsFastLd) && IsFastLd) {
LastLegalVectorType = i + 1;
}
// Find a legal type for the integer store.
unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
StoreTy = EVT::getIntegerVT(Context, SizeInBits);
if (TLI.isTypeLegal(StoreTy) &&
TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
FirstStoreAlign, &IsFastSt) && IsFastSt &&
TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
FirstLoadAlign, &IsFastLd) && IsFastLd)
LastLegalIntegerType = i + 1;
// Or check whether a truncstore and extload is legal.
else if (TLI.getTypeAction(Context, StoreTy) ==
TargetLowering::TypePromoteInteger) {
EVT LegalizedStoredValueTy =
TLI.getTypeToTransformTo(Context, StoreTy);
if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
IsFastSt &&
TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
IsFastLd)
LastLegalIntegerType = i+1;
}
}
// Only use vector types if the vector type is larger than the integer type.
// If they are the same, use integers.
bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
// We add +1 here because the LastXXX variables refer to location while
// the NumElem refers to array/index size.
unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
NumElem = std::min(LastLegalType, NumElem);
if (NumElem < 2)
return false;
// Collect the chains from all merged stores. Because the common case
// all chains are the same, check if we match the first Chain.
SmallVector<SDValue, 8> MergeStoreChains;
MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
for (unsigned i = 1; i < NumElem; ++i)
if (StoreNodes[0].MemNode->getChain() != StoreNodes[i].MemNode->getChain())
MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
// Find if it is better to use vectors or integers to load and store
// to memory.
EVT JointMemOpVT;
if (UseVectorTy) {
JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
} else {
unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
}
SDLoc LoadDL(LoadNodes[0].MemNode);
SDLoc StoreDL(StoreNodes[0].MemNode);
// The merged loads are required to have the same incoming chain, so
// using the first's chain is acceptable.
SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(),
FirstLoad->getBasePtr(),
FirstLoad->getPointerInfo(), FirstLoadAlign);
SDValue NewStoreChain =
DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
AddToWorklist(NewStoreChain.getNode());
SDValue NewStore =
DAG.getStore(NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
FirstInChain->getPointerInfo(), FirstStoreAlign);
// Transfer chain users from old loads to the new load.
for (unsigned i = 0; i < NumElem; ++i) {
LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
SDValue(NewLoad.getNode(), 1));
}
// Replace the all stores with the new store.
for (unsigned i = 0; i < NumElem; ++i)
CombineTo(StoreNodes[i].MemNode, NewStore);
return true;
}
SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
SDLoc SL(ST);
SDValue ReplStore;
// Replace the chain to avoid dependency.
if (ST->isTruncatingStore()) {
ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
ST->getBasePtr(), ST->getMemoryVT(),
ST->getMemOperand());
} else {
ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
ST->getMemOperand());
}
// Create token to keep both nodes around.
SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
MVT::Other, ST->getChain(), ReplStore);
// Make sure the new and old chains are cleaned up.
AddToWorklist(Token.getNode());
// Don't add users to work list.
return CombineTo(ST, Token, false);
}
SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
SDValue Value = ST->getValue();
if (Value.getOpcode() == ISD::TargetConstantFP)
return SDValue();
SDLoc DL(ST);
SDValue Chain = ST->getChain();
SDValue Ptr = ST->getBasePtr();
const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
// NOTE: If the original store is volatile, this transform must not increase
// the number of stores. For example, on x86-32 an f64 can be stored in one
// processor operation but an i64 (which is not legal) requires two. So the
// transform should not be done in this case.
SDValue Tmp;
switch (CFP->getSimpleValueType(0).SimpleTy) {
default:
llvm_unreachable("Unknown FP type");
case MVT::f16: // We don't do this for these yet.
case MVT::f80:
case MVT::f128:
case MVT::ppcf128:
return SDValue();
case MVT::f32:
if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
;
Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
bitcastToAPInt().getZExtValue(), SDLoc(CFP),
MVT::i32);
return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
}
return SDValue();
case MVT::f64:
if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
!ST->isVolatile()) ||
TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
;
Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
getZExtValue(), SDLoc(CFP), MVT::i64);
return DAG.getStore(Chain, DL, Tmp,
Ptr, ST->getMemOperand());
}
if (!ST->isVolatile() &&
TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
// Many FP stores are not made apparent until after legalize, e.g. for
// argument passing. Since this is so common, custom legalize the
// 64-bit integer store into two 32-bit stores.
uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
if (DAG.getDataLayout().isBigEndian())
std::swap(Lo, Hi);
unsigned Alignment = ST->getAlignment();
MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
AAMDNodes AAInfo = ST->getAAInfo();
SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
ST->getAlignment(), MMOFlags, AAInfo);
Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
DAG.getConstant(4, DL, Ptr.getValueType()));
Alignment = MinAlign(Alignment, 4U);
SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
ST->getPointerInfo().getWithOffset(4),
Alignment, MMOFlags, AAInfo);
return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
St0, St1);
}
return SDValue();
}
}
SDValue DAGCombiner::visitSTORE(SDNode *N) {
StoreSDNode *ST = cast<StoreSDNode>(N);
SDValue Chain = ST->getChain();
SDValue Value = ST->getValue();
SDValue Ptr = ST->getBasePtr();
// If this is a store of a bit convert, store the input value if the
// resultant store does not need a higher alignment than the original.
if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
ST->isUnindexed()) {
EVT SVT = Value.getOperand(0).getValueType();
if (((!LegalOperations && !ST->isVolatile()) ||
TLI.isOperationLegalOrCustom(ISD::STORE, SVT)) &&
TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) {
unsigned OrigAlign = ST->getAlignment();
bool Fast = false;
if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT,
ST->getAddressSpace(), OrigAlign, &Fast) &&
Fast) {
return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
ST->getPointerInfo(), OrigAlign,
ST->getMemOperand()->getFlags(), ST->getAAInfo());
}
}
}
// Turn 'store undef, Ptr' -> nothing.
if (Value.isUndef() && ST->isUnindexed())
return Chain;
// Try to infer better alignment information than the store already has.
if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
if (Align > ST->getAlignment()) {
SDValue NewStore =
DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
ST->getMemoryVT(), Align,
ST->getMemOperand()->getFlags(), ST->getAAInfo());
if (NewStore.getNode() != N)
return CombineTo(ST, NewStore, true);
}
}
}
// Try transforming a pair floating point load / store ops to integer
// load / store ops.
if (SDValue NewST = TransformFPLoadStorePair(N))
return NewST;
if (ST->isUnindexed()) {
// Walk up chain skipping non-aliasing memory nodes, on this store and any
// adjacent stores.
if (findBetterNeighborChains(ST)) {
// replaceStoreChain uses CombineTo, which handled all of the worklist
// manipulation. Return the original node to not do anything else.
return SDValue(ST, 0);
}
Chain = ST->getChain();
}
// Try transforming N to an indexed store.
if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
return SDValue(N, 0);
// FIXME: is there such a thing as a truncating indexed store?
if (ST->isTruncatingStore() && ST->isUnindexed() &&
Value.getValueType().isInteger()) {
// See if we can simplify the input to this truncstore with knowledge that
// only the low bits are being used. For example:
// "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
SDValue Shorter = GetDemandedBits(
Value, APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
ST->getMemoryVT().getScalarSizeInBits()));
AddToWorklist(Value.getNode());
if (Shorter.getNode())
return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Ptr, ST->getMemoryVT(), ST->getMemOperand());
// Otherwise, see if we can simplify the operation with
// SimplifyDemandedBits, which only works if the value has a single use.
if (SimplifyDemandedBits(
Value,
APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
ST->getMemoryVT().getScalarSizeInBits()))) {
// Re-visit the store if anything changed and the store hasn't been merged
// with another node (N is deleted) SimplifyDemandedBits will add Value's
// node back to the worklist if necessary, but we also need to re-visit
// the Store node itself.
if (N->getOpcode() != ISD::DELETED_NODE)
AddToWorklist(N);
return SDValue(N, 0);
}
}
// If this is a load followed by a store to the same location, then the store
// is dead/noop.
if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
ST->isUnindexed() && !ST->isVolatile() &&
// There can't be any side effects between the load and store, such as
// a call or store.
Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
// The store is dead, remove it.
return Chain;
}
}
// If this is a store followed by a store with the same value to the same
// location, then the store is dead/noop.
if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
ST1->isUnindexed() && !ST1->isVolatile()) {
// The store is dead, remove it.
return Chain;
}
}
// If this is an FP_ROUND or TRUNC followed by a store, fold this into a
// truncating store. We can do this even if this is already a truncstore.
if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
&& Value.getNode()->hasOneUse() && ST->isUnindexed() &&
TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
ST->getMemoryVT())) {
return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Ptr, ST->getMemoryVT(), ST->getMemOperand());
}
// Only perform this optimization before the types are legal, because we
// don't want to perform this optimization on every DAGCombine invocation.
if (!LegalTypes) {
for (;;) {
// There can be multiple store sequences on the same chain.
// Keep trying to merge store sequences until we are unable to do so
// or until we merge the last store on the chain.
bool Changed = MergeConsecutiveStores(ST);
if (!Changed) break;
// Return N as merge only uses CombineTo and no worklist clean
// up is necessary.
if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
return SDValue(N, 0);
}
}
// Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
//
// Make sure to do this only after attempting to merge stores in order to
// avoid changing the types of some subset of stores due to visit order,
// preventing their merging.
if (isa<ConstantFPSDNode>(ST->getValue())) {
if (SDValue NewSt = replaceStoreOfFPConstant(ST))
return NewSt;
}
if (SDValue NewSt = splitMergedValStore(ST))
return NewSt;
return ReduceLoadOpStoreWidth(N);
}
/// For the instruction sequence of store below, F and I values
/// are bundled together as an i64 value before being stored into memory.
/// Sometimes it is more efficent to generate separate stores for F and I,
/// which can remove the bitwise instructions or sink them to colder places.
///
/// (store (or (zext (bitcast F to i32) to i64),
/// (shl (zext I to i64), 32)), addr) -->
/// (store F, addr) and (store I, addr+4)
///
/// Similarly, splitting for other merged store can also be beneficial, like:
/// For pair of {i32, i32}, i64 store --> two i32 stores.
/// For pair of {i32, i16}, i64 store --> two i32 stores.
/// For pair of {i16, i16}, i32 store --> two i16 stores.
/// For pair of {i16, i8}, i32 store --> two i16 stores.
/// For pair of {i8, i8}, i16 store --> two i8 stores.
///
/// We allow each target to determine specifically which kind of splitting is
/// supported.
///
/// The store patterns are commonly seen from the simple code snippet below
/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
/// void goo(const std::pair<int, float> &);
/// hoo() {
/// ...
/// goo(std::make_pair(tmp, ftmp));
/// ...
/// }
///
SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
if (OptLevel == CodeGenOpt::None)
return SDValue();
SDValue Val = ST->getValue();
SDLoc DL(ST);
// Match OR operand.
if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
return SDValue();
// Match SHL operand and get Lower and Higher parts of Val.
SDValue Op1 = Val.getOperand(0);
SDValue Op2 = Val.getOperand(1);
SDValue Lo, Hi;
if (Op1.getOpcode() != ISD::SHL) {
std::swap(Op1, Op2);
if (Op1.getOpcode() != ISD::SHL)
return SDValue();
}
Lo = Op2;
Hi = Op1.getOperand(0);
if (!Op1.hasOneUse())
return SDValue();
// Match shift amount to HalfValBitSize.
unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
return SDValue();
// Lo and Hi are zero-extended from int with size less equal than 32
// to i64.
if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
!Lo.getOperand(0).getValueType().isScalarInteger() ||
Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
!Hi.getOperand(0).getValueType().isScalarInteger() ||
Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
return SDValue();
// Use the EVT of low and high parts before bitcast as the input
// of target query.
EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
? Lo.getOperand(0).getValueType()
: Lo.getValueType();
EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
? Hi.getOperand(0).getValueType()
: Hi.getValueType();
if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
return SDValue();
// Start to split store.
unsigned Alignment = ST->getAlignment();
MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
AAMDNodes AAInfo = ST->getAAInfo();
// Change the sizes of Lo and Hi's value types to HalfValBitSize.
EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
SDValue Chain = ST->getChain();
SDValue Ptr = ST->getBasePtr();
// Lower value store.
SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
ST->getAlignment(), MMOFlags, AAInfo);
Ptr =
DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType()));
// Higher value store.
SDValue St1 =
DAG.getStore(St0, DL, Hi, Ptr,
ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
Alignment / 2, MMOFlags, AAInfo);
return St1;
}
SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
SDValue InVec = N->getOperand(0);
SDValue InVal = N->getOperand(1);
SDValue EltNo = N->getOperand(2);
SDLoc DL(N);
// If the inserted element is an UNDEF, just use the input vector.
if (InVal.isUndef())
return InVec;
EVT VT = InVec.getValueType();
// Check that we know which element is being inserted
if (!isa<ConstantSDNode>(EltNo))
return SDValue();
unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
// Canonicalize insert_vector_elt dag nodes.
// Example:
// (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
// -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
//
// Do this only if the child insert_vector node has one use; also
// do this only if indices are both constants and Idx1 < Idx0.
if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
&& isa<ConstantSDNode>(InVec.getOperand(2))) {
unsigned OtherElt =
cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
if (Elt < OtherElt) {
// Swap nodes.
SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
InVec.getOperand(0), InVal, EltNo);
AddToWorklist(NewOp.getNode());
return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
}
}
// If we can't generate a legal BUILD_VECTOR, exit
if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
return SDValue();
// Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
// be converted to a BUILD_VECTOR). Fill in the Ops vector with the
// vector elements.
SmallVector<SDValue, 8> Ops;
// Do not combine these two vectors if the output vector will not replace
// the input vector.
if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Ops.append(InVec.getNode()->op_begin(),
InVec.getNode()->op_end());
} else if (InVec.isUndef()) {
unsigned NElts = VT.getVectorNumElements();
Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
} else {
return SDValue();
}
// Insert the element
if (Elt < Ops.size()) {
// All the operands of BUILD_VECTOR must have the same type;
// we enforce that here.
EVT OpVT = Ops[0].getValueType();
Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
}
// Return the new vector
return DAG.getBuildVector(VT, DL, Ops);
}
SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
assert(!OriginalLoad->isVolatile());
EVT ResultVT = EVE->getValueType(0);
EVT VecEltVT = InVecVT.getVectorElementType();
unsigned Align = OriginalLoad->getAlignment();
unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
VecEltVT.getTypeForEVT(*DAG.getContext()));
if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
return SDValue();
ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ?
ISD::NON_EXTLOAD : ISD::EXTLOAD;
if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
return SDValue();
Align = NewAlign;
SDValue NewPtr = OriginalLoad->getBasePtr();
SDValue Offset;
EVT PtrType = NewPtr.getValueType();
MachinePointerInfo MPI;
SDLoc DL(EVE);
if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
int Elt = ConstEltNo->getZExtValue();
unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
Offset = DAG.getConstant(PtrOff, DL, PtrType);
MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
} else {
Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
Offset = DAG.getNode(
ISD::MUL, DL, PtrType, Offset,
DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
MPI = OriginalLoad->getPointerInfo();
}
NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
// The replacement we need to do here is a little tricky: we need to
// replace an extractelement of a load with a load.
// Use ReplaceAllUsesOfValuesWith to do the replacement.
// Note that this replacement assumes that the extractvalue is the only
// use of the load; that's okay because we don't want to perform this
// transformation in other cases anyway.
SDValue Load;
SDValue Chain;
if (ResultVT.bitsGT(VecEltVT)) {
// If the result type of vextract is wider than the load, then issue an
// extending load instead.
ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
VecEltVT)
? ISD::ZEXTLOAD
: ISD::EXTLOAD;
Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
Align, OriginalLoad->getMemOperand()->getFlags(),
OriginalLoad->getAAInfo());
Chain = Load.getValue(1);
} else {
Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr,
MPI, Align, OriginalLoad->getMemOperand()->getFlags(),
OriginalLoad->getAAInfo());
Chain = Load.getValue(1);
if (ResultVT.bitsLT(VecEltVT))
Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
else
Load = DAG.getBitcast(ResultVT, Load);
}
WorklistRemover DeadNodes(*this);
SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
SDValue To[] = { Load, Chain };
DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
// Since we're explicitly calling ReplaceAllUses, add the new node to the
// worklist explicitly as well.
AddToWorklist(Load.getNode());
AddUsersToWorklist(Load.getNode()); // Add users too
// Make sure to revisit this node to clean it up; it will usually be dead.
AddToWorklist(EVE);
++OpsNarrowed;
return SDValue(EVE, 0);
}
SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
// (vextract (scalar_to_vector val, 0) -> val
SDValue InVec = N->getOperand(0);
EVT VT = InVec.getValueType();
EVT NVT = N->getValueType(0);
if (InVec.isUndef())
return DAG.getUNDEF(NVT);
if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
// Check if the result type doesn't match the inserted element type. A
// SCALAR_TO_VECTOR may truncate the inserted element and the
// EXTRACT_VECTOR_ELT may widen the extracted vector.
SDValue InOp = InVec.getOperand(0);
if (InOp.getValueType() != NVT) {
assert(InOp.getValueType().isInteger() && NVT.isInteger());
return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
}
return InOp;
}
SDValue EltNo = N->getOperand(1);
ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
// extract_vector_elt (build_vector x, y), 1 -> y
if (ConstEltNo &&
InVec.getOpcode() == ISD::BUILD_VECTOR &&
TLI.isTypeLegal(VT) &&
(InVec.hasOneUse() ||
TLI.aggressivelyPreferBuildVectorSources(VT))) {
SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
EVT InEltVT = Elt.getValueType();
// Sometimes build_vector's scalar input types do not match result type.
if (NVT == InEltVT)
return Elt;
// TODO: It may be useful to truncate if free if the build_vector implicitly
// converts.
}
// extract_vector_elt (v2i32 (bitcast i64:x)), 0 -> i32 (trunc i64:x)
if (ConstEltNo && InVec.getOpcode() == ISD::BITCAST && InVec.hasOneUse() &&
ConstEltNo->isNullValue() && VT.isInteger()) {
SDValue BCSrc = InVec.getOperand(0);
if (BCSrc.getValueType().isScalarInteger())
return DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, BCSrc);
}
// extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
//
// This only really matters if the index is non-constant since other combines
// on the constant elements already work.
if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT &&
EltNo == InVec.getOperand(2)) {
SDValue Elt = InVec.getOperand(1);
return VT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, SDLoc(N), NVT) : Elt;
}
// Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
// We only perform this optimization before the op legalization phase because
// we may introduce new vector instructions which are not backed by TD
// patterns. For example on AVX, extracting elements from a wide vector
// without using extract_subvector. However, if we can find an underlying
// scalar value, then we can always use that.
if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
int NumElem = VT.getVectorNumElements();
ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
// Find the new index to extract from.
int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
// Extracting an undef index is undef.
if (OrigElt == -1)
return DAG.getUNDEF(NVT);
// Select the right vector half to extract from.
SDValue SVInVec;
if (OrigElt < NumElem) {
SVInVec = InVec->getOperand(0);
} else {
SVInVec = InVec->getOperand(1);
OrigElt -= NumElem;
}
if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
SDValue InOp = SVInVec.getOperand(OrigElt);
if (InOp.getValueType() != NVT) {
assert(InOp.getValueType().isInteger() && NVT.isInteger());
InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
}
return InOp;
}
// FIXME: We should handle recursing on other vector shuffles and
// scalar_to_vector here as well.
if (!LegalOperations) {
EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
}
}
bool BCNumEltsChanged = false;
EVT ExtVT = VT.getVectorElementType();
EVT LVT = ExtVT;
// If the result of load has to be truncated, then it's not necessarily
// profitable.
if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
return SDValue();
if (InVec.getOpcode() == ISD::BITCAST) {
// Don't duplicate a load with other uses.
if (!InVec.hasOneUse())
return SDValue();
EVT BCVT = InVec.getOperand(0).getValueType();
if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
return SDValue();
if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
BCNumEltsChanged = true;
InVec = InVec.getOperand(0);
ExtVT = BCVT.getVectorElementType();
}
// (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
ISD::isNormalLoad(InVec.getNode()) &&
!N->getOperand(1)->hasPredecessor(InVec.getNode())) {
SDValue Index = N->getOperand(1);
if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec)) {
if (!OrigLoad->isVolatile()) {
return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
OrigLoad);
}
}
}
// Perform only after legalization to ensure build_vector / vector_shuffle
// optimizations have already been done.
if (!LegalOperations) return SDValue();
// (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
// (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
// (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
if (ConstEltNo) {
int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
LoadSDNode *LN0 = nullptr;
const ShuffleVectorSDNode *SVN = nullptr;
if (ISD::isNormalLoad(InVec.getNode())) {
LN0 = cast<LoadSDNode>(InVec);
} else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
InVec.getOperand(0).getValueType() == ExtVT &&
ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
// Don't duplicate a load with other uses.
if (!InVec.hasOneUse())
return SDValue();
LN0 = cast<LoadSDNode>(InVec.getOperand(0));
} else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
// (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
// =>
// (load $addr+1*size)
// Don't duplicate a load with other uses.
if (!InVec.hasOneUse())
return SDValue();
// If the bit convert changed the number of elements, it is unsafe
// to examine the mask.
if (BCNumEltsChanged)
return SDValue();
// Select the input vector, guarding against out of range extract vector.
unsigned NumElems = VT.getVectorNumElements();
int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
if (InVec.getOpcode() == ISD::BITCAST) {
// Don't duplicate a load with other uses.
if (!InVec.hasOneUse())
return SDValue();
InVec = InVec.getOperand(0);
}
if (ISD::isNormalLoad(InVec.getNode())) {
LN0 = cast<LoadSDNode>(InVec);
Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
}
}
// Make sure we found a non-volatile load and the extractelement is
// the only use.
if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
return SDValue();
// If Idx was -1 above, Elt is going to be -1, so just return undef.
if (Elt == -1)
return DAG.getUNDEF(LVT);
return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
}
return SDValue();
}
// Simplify (build_vec (ext )) to (bitcast (build_vec ))
SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
// We perform this optimization post type-legalization because
// the type-legalizer often scalarizes integer-promoted vectors.
// Performing this optimization before may create bit-casts which
// will be type-legalized to complex code sequences.
// We perform this optimization only before the operation legalizer because we
// may introduce illegal operations.
if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
return SDValue();
unsigned NumInScalars = N->getNumOperands();
SDLoc DL(N);
EVT VT = N->getValueType(0);
// Check to see if this is a BUILD_VECTOR of a bunch of values
// which come from any_extend or zero_extend nodes. If so, we can create
// a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
// optimizations. We do not handle sign-extend because we can't fill the sign
// using shuffles.
EVT SourceType = MVT::Other;
bool AllAnyExt = true;
for (unsigned i = 0; i != NumInScalars; ++i) {
SDValue In = N->getOperand(i);
// Ignore undef inputs.
if (In.isUndef()) continue;
bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
// Abort if the element is not an extension.
if (!ZeroExt && !AnyExt) {
SourceType = MVT::Other;
break;
}
// The input is a ZeroExt or AnyExt. Check the original type.
EVT InTy = In.getOperand(0).getValueType();
// Check that all of the widened source types are the same.
if (SourceType == MVT::Other)
// First time.
SourceType = InTy;
else if (InTy != SourceType) {
// Multiple income types. Abort.
SourceType = MVT::Other;
break;
}
// Check if all of the extends are ANY_EXTENDs.
AllAnyExt &= AnyExt;
}
// In order to have valid types, all of the inputs must be extended from the
// same source type and all of the inputs must be any or zero extend.
// Scalar sizes must be a power of two.
EVT OutScalarTy = VT.getScalarType();
bool ValidTypes = SourceType != MVT::Other &&
isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
isPowerOf2_32(SourceType.getSizeInBits());
// Create a new simpler BUILD_VECTOR sequence which other optimizations can
// turn into a single shuffle instruction.
if (!ValidTypes)
return SDValue();
bool isLE = DAG.getDataLayout().isLittleEndian();
unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
assert(ElemRatio > 1 && "Invalid element size ratio");
SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
DAG.getConstant(0, DL, SourceType);
unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
// Populate the new build_vector
for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
SDValue Cast = N->getOperand(i);
assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
Cast.getOpcode() == ISD::ZERO_EXTEND ||
Cast.isUndef()) && "Invalid cast opcode");
SDValue In;
if (Cast.isUndef())
In = DAG.getUNDEF(SourceType);
else
In = Cast->getOperand(0);
unsigned Index = isLE ? (i * ElemRatio) :
(i * ElemRatio + (ElemRatio - 1));
assert(Index < Ops.size() && "Invalid index");
Ops[Index] = In;
}
// The type of the new BUILD_VECTOR node.
EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
"Invalid vector size");
// Check if the new vector type is legal.
if (!isTypeLegal(VecVT)) return SDValue();
// Make the new BUILD_VECTOR.
SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
// The new BUILD_VECTOR node has the potential to be further optimized.
AddToWorklist(BV.getNode());
// Bitcast to the desired type.
return DAG.getBitcast(VT, BV);
}
SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
EVT VT = N->getValueType(0);
unsigned NumInScalars = N->getNumOperands();
SDLoc DL(N);
EVT SrcVT = MVT::Other;
unsigned Opcode = ISD::DELETED_NODE;
unsigned NumDefs = 0;
for (unsigned i = 0; i != NumInScalars; ++i) {
SDValue In = N->getOperand(i);
unsigned Opc = In.getOpcode();
if (Opc == ISD::UNDEF)
continue;
// If all scalar values are floats and converted from integers.
if (Opcode == ISD::DELETED_NODE &&
(Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
Opcode = Opc;
}
if (Opc != Opcode)
return SDValue();
EVT InVT = In.getOperand(0).getValueType();
// If all scalar values are typed differently, bail out. It's chosen to
// simplify BUILD_VECTOR of integer types.
if (SrcVT == MVT::Other)
SrcVT = InVT;
if (SrcVT != InVT)
return SDValue();
NumDefs++;
}
// If the vector has just one element defined, it's not worth to fold it into
// a vectorized one.
if (NumDefs < 2)
return SDValue();
assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
&& "Should only handle conversion from integer to float.");
assert(SrcVT != MVT::Other && "Cannot determine source type!");
EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
return SDValue();
// Just because the floating-point vector type is legal does not necessarily
// mean that the corresponding integer vector type is.
if (!isTypeLegal(NVT))
return SDValue();
SmallVector<SDValue, 8> Opnds;
for (unsigned i = 0; i != NumInScalars; ++i) {
SDValue In = N->getOperand(i);
if (In.isUndef())
Opnds.push_back(DAG.getUNDEF(SrcVT));
else
Opnds.push_back(In.getOperand(0));
}
SDValue BV = DAG.getBuildVector(NVT, DL, Opnds);
AddToWorklist(BV.getNode());
return DAG.getNode(Opcode, DL, VT, BV);
}
SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
ArrayRef<int> VectorMask,
SDValue VecIn1, SDValue VecIn2,
unsigned LeftIdx) {
MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy);
EVT VT = N->getValueType(0);
EVT InVT1 = VecIn1.getValueType();
EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
unsigned Vec2Offset = InVT1.getVectorNumElements();
unsigned NumElems = VT.getVectorNumElements();
unsigned ShuffleNumElems = NumElems;
// We can't generate a shuffle node with mismatched input and output types.
// Try to make the types match the type of the output.
if (InVT1 != VT || InVT2 != VT) {
if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) {
// If the output vector length is a multiple of both input lengths,
// we can concatenate them and pad the rest with undefs.
unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits();
assert(NumConcats >= 2 && "Concat needs at least two inputs!");
SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
ConcatOps[0] = VecIn1;
ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
VecIn2 = SDValue();
} else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) {
if (!TLI.isExtractSubvectorCheap(VT, NumElems))
return SDValue();
if (!VecIn2.getNode()) {
// If we only have one input vector, and it's twice the size of the
// output, split it in two.
VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
DAG.getConstant(NumElems, DL, IdxTy));
VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
// Since we now have shorter input vectors, adjust the offset of the
// second vector's start.
Vec2Offset = NumElems;
} else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) {
// VecIn1 is wider than the output, and we have another, possibly
// smaller input. Pad the smaller input with undefs, shuffle at the
// input vector width, and extract the output.
// The shuffle type is different than VT, so check legality again.
if (LegalOperations &&
!TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
return SDValue();
// Legalizing INSERT_SUBVECTOR is tricky - you basically have to
// lower it back into a BUILD_VECTOR. So if the inserted type is
// illegal, don't even try.
if (InVT1 != InVT2) {
if (!TLI.isTypeLegal(InVT2))
return SDValue();
VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
}
ShuffleNumElems = NumElems * 2;
} else {
// Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider
// than VecIn1. We can't handle this for now - this case will disappear
// when we start sorting the vectors by type.
return SDValue();
}
} else {
// TODO: Support cases where the length mismatch isn't exactly by a
// factor of 2.
// TODO: Move this check upwards, so that if we have bad type
// mismatches, we don't create any DAG nodes.
return SDValue();
}
}
// Initialize mask to undef.
SmallVector<int, 8> Mask(ShuffleNumElems, -1);
// Only need to run up to the number of elements actually used, not the
// total number of elements in the shuffle - if we are shuffling a wider
// vector, the high lanes should be set to undef.
for (unsigned i = 0; i != NumElems; ++i) {
if (VectorMask[i] <= 0)
continue;
unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
if (VectorMask[i] == (int)LeftIdx) {
Mask[i] = ExtIndex;
} else if (VectorMask[i] == (int)LeftIdx + 1) {
Mask[i] = Vec2Offset + ExtIndex;
}
}
// The type the input vectors may have changed above.
InVT1 = VecIn1.getValueType();
// If we already have a VecIn2, it should have the same type as VecIn1.
// If we don't, get an undef/zero vector of the appropriate type.
VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
if (ShuffleNumElems > NumElems)
Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
return Shuffle;
}
// Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
// operations. If the types of the vectors we're extracting from allow it,
// turn this into a vector_shuffle node.
SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
SDLoc DL(N);
EVT VT = N->getValueType(0);
// Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
if (!isTypeLegal(VT))
return SDValue();
// May only combine to shuffle after legalize if shuffle is legal.
if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
return SDValue();
bool UsesZeroVector = false;
unsigned NumElems = N->getNumOperands();
// Record, for each element of the newly built vector, which input vector
// that element comes from. -1 stands for undef, 0 for the zero vector,
// and positive values for the input vectors.
// VectorMask maps each element to its vector number, and VecIn maps vector
// numbers to their initial SDValues.
SmallVector<int, 8> VectorMask(NumElems, -1);
SmallVector<SDValue, 8> VecIn;
VecIn.push_back(SDValue());
for (unsigned i = 0; i != NumElems; ++i) {
SDValue Op = N->getOperand(i);
if (Op.isUndef())
continue;
// See if we can use a blend with a zero vector.
// TODO: Should we generalize this to a blend with an arbitrary constant
// vector?
if (isNullConstant(Op) || isNullFPConstant(Op)) {
UsesZeroVector = true;
VectorMask[i] = 0;
continue;
}
// Not an undef or zero. If the input is something other than an
// EXTRACT_VECTOR_ELT with a constant index, bail out.
if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
!isa<ConstantSDNode>(Op.getOperand(1)))
return SDValue();
SDValue ExtractedFromVec = Op.getOperand(0);
// All inputs must have the same element type as the output.
if (VT.getVectorElementType() !=
ExtractedFromVec.getValueType().getVectorElementType())
return SDValue();
// Have we seen this input vector before?
// The vectors are expected to be tiny (usually 1 or 2 elements), so using
// a map back from SDValues to numbers isn't worth it.
unsigned Idx = std::distance(
VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec));
if (Idx == VecIn.size())
VecIn.push_back(ExtractedFromVec);
VectorMask[i] = Idx;
}
// If we didn't find at least one input vector, bail out.
if (VecIn.size() < 2)
return SDValue();
// TODO: We want to sort the vectors by descending length, so that adjacent
// pairs have similar length, and the longer vector is always first in the
// pair.
// TODO: Should this fire if some of the input vectors has illegal type (like
// it does now), or should we let legalization run its course first?
// Shuffle phase:
// Take pairs of vectors, and shuffle them so that the result has elements
// from these vectors in the correct places.
// For example, given:
// t10: i32 = extract_vector_elt t1, Constant:i64<0>
// t11: i32 = extract_vector_elt t2, Constant:i64<0>
// t12: i32 = extract_vector_elt t3, Constant:i64<0>
// t13: i32 = extract_vector_elt t1, Constant:i64<1>
// t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
// We will generate:
// t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
// t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
SmallVector<SDValue, 4> Shuffles;
for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
unsigned LeftIdx = 2 * In + 1;
SDValue VecLeft = VecIn[LeftIdx];
SDValue VecRight =
(LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
VecRight, LeftIdx))
Shuffles.push_back(Shuffle);
else
return SDValue();
}
// If we need the zero vector as an "ingredient" in the blend tree, add it
// to the list of shuffles.
if (UsesZeroVector)
Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
: DAG.getConstantFP(0.0, DL, VT));
// If we only have one shuffle, we're done.
if (Shuffles.size() == 1)
return Shuffles[0];
// Update the vector mask to point to the post-shuffle vectors.
for (int &Vec : VectorMask)
if (Vec == 0)
Vec = Shuffles.size() - 1;
else
Vec = (Vec - 1) / 2;
// More than one shuffle. Generate a binary tree of blends, e.g. if from
// the previous step we got the set of shuffles t10, t11, t12, t13, we will
// generate:
// t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
// t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
// t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
// t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
// t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
// t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
// t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
// Make sure the initial size of the shuffle list is even.
if (Shuffles.size() % 2)
Shuffles.push_back(DAG.getUNDEF(VT));
for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
if (CurSize % 2) {
Shuffles[CurSize] = DAG.getUNDEF(VT);
CurSize++;
}
for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
int Left = 2 * In;
int Right = 2 * In + 1;
SmallVector<int, 8> Mask(NumElems, -1);
for (unsigned i = 0; i != NumElems; ++i) {
if (VectorMask[i] == Left) {
Mask[i] = i;
VectorMask[i] = In;
} else if (VectorMask[i] == Right) {
Mask[i] = i + NumElems;
VectorMask[i] = In;
}
}
Shuffles[In] =
DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
}
}
return Shuffles[0];
}
SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
EVT VT = N->getValueType(0);
// A vector built entirely of undefs is undef.
if (ISD::allOperandsUndef(N))
return DAG.getUNDEF(VT);
// Check if we can express BUILD VECTOR via subvector extract.
if (!LegalTypes && (N->getNumOperands() > 1)) {
SDValue Op0 = N->getOperand(0);
auto checkElem = [&](SDValue Op) -> uint64_t {
if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
(Op0.getOperand(0) == Op.getOperand(0)))
if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
return CNode->getZExtValue();
return -1;
};
int Offset = checkElem(Op0);
for (unsigned i = 0; i < N->getNumOperands(); ++i) {
if (Offset + i != checkElem(N->getOperand(i))) {
Offset = -1;
break;
}
}
if ((Offset == 0) &&
(Op0.getOperand(0).getValueType() == N->getValueType(0)))
return Op0.getOperand(0);
if ((Offset != -1) &&
((Offset % N->getValueType(0).getVectorNumElements()) ==
0)) // IDX must be multiple of output size.
return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
Op0.getOperand(0), Op0.getOperand(1));
}
if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
return V;
if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
return V;
if (SDValue V = reduceBuildVecToShuffle(N))
return V;
return SDValue();
}
static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
EVT OpVT = N->getOperand(0).getValueType();
// If the operands are legal vectors, leave them alone.
if (TLI.isTypeLegal(OpVT))
return SDValue();
SDLoc DL(N);
EVT VT = N->getValueType(0);
SmallVector<SDValue, 8> Ops;
EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
// Keep track of what we encounter.
bool AnyInteger = false;
bool AnyFP = false;
for (const SDValue &Op : N->ops()) {
if (ISD::BITCAST == Op.getOpcode() &&
!Op.getOperand(0).getValueType().isVector())
Ops.push_back(Op.getOperand(0));
else if (ISD::UNDEF == Op.getOpcode())
Ops.push_back(ScalarUndef);
else
return SDValue();
// Note whether we encounter an integer or floating point scalar.
// If it's neither, bail out, it could be something weird like x86mmx.
EVT LastOpVT = Ops.back().getValueType();
if (LastOpVT.isFloatingPoint())
AnyFP = true;
else if (LastOpVT.isInteger())
AnyInteger = true;
else
return SDValue();
}
// If any of the operands is a floating point scalar bitcast to a vector,
// use floating point types throughout, and bitcast everything.
// Replace UNDEFs by another scalar UNDEF node, of the final desired type.
if (AnyFP) {
SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
if (AnyInteger) {
for (SDValue &Op : Ops) {
if (Op.getValueType() == SVT)
continue;
if (Op.isUndef())
Op = ScalarUndef;
else
Op = DAG.getBitcast(SVT, Op);
}
}
}
EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
VT.getSizeInBits() / SVT.getSizeInBits());
return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
}
// Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
// operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
// most two distinct vectors the same size as the result, attempt to turn this
// into a legal shuffle.
static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
EVT VT = N->getValueType(0);
EVT OpVT = N->getOperand(0).getValueType();
int NumElts = VT.getVectorNumElements();
int NumOpElts = OpVT.getVectorNumElements();
SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
SmallVector<int, 8> Mask;
for (SDValue Op : N->ops()) {
// Peek through any bitcast.
while (Op.getOpcode() == ISD::BITCAST)
Op = Op.getOperand(0);
// UNDEF nodes convert to UNDEF shuffle mask values.
if (Op.isUndef()) {
Mask.append((unsigned)NumOpElts, -1);
continue;
}
if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
return SDValue();
// What vector are we extracting the subvector from and at what index?
SDValue ExtVec = Op.getOperand(0);
// We want the EVT of the original extraction to correctly scale the
// extraction index.
EVT ExtVT = ExtVec.getValueType();
// Peek through any bitcast.
while (ExtVec.getOpcode() == ISD::BITCAST)
ExtVec = ExtVec.getOperand(0);
// UNDEF nodes convert to UNDEF shuffle mask values.
if (ExtVec.isUndef()) {
Mask.append((unsigned)NumOpElts, -1);
continue;
}
if (!isa<ConstantSDNode>(Op.getOperand(1)))
return SDValue();
int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
// Ensure that we are extracting a subvector from a vector the same
// size as the result.
if (ExtVT.getSizeInBits() != VT.getSizeInBits())
return SDValue();
// Scale the subvector index to account for any bitcast.
int NumExtElts = ExtVT.getVectorNumElements();
if (0 == (NumExtElts % NumElts))
ExtIdx /= (NumExtElts / NumElts);
else if (0 == (NumElts % NumExtElts))
ExtIdx *= (NumElts / NumExtElts);
else
return SDValue();
// At most we can reference 2 inputs in the final shuffle.
if (SV0.isUndef() || SV0 == ExtVec) {
SV0 = ExtVec;
for (int i = 0; i != NumOpElts; ++i)
Mask.push_back(i + ExtIdx);
} else if (SV1.isUndef() || SV1 == ExtVec) {
SV1 = ExtVec;
for (int i = 0; i != NumOpElts; ++i)
Mask.push_back(i + ExtIdx + NumElts);
} else {
return SDValue();
}
}
if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
return SDValue();
return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
DAG.getBitcast(VT, SV1), Mask);
}
SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
// If we only have one input vector, we don't need to do any concatenation.
if (N->getNumOperands() == 1)
return N->getOperand(0);
// Check if all of the operands are undefs.
EVT VT = N->getValueType(0);
if (ISD::allOperandsUndef(N))
return DAG.getUNDEF(VT);
// Optimize concat_vectors where all but the first of the vectors are undef.
if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
return Op.isUndef();
})) {
SDValue In = N->getOperand(0);
assert(In.getValueType().isVector() && "Must concat vectors");
// Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
if (In->getOpcode() == ISD::BITCAST &&
!In->getOperand(0)->getValueType(0).isVector()) {
SDValue Scalar = In->getOperand(0);
// If the bitcast type isn't legal, it might be a trunc of a legal type;
// look through the trunc so we can still do the transform:
// concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
if (Scalar->getOpcode() == ISD::TRUNCATE &&
!TLI.isTypeLegal(Scalar.getValueType()) &&
TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
Scalar = Scalar->getOperand(0);
EVT SclTy = Scalar->getValueType(0);
if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
return SDValue();
unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
if (VNTNumElms < 2)
return SDValue();
EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
return SDValue();
SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
return DAG.getBitcast(VT, Res);
}
}
// Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
// We have already tested above for an UNDEF only concatenation.
// fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
// -> (BUILD_VECTOR A, B, ..., C, D, ...)
auto IsBuildVectorOrUndef = [](const SDValue &Op) {
return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
};
if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
SmallVector<SDValue, 8> Opnds;
EVT SVT = VT.getScalarType();
EVT MinVT = SVT;
if (!SVT.isFloatingPoint()) {
// If BUILD_VECTOR are from built from integer, they may have different
// operand types. Get the smallest type and truncate all operands to it.
bool FoundMinVT = false;
for (const SDValue &Op : N->ops())
if (ISD::BUILD_VECTOR == Op.getOpcode()) {
EVT OpSVT = Op.getOperand(0)->getValueType(0);
MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
FoundMinVT = true;
}
assert(FoundMinVT && "Concat vector type mismatch");
}
for (const SDValue &Op : N->ops()) {
EVT OpVT = Op.getValueType();
unsigned NumElts = OpVT.getVectorNumElements();
if (ISD::UNDEF == Op.getOpcode())
Opnds.append(NumElts, DAG.getUNDEF(MinVT));
if (ISD::BUILD_VECTOR == Op.getOpcode()) {
if (SVT.isFloatingPoint()) {
assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
} else {
for (unsigned i = 0; i != NumElts; ++i)
Opnds.push_back(
DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
}
}
}
assert(VT.getVectorNumElements() == Opnds.size() &&
"Concat vector type mismatch");
return DAG.getBuildVector(VT, SDLoc(N), Opnds);
}
// Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
if (SDValue V = combineConcatVectorOfScalars(N, DAG))
return V;
// Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
return V;
// Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
// nodes often generate nop CONCAT_VECTOR nodes.
// Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
// place the incoming vectors at the exact same location.
SDValue SingleSource = SDValue();
unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
SDValue Op = N->getOperand(i);
if (Op.isUndef())
continue;
// Check if this is the identity extract:
if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
return SDValue();
// Find the single incoming vector for the extract_subvector.
if (SingleSource.getNode()) {
if (Op.getOperand(0) != SingleSource)
return SDValue();
} else {
SingleSource = Op.getOperand(0);
// Check the source type is the same as the type of the result.
// If not, this concat may extend the vector, so we can not
// optimize it away.
if (SingleSource.getValueType() != N->getValueType(0))
return SDValue();
}
unsigned IdentityIndex = i * PartNumElem;
ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
// The extract index must be constant.
if (!CS)
return SDValue();
// Check that we are reading from the identity index.
if (CS->getZExtValue() != IdentityIndex)
return SDValue();
}
if (SingleSource.getNode())
return SingleSource;
return SDValue();
}
SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
EVT NVT = N->getValueType(0);
SDValue V = N->getOperand(0);
// Extract from UNDEF is UNDEF.
if (V.isUndef())
return DAG.getUNDEF(NVT);
// Combine:
// (extract_subvec (concat V1, V2, ...), i)
// Into:
// Vi if possible
// Only operand 0 is checked as 'concat' assumes all inputs of the same
// type.
if (V->getOpcode() == ISD::CONCAT_VECTORS &&
isa<ConstantSDNode>(N->getOperand(1)) &&
V->getOperand(0).getValueType() == NVT) {
unsigned Idx = N->getConstantOperandVal(1);
unsigned NumElems = NVT.getVectorNumElements();
assert((Idx % NumElems) == 0 &&
"IDX in concat is not a multiple of the result vector length.");
return V->getOperand(Idx / NumElems);
}
// Skip bitcasting
if (V->getOpcode() == ISD::BITCAST)
V = V.getOperand(0);
if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
// Handle only simple case where vector being inserted and vector
// being extracted are of same size.
EVT SmallVT = V->getOperand(1).getValueType();
if (!NVT.bitsEq(SmallVT))
return SDValue();
// Only handle cases where both indexes are constants.
ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
if (InsIdx && ExtIdx) {
// Combine:
// (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
// Into:
// indices are equal or bit offsets are equal => V1
// otherwise => (extract_subvec V1, ExtIdx)
if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() ==
ExtIdx->getZExtValue() * NVT.getScalarSizeInBits())
return DAG.getBitcast(NVT, V->getOperand(1));
return DAG.getNode(
ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
DAG.getBitcast(N->getOperand(0).getValueType(), V->getOperand(0)),
N->getOperand(1));
}
}
return SDValue();
}
static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
SDValue V, SelectionDAG &DAG) {
SDLoc DL(V);
EVT VT = V.getValueType();
switch (V.getOpcode()) {
default:
return V;
case ISD::CONCAT_VECTORS: {
EVT OpVT = V->getOperand(0).getValueType();
int OpSize = OpVT.getVectorNumElements();
SmallBitVector OpUsedElements(OpSize, false);
bool FoundSimplification = false;
SmallVector<SDValue, 4> NewOps;
NewOps.reserve(V->getNumOperands());
for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
SDValue Op = V->getOperand(i);
bool OpUsed = false;
for (int j = 0; j < OpSize; ++j)
if (UsedElements[i * OpSize + j]) {
OpUsedElements[j] = true;
OpUsed = true;
}
NewOps.push_back(
OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
: DAG.getUNDEF(OpVT));
FoundSimplification |= Op == NewOps.back();
OpUsedElements.reset();
}
if (FoundSimplification)
V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
return V;
}
case ISD::INSERT_SUBVECTOR: {
SDValue BaseV = V->getOperand(0);
SDValue SubV = V->getOperand(1);
auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
if (!IdxN)
return V;
int SubSize = SubV.getValueType().getVectorNumElements();
int Idx = IdxN->getZExtValue();
bool SubVectorUsed = false;
SmallBitVector SubUsedElements(SubSize, false);
for (int i = 0; i < SubSize; ++i)
if (UsedElements[i + Idx]) {
SubVectorUsed = true;
SubUsedElements[i] = true;
UsedElements[i + Idx] = false;
}
// Now recurse on both the base and sub vectors.
SDValue SimplifiedSubV =
SubVectorUsed
? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
: DAG.getUNDEF(SubV.getValueType());
SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
return V;
}
}
}
static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
SDValue N1, SelectionDAG &DAG) {
EVT VT = SVN->getValueType(0);
int NumElts = VT.getVectorNumElements();
SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
for (int M : SVN->getMask())
if (M >= 0 && M < NumElts)
N0UsedElements[M] = true;
else if (M >= NumElts)
N1UsedElements[M - NumElts] = true;
SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
if (S0 == N0 && S1 == N1)
return SDValue();
return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
}
// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
// or turn a shuffle of a single concat into simpler shuffle then concat.
static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
EVT VT = N->getValueType(0);
unsigned NumElts = VT.getVectorNumElements();
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
SmallVector<SDValue, 4> Ops;
EVT ConcatVT = N0.getOperand(0).getValueType();
unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
unsigned NumConcats = NumElts / NumElemsPerConcat;
// Special case: shuffle(concat(A,B)) can be more efficiently represented
// as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
// half vector elements.
if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
SVN->getMask().end(), [](int i) { return i == -1; })) {
N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
N1 = DAG.getUNDEF(ConcatVT);
return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
}
// Look at every vector that's inserted. We're looking for exact
// subvector-sized copies from a concatenated vector
for (unsigned I = 0; I != NumConcats; ++I) {
// Make sure we're dealing with a copy.
unsigned Begin = I * NumElemsPerConcat;
bool AllUndef = true, NoUndef = true;
for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
if (SVN->getMaskElt(J) >= 0)
AllUndef = false;
else
NoUndef = false;
}
if (NoUndef) {
if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
return SDValue();
for (unsigned J = 1; J != NumElemsPerConcat; ++J)
if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
return SDValue();
unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
if (FirstElt < N0.getNumOperands())
Ops.push_back(N0.getOperand(FirstElt));
else
Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
} else if (AllUndef) {
Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
} else { // Mixed with general masks and undefs, can't do optimization.
return SDValue();
}
}
return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
}
// Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
// BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
//
// SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
// a simplification in some sense, but it isn't appropriate in general: some
// BUILD_VECTORs are substantially cheaper than others. The general case
// of a BUILD_VECTOR requires inserting each element individually (or
// performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
// all constants is a single constant pool load. A BUILD_VECTOR where each
// element is identical is a splat. A BUILD_VECTOR where most of the operands
// are undef lowers to a small number of element insertions.
//
// To deal with this, we currently use a bunch of mostly arbitrary heuristics.
// We don't fold shuffles where one side is a non-zero constant, and we don't
// fold shuffles if the resulting BUILD_VECTOR would have duplicate
// non-constant operands. This seems to work out reasonably well in practice.
static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
SelectionDAG &DAG,
const TargetLowering &TLI) {
EVT VT = SVN->getValueType(0);
unsigned NumElts = VT.getVectorNumElements();
SDValue N0 = SVN->getOperand(0);
SDValue N1 = SVN->getOperand(1);
if (!N0->hasOneUse() || !N1->hasOneUse())
return SDValue();
// If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
// discussed above.
if (!N1.isUndef()) {
bool N0AnyConst = isAnyConstantBuildVector(N0.getNode());
bool N1AnyConst = isAnyConstantBuildVector(N1.getNode());
if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
return SDValue();
if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
return SDValue();
}
SmallVector<SDValue, 8> Ops;
SmallSet<SDValue, 16> DuplicateOps;
for (int M : SVN->getMask()) {
SDValue Op = DAG.getUNDEF(VT.getScalarType());
if (M >= 0) {
int Idx = M < (int)NumElts ? M : M - NumElts;
SDValue &S = (M < (int)NumElts ? N0 : N1);
if (S.getOpcode() == ISD::BUILD_VECTOR) {
Op = S.getOperand(Idx);
} else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
if (Idx == 0)
Op = S.getOperand(0);
} else {
// Operand can't be combined - bail out.
return SDValue();
}
}
// Don't duplicate a non-constant BUILD_VECTOR operand; semantically, this is
// fine, but it's likely to generate low-quality code if the target can't
// reconstruct an appropriate shuffle.
if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op))
if (!DuplicateOps.insert(Op).second)
return SDValue();
Ops.push_back(Op);
}
// BUILD_VECTOR requires all inputs to be of the same type, find the
// maximum type and extend them all.
EVT SVT = VT.getScalarType();
if (SVT.isInteger())
for (SDValue &Op : Ops)
SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
if (SVT != VT.getScalarType())
for (SDValue &Op : Ops)
Op = TLI.isZExtFree(Op.getValueType(), SVT)
? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
: DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
}
// Match shuffles that can be converted to any_vector_extend_in_reg.
// This is often generated during legalization.
// e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
// TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
SelectionDAG &DAG,
const TargetLowering &TLI,
bool LegalOperations) {
EVT VT = SVN->getValueType(0);
bool IsBigEndian = DAG.getDataLayout().isBigEndian();
// TODO Add support for big-endian when we have a test case.
if (!VT.isInteger() || IsBigEndian)
return SDValue();
unsigned NumElts = VT.getVectorNumElements();
unsigned EltSizeInBits = VT.getScalarSizeInBits();
ArrayRef<int> Mask = SVN->getMask();
SDValue N0 = SVN->getOperand(0);
// shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
for (unsigned i = 0; i != NumElts; ++i) {
if (Mask[i] < 0)
continue;
if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
continue;
return false;
}
return true;
};
// Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
// power-of-2 extensions as they are the most likely.
for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
if (!isAnyExtend(Scale))
continue;
EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
if (!LegalOperations ||
TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
return DAG.getBitcast(VT,
DAG.getAnyExtendVectorInReg(N0, SDLoc(SVN), OutVT));
}
return SDValue();
}
// Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
// each source element of a large type into the lowest elements of a smaller
// destination type. This is often generated during legalization.
// If the source node itself was a '*_extend_vector_inreg' node then we should
// then be able to remove it.
SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, SelectionDAG &DAG) {
EVT VT = SVN->getValueType(0);
bool IsBigEndian = DAG.getDataLayout().isBigEndian();
// TODO Add support for big-endian when we have a test case.
if (!VT.isInteger() || IsBigEndian)
return SDValue();
SDValue N0 = SVN->getOperand(0);
while (N0.getOpcode() == ISD::BITCAST)
N0 = N0.getOperand(0);
unsigned Opcode = N0.getOpcode();
if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
return SDValue();
SDValue N00 = N0.getOperand(0);
ArrayRef<int> Mask = SVN->getMask();
unsigned NumElts = VT.getVectorNumElements();
unsigned EltSizeInBits = VT.getScalarSizeInBits();
unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
// (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
// (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
// (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
for (unsigned i = 0; i != NumElts; ++i) {
if (Mask[i] < 0)
continue;
if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
continue;
return false;
}
return true;
};
// At the moment we just handle the case where we've truncated back to the
// same size as before the extension.
// TODO: handle more extension/truncation cases as cases arise.
if (EltSizeInBits != ExtSrcSizeInBits)
return SDValue();
// Attempt to match a 'truncate_vector_inreg' shuffle, we just search for
// power-of-2 truncations as they are the most likely.
for (unsigned Scale = 2; Scale < NumElts; Scale *= 2)
if (isTruncate(Scale))
return DAG.getBitcast(VT, N00);
return SDValue();
}
SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
EVT VT = N->getValueType(0);
unsigned NumElts = VT.getVectorNumElements();
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
// Canonicalize shuffle undef, undef -> undef
if (N0.isUndef() && N1.isUndef())
return DAG.getUNDEF(VT);
ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
// Canonicalize shuffle v, v -> v, undef
if (N0 == N1) {
SmallVector<int, 8> NewMask;
for (unsigned i = 0; i != NumElts; ++i) {
int Idx = SVN->getMaskElt(i);
if (Idx >= (int)NumElts) Idx -= NumElts;
NewMask.push_back(Idx);
}
return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask);
}
// Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
if (N0.isUndef())
return DAG.getCommutedVectorShuffle(*SVN);
// Remove references to rhs if it is undef
if (N1.isUndef()) {
bool Changed = false;
SmallVector<int, 8> NewMask;
for (unsigned i = 0; i != NumElts; ++i) {
int Idx = SVN->getMaskElt(i);
if (Idx >= (int)NumElts) {
Idx = -1;
Changed = true;
}
NewMask.push_back(Idx);
}
if (Changed)
return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
}
// If it is a splat, check if the argument vector is another splat or a
// build_vector.
if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
SDNode *V = N0.getNode();
// If this is a bit convert that changes the element type of the vector but
// not the number of vector elements, look through it. Be careful not to
// look though conversions that change things like v4f32 to v2f64.
if (V->getOpcode() == ISD::BITCAST) {
SDValue ConvInput = V->getOperand(0);
if (ConvInput.getValueType().isVector() &&
ConvInput.getValueType().getVectorNumElements() == NumElts)
V = ConvInput.getNode();
}
if (V->getOpcode() == ISD::BUILD_VECTOR) {
assert(V->getNumOperands() == NumElts &&
"BUILD_VECTOR has wrong number of operands");
SDValue Base;
bool AllSame = true;
for (unsigned i = 0; i != NumElts; ++i) {
if (!V->getOperand(i).isUndef()) {
Base = V->getOperand(i);
break;
}
}
// Splat of <u, u, u, u>, return <u, u, u, u>
if (!Base.getNode())
return N0;
for (unsigned i = 0; i != NumElts; ++i) {
if (V->getOperand(i) != Base) {
AllSame = false;
break;
}
}
// Splat of <x, x, x, x>, return <x, x, x, x>
if (AllSame)
return N0;
// Canonicalize any other splat as a build_vector.
const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
SmallVector<SDValue, 8> Ops(NumElts, Splatted);
SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
// We may have jumped through bitcasts, so the type of the
// BUILD_VECTOR may not match the type of the shuffle.
if (V->getValueType(0) != VT)
NewBV = DAG.getBitcast(VT, NewBV);
return NewBV;
}
}
// There are various patterns used to build up a vector from smaller vectors,
// subvectors, or elements. Scan chains of these and replace unused insertions
// or components with undef.
if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
return S;
// Match shuffles that can be converted to any_vector_extend_in_reg.
if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
return V;
// Combine "truncate_vector_in_reg" style shuffles.
if (SDValue V = combineTruncationShuffle(SVN, DAG))
return V;
if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
Level < AfterLegalizeVectorOps &&
(N1.isUndef() ||
(N1.getOpcode() == ISD::CONCAT_VECTORS &&
N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
if (SDValue V = partitionShuffleOfConcats(N, DAG))
return V;
}
// Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
// BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
return Res;
// If this shuffle only has a single input that is a bitcasted shuffle,
// attempt to merge the 2 shuffles and suitably bitcast the inputs/output
// back to their original types.
if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
N1.isUndef() && Level < AfterLegalizeVectorOps &&
TLI.isTypeLegal(VT)) {
// Peek through the bitcast only if there is one user.
SDValue BC0 = N0;
while (BC0.getOpcode() == ISD::BITCAST) {
if (!BC0.hasOneUse())
break;
BC0 = BC0.getOperand(0);
}
auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
if (Scale == 1)
return SmallVector<int, 8>(Mask.begin(), Mask.end());
SmallVector<int, 8> NewMask;
for (int M : Mask)
for (int s = 0; s != Scale; ++s)
NewMask.push_back(M < 0 ? -1 : Scale * M + s);
return NewMask;
};
if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
EVT SVT = VT.getScalarType();
EVT InnerVT = BC0->getValueType(0);
EVT InnerSVT = InnerVT.getScalarType();
// Determine which shuffle works with the smaller scalar type.
EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
EVT ScaleSVT = ScaleVT.getScalarType();
if (TLI.isTypeLegal(ScaleVT) &&
0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
// Scale the shuffle masks to the smaller scalar type.
ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
SmallVector<int, 8> InnerMask =
ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
SmallVector<int, 8> OuterMask =
ScaleShuffleMask(SVN->getMask(), OuterScale);
// Merge the shuffle masks.
SmallVector<int, 8> NewMask;
for (int M : OuterMask)
NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
// Test for shuffle mask legality over both commutations.
SDValue SV0 = BC0->getOperand(0);
SDValue SV1 = BC0->getOperand(1);
bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
if (!LegalMask) {
std::swap(SV0, SV1);
ShuffleVectorSDNode::commuteMask(NewMask);
LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
}
if (LegalMask) {
SV0 = DAG.getBitcast(ScaleVT, SV0);
SV1 = DAG.getBitcast(ScaleVT, SV1);
return DAG.getBitcast(
VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
}
}
}
}
// Canonicalize shuffles according to rules:
// shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
// shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
// shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
TLI.isTypeLegal(VT)) {
// The incoming shuffle must be of the same type as the result of the
// current shuffle.
assert(N1->getOperand(0).getValueType() == VT &&
"Shuffle types don't match");
SDValue SV0 = N1->getOperand(0);
SDValue SV1 = N1->getOperand(1);
bool HasSameOp0 = N0 == SV0;
bool IsSV1Undef = SV1.isUndef();
if (HasSameOp0 || IsSV1Undef || N0 == SV1)
// Commute the operands of this shuffle so that next rule
// will trigger.
return DAG.getCommutedVectorShuffle(*SVN);
}
// Try to fold according to rules:
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
// Don't try to fold shuffles with illegal type.
// Only fold if this shuffle is the only user of the other shuffle.
if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
// Don't try to fold splats; they're likely to simplify somehow, or they
// might be free.
if (OtherSV->isSplat())
return SDValue();
// The incoming shuffle must be of the same type as the result of the
// current shuffle.
assert(OtherSV->getOperand(0).getValueType() == VT &&
"Shuffle types don't match");
SDValue SV0, SV1;
SmallVector<int, 4> Mask;
// Compute the combined shuffle mask for a shuffle with SV0 as the first
// operand, and SV1 as the second operand.
for (unsigned i = 0; i != NumElts; ++i) {
int Idx = SVN->getMaskElt(i);
if (Idx < 0) {
// Propagate Undef.
Mask.push_back(Idx);
continue;
}
SDValue CurrentVec;
if (Idx < (int)NumElts) {
// This shuffle index refers to the inner shuffle N0. Lookup the inner
// shuffle mask to identify which vector is actually referenced.
Idx = OtherSV->getMaskElt(Idx);
if (Idx < 0) {
// Propagate Undef.
Mask.push_back(Idx);
continue;
}
CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
: OtherSV->getOperand(1);
} else {
// This shuffle index references an element within N1.
CurrentVec = N1;
}
// Simple case where 'CurrentVec' is UNDEF.
if (CurrentVec.isUndef()) {
Mask.push_back(-1);
continue;
}
// Canonicalize the shuffle index. We don't know yet if CurrentVec
// will be the first or second operand of the combined shuffle.
Idx = Idx % NumElts;
if (!SV0.getNode() || SV0 == CurrentVec) {
// Ok. CurrentVec is the left hand side.
// Update the mask accordingly.
SV0 = CurrentVec;
Mask.push_back(Idx);
continue;
}
// Bail out if we cannot convert the shuffle pair into a single shuffle.
if (SV1.getNode() && SV1 != CurrentVec)
return SDValue();
// Ok. CurrentVec is the right hand side.
// Update the mask accordingly.
SV1 = CurrentVec;
Mask.push_back(Idx + NumElts);
}
// Check if all indices in Mask are Undef. In case, propagate Undef.
bool isUndefMask = true;
for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
isUndefMask &= Mask[i] < 0;
if (isUndefMask)
return DAG.getUNDEF(VT);
if (!SV0.getNode())
SV0 = DAG.getUNDEF(VT);
if (!SV1.getNode())
SV1 = DAG.getUNDEF(VT);
// Avoid introducing shuffles with illegal mask.
if (!TLI.isShuffleMaskLegal(Mask, VT)) {
ShuffleVectorSDNode::commuteMask(Mask);
if (!TLI.isShuffleMaskLegal(Mask, VT))
return SDValue();
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
std::swap(SV0, SV1);
}
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
// shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask);
}
return SDValue();
}
SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
SDValue InVal = N->getOperand(0);
EVT VT = N->getValueType(0);
// Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
// with a VECTOR_SHUFFLE.
if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
SDValue InVec = InVal->getOperand(0);
SDValue EltNo = InVal->getOperand(1);
// FIXME: We could support implicit truncation if the shuffle can be
// scaled to a smaller vector scalar type.
ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
if (C0 && VT == InVec.getValueType() &&
VT.getScalarType() == InVal.getValueType()) {
SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
int Elt = C0->getZExtValue();
NewMask[0] = Elt;
if (TLI.isShuffleMaskLegal(NewMask, VT))
return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
NewMask);
}
}
return SDValue();
}
SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
EVT VT = N->getValueType(0);
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
SDValue N2 = N->getOperand(2);
// If inserting an UNDEF, just return the original vector.
if (N1.isUndef())
return N0;
// If this is an insert of an extracted vector into an undef vector, we can
// just use the input to the extract.
if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
return N1.getOperand(0);
// Combine INSERT_SUBVECTORs where we are inserting to the same index.
// INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
// --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
N0.getOperand(1).getValueType() == N1.getValueType() &&
N0.getOperand(2) == N2)
return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
N1, N2);
if (!isa<ConstantSDNode>(N2))
return SDValue();
unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue();
// Canonicalize insert_subvector dag nodes.
// Example:
// (insert_subvector (insert_subvector A, Idx0), Idx1)
// -> (insert_subvector (insert_subvector A, Idx1), Idx0)
if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
N1.getValueType() == N0.getOperand(1).getValueType() &&
isa<ConstantSDNode>(N0.getOperand(2))) {
unsigned OtherIdx = cast<ConstantSDNode>(N0.getOperand(2))->getZExtValue();
if (InsIdx < OtherIdx) {
// Swap nodes.
SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
N0.getOperand(0), N1, N2);
AddToWorklist(NewOp.getNode());
return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
VT, NewOp, N0.getOperand(1), N0.getOperand(2));
}
}
// If the input vector is a concatenation, and the insert replaces
// one of the pieces, we can optimize into a single concat_vectors.
if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
N0.getOperand(0).getValueType() == N1.getValueType()) {
unsigned Factor = N1.getValueType().getVectorNumElements();
SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1;
return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
}
return SDValue();
}
SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
SDValue N0 = N->getOperand(0);
// fold (fp_to_fp16 (fp16_to_fp op)) -> op
if (N0->getOpcode() == ISD::FP16_TO_FP)
return N0->getOperand(0);
return SDValue();
}
SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
SDValue N0 = N->getOperand(0);
// fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
if (N0->getOpcode() == ISD::AND) {
ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
if (AndConst && AndConst->getAPIntValue() == 0xffff) {
return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
N0.getOperand(0));
}
}
return SDValue();
}
/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
/// with the destination vector and a zero vector.
/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
/// vector_shuffle V, Zero, <0, 4, 2, 4>
SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
EVT VT = N->getValueType(0);
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
SDLoc DL(N);
// Make sure we're not running after operation legalization where it
// may have custom lowered the vector shuffles.
if (LegalOperations)
return SDValue();
if (N->getOpcode() != ISD::AND)
return SDValue();
if (RHS.getOpcode() == ISD::BITCAST)
RHS = RHS.getOperand(0);
if (RHS.getOpcode() != ISD::BUILD_VECTOR)
return SDValue();
EVT RVT = RHS.getValueType();
unsigned NumElts = RHS.getNumOperands();
// Attempt to create a valid clear mask, splitting the mask into
// sub elements and checking to see if each is
// all zeros or all ones - suitable for shuffle masking.
auto BuildClearMask = [&](int Split) {
int NumSubElts = NumElts * Split;
int NumSubBits = RVT.getScalarSizeInBits() / Split;
SmallVector<int, 8> Indices;
for (int i = 0; i != NumSubElts; ++i) {
int EltIdx = i / Split;
int SubIdx = i % Split;
SDValue Elt = RHS.getOperand(EltIdx);
if (Elt.isUndef()) {
Indices.push_back(-1);
continue;
}
APInt Bits;
if (isa<ConstantSDNode>(Elt))
Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
else if (isa<ConstantFPSDNode>(Elt))
Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
else
return SDValue();
// Extract the sub element from the constant bit mask.
if (DAG.getDataLayout().isBigEndian()) {
Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
} else {
Bits = Bits.lshr(SubIdx * NumSubBits);
}
if (Split > 1)
Bits = Bits.trunc(NumSubBits);
if (Bits.isAllOnesValue())
Indices.push_back(i);
else if (Bits == 0)
Indices.push_back(i + NumSubElts);
else
return SDValue();
}
// Let's see if the target supports this vector_shuffle.
EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
return SDValue();
SDValue Zero = DAG.getConstant(0, DL, ClearVT);
return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
DAG.getBitcast(ClearVT, LHS),
Zero, Indices));
};
// Determine maximum split level (byte level masking).
int MaxSplit = 1;
if (RVT.getScalarSizeInBits() % 8 == 0)
MaxSplit = RVT.getScalarSizeInBits() / 8;
for (int Split = 1; Split <= MaxSplit; ++Split)
if (RVT.getScalarSizeInBits() % Split == 0)
if (SDValue S = BuildClearMask(Split))
return S;
return SDValue();
}
/// Visit a binary vector operation, like ADD.
SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
assert(N->getValueType(0).isVector() &&
"SimplifyVBinOp only works on vectors!");
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
SDValue Ops[] = {LHS, RHS};
// See if we can constant fold the vector operation.
if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
return Fold;
// Try to convert a constant mask AND into a shuffle clear mask.
if (SDValue Shuffle = XformToShuffleWithZero(N))
return Shuffle;
// Type legalization might introduce new shuffles in the DAG.
// Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
// -> (shuffle (VBinOp (A, B)), Undef, Mask).
if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
LHS.getOperand(1).isUndef() &&
RHS.getOperand(1).isUndef()) {
ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
if (SVN0->getMask().equals(SVN1->getMask())) {
EVT VT = N->getValueType(0);
SDValue UndefVector = LHS.getOperand(1);
SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
LHS.getOperand(0), RHS.getOperand(0),
N->getFlags());
AddUsersToWorklist(N);
return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
SVN0->getMask());
}
}
return SDValue();
}
SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
SDValue N2) {
assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
cast<CondCodeSDNode>(N0.getOperand(2))->get());
// If we got a simplified select_cc node back from SimplifySelectCC, then
// break it down into a new SETCC node, and a new SELECT node, and then return
// the SELECT node, since we were called with a SELECT node.
if (SCC.getNode()) {
// Check to see if we got a select_cc back (to turn into setcc/select).
// Otherwise, just return whatever node we got back, like fabs.
if (SCC.getOpcode() == ISD::SELECT_CC) {
SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
N0.getValueType(),
SCC.getOperand(0), SCC.getOperand(1),
SCC.getOperand(4));
AddToWorklist(SETCC.getNode());
return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
SCC.getOperand(2), SCC.getOperand(3));
}
return SCC;
}
return SDValue();
}
/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
/// being selected between, see if we can simplify the select. Callers of this
/// should assume that TheSelect is deleted if this returns true. As such, they
/// should return the appropriate thing (e.g. the node) back to the top-level of
/// the DAG combiner loop to avoid it being looked at.
bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
SDValue RHS) {
// fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
// The select + setcc is redundant, because fsqrt returns NaN for X < 0.
if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
// We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
SDValue Sqrt = RHS;
ISD::CondCode CC;
SDValue CmpLHS;
const ConstantFPSDNode *Zero = nullptr;
if (TheSelect->getOpcode() == ISD::SELECT_CC) {
CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
CmpLHS = TheSelect->getOperand(0);
Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
} else {
// SELECT or VSELECT
SDValue Cmp = TheSelect->getOperand(0);
if (Cmp.getOpcode() == ISD::SETCC) {
CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
CmpLHS = Cmp.getOperand(0);
Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
}
}
if (Zero && Zero->isZero() &&
Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
CC == ISD::SETULT || CC == ISD::SETLT)) {
// We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
CombineTo(TheSelect, Sqrt);
return true;
}
}
}
// Cannot simplify select with vector condition
if (TheSelect->getOperand(0).getValueType().isVector()) return false;
// If this is a select from two identical things, try to pull the operation
// through the select.
if (LHS.getOpcode() != RHS.getOpcode() ||
!LHS.hasOneUse() || !RHS.hasOneUse())
return false;
// If this is a load and the token chain is identical, replace the select
// of two loads with a load through a select of the address to load from.
// This triggers in things like "select bool X, 10.0, 123.0" after the FP
// constants have been dropped into the constant pool.
if (LHS.getOpcode() == ISD::LOAD) {
LoadSDNode *LLD = cast<LoadSDNode>(LHS);
LoadSDNode *RLD = cast<LoadSDNode>(RHS);
// Token chains must be identical.
if (LHS.getOperand(0) != RHS.getOperand(0) ||
// Do not let this transformation reduce the number of volatile loads.
LLD->isVolatile() || RLD->isVolatile() ||
// FIXME: If either is a pre/post inc/dec load,
// we'd need to split out the address adjustment.
LLD->isIndexed() || RLD->isIndexed() ||
// If this is an EXTLOAD, the VT's must match.
LLD->getMemoryVT() != RLD->getMemoryVT() ||
// If this is an EXTLOAD, the kind of extension must match.
(LLD->getExtensionType() != RLD->getExtensionType() &&
// The only exception is if one of the extensions is anyext.
LLD->getExtensionType() != ISD::EXTLOAD &&
RLD->getExtensionType() != ISD::EXTLOAD) ||
// FIXME: this discards src value information. This is
// over-conservative. It would be beneficial to be able to remember
// both potential memory locations. Since we are discarding
// src value info, don't do the transformation if the memory
// locations are not in the default address space.
LLD->getPointerInfo().getAddrSpace() != 0 ||
RLD->getPointerInfo().getAddrSpace() != 0 ||
!TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
LLD->getBasePtr().getValueType()))
return false;
// Check that the select condition doesn't reach either load. If so,
// folding this will induce a cycle into the DAG. If not, this is safe to
// xform, so create a select of the addresses.
SDValue Addr;
if (TheSelect->getOpcode() == ISD::SELECT) {
SDNode *CondNode = TheSelect->getOperand(0).getNode();
if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
(RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
return false;
// The loads must not depend on one another.
if (LLD->isPredecessorOf(RLD) ||
RLD->isPredecessorOf(LLD))
return false;
Addr = DAG.getSelect(SDLoc(TheSelect),
LLD->getBasePtr().getValueType(),
TheSelect->getOperand(0), LLD->getBasePtr(),
RLD->getBasePtr());
} else { // Otherwise SELECT_CC
SDNode *CondLHS = TheSelect->getOperand(0).getNode();
SDNode *CondRHS = TheSelect->getOperand(1).getNode();
if ((LLD->hasAnyUseOfValue(1) &&
(LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
(RLD->hasAnyUseOfValue(1) &&
(RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
return false;
Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
LLD->getBasePtr().getValueType(),
TheSelect->getOperand(0),
TheSelect->getOperand(1),
LLD->getBasePtr(), RLD->getBasePtr(),
TheSelect->getOperand(4));
}
SDValue Load;
// It is safe to replace the two loads if they have different alignments,
// but the new load must be the minimum (most restrictive) alignment of the
// inputs.
unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
if (!RLD->isInvariant())
MMOFlags &= ~MachineMemOperand::MOInvariant;
if (!RLD->isDereferenceable())
MMOFlags &= ~MachineMemOperand::MODereferenceable;
if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
// FIXME: Discards pointer and AA info.
Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
MMOFlags);
} else {
// FIXME: Discards pointer and AA info.
Load = DAG.getExtLoad(
LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
: LLD->getExtensionType(),
SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
}
// Users of the select now use the result of the load.
CombineTo(TheSelect, Load);
// Users of the old loads now use the new load's chain. We know the
// old-load value is dead now.
CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
return true;
}
return false;
}
/// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
/// bitwise 'and'.
SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
SDValue N1, SDValue N2, SDValue N3,
ISD::CondCode CC) {
// If this is a select where the false operand is zero and the compare is a
// check of the sign bit, see if we can perform the "gzip trick":
// select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
// select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
EVT XType = N0.getValueType();
EVT AType = N2.getValueType();
if (!isNullConstant(N3) || !XType.bitsGE(AType))
return SDValue();
// If the comparison is testing for a positive value, we have to invert
// the sign bit mask, so only do that transform if the target has a bitwise
// 'and not' instruction (the invert is free).
if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
// (X > -1) ? A : 0
// (X > 0) ? X : 0 <-- This is canonical signed max.
if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
return SDValue();
} else if (CC == ISD::SETLT) {
// (X < 0) ? A : 0
// (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
return SDValue();
} else {
return SDValue();
}
// and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
// constant.
EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
AddToWorklist(Shift.getNode());
if (XType.bitsGT(AType)) {
Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
AddToWorklist(Shift.getNode());
}
if (CC == ISD::SETGT)
Shift = DAG.getNOT(DL, Shift, AType);
return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
}
SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy);
SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
AddToWorklist(Shift.getNode());
if (XType.bitsGT(AType)) {
Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
AddToWorklist(Shift.getNode());
}
if (CC == ISD::SETGT)
Shift = DAG.getNOT(DL, Shift, AType);
return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
}
/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
/// where 'cond' is the comparison specified by CC.
SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
SDValue N2, SDValue N3, ISD::CondCode CC,
bool NotExtCompare) {
// (x ? y : y) -> y.
if (N2 == N3) return N2;
EVT VT = N2.getValueType();
ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
// Determine if the condition we're dealing with is constant
SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
N0, N1, CC, DL, false);
if (SCC.getNode()) AddToWorklist(SCC.getNode());
if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
// fold select_cc true, x, y -> x
// fold select_cc false, x, y -> y
return !SCCC->isNullValue() ? N2 : N3;
}
// Check to see if we can simplify the select into an fabs node
if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
// Allow either -0.0 or 0.0
if (CFP->isZero()) {
// select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
N0 == N2 && N3.getOpcode() == ISD::FNEG &&
N2 == N3.getOperand(0))
return DAG.getNode(ISD::FABS, DL, VT, N0);
// select (setl[te] X, +/-0.0), fneg(X), X -> fabs
if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
N0 == N3 && N2.getOpcode() == ISD::FNEG &&
N2.getOperand(0) == N3)
return DAG.getNode(ISD::FABS, DL, VT, N3);
}
}
// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
// in it. This is a win when the constant is not otherwise available because
// it replaces two constant pool loads with one. We only do this if the FP
// type is known to be legal, because if it isn't, then we are before legalize
// types an we want the other legalization to happen first (e.g. to avoid
// messing with soft float) and if the ConstantFP is not legal, because if
// it is legal, we may not need to store the FP constant in a constant pool.
if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
if (TLI.isTypeLegal(N2.getValueType()) &&
(TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
TargetLowering::Legal &&
!TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
!TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
// If both constants have multiple uses, then we won't need to do an
// extra load, they are likely around in registers for other users.
(TV->hasOneUse() || FV->hasOneUse())) {
Constant *Elts[] = {
const_cast<ConstantFP*>(FV->getConstantFPValue()),
const_cast<ConstantFP*>(TV->getConstantFPValue())
};
Type *FPTy = Elts[0]->getType();
const DataLayout &TD = DAG.getDataLayout();
// Create a ConstantArray of the two constants.
Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
SDValue CPIdx =
DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
TD.getPrefTypeAlignment(FPTy));
unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
// Get the offsets to the 0 and 1 element of the array so that we can
// select between them.
SDValue Zero = DAG.getIntPtrConstant(0, DL);
unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
SDValue Cond = DAG.getSetCC(DL,
getSetCCResultType(N0.getValueType()),
N0, N1, CC);
AddToWorklist(Cond.getNode());
SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
Cond, One, Zero);
AddToWorklist(CstOffset.getNode());
CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
CstOffset);
AddToWorklist(CPIdx.getNode());
return DAG.getLoad(
TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
Alignment);
}
}
if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
return V;
// fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
// where y is has a single bit set.
// A plaintext description would be, we can turn the SELECT_CC into an AND
// when the condition can be materialized as an all-ones register. Any
// single bit-test can be materialized as an all-ones register with
// shift-left and shift-right-arith.
if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
SDValue AndLHS = N0->getOperand(0);
ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
// Shift the tested bit over the sign bit.
const APInt &AndMask = ConstAndRHS->getAPIntValue();
SDValue ShlAmt =
DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
getShiftAmountTy(AndLHS.getValueType()));
SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
// Now arithmetic right shift it all the way over, so the result is either
// all-ones, or zero.
SDValue ShrAmt =
DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
getShiftAmountTy(Shl.getValueType()));
SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
}
}
// fold select C, 16, 0 -> shl C, 4
if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
TLI.getBooleanContents(N0.getValueType()) ==
TargetLowering::ZeroOrOneBooleanContent) {
// If the caller doesn't want us to simplify this into a zext of a compare,
// don't do it.
if (NotExtCompare && N2C->isOne())
return SDValue();
// Get a SetCC of the condition
// NOTE: Don't create a SETCC if it's not legal on this target.
if (!LegalOperations ||
TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
SDValue Temp, SCC;
// cast from setcc result type to select result type
if (LegalTypes) {
SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
N0, N1, CC);
if (N2.getValueType().bitsLT(SCC.getValueType()))
Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
N2.getValueType());
else
Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
N2.getValueType(), SCC);
} else {
SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
N2.getValueType(), SCC);
}
AddToWorklist(SCC.getNode());
AddToWorklist(Temp.getNode());
if (N2C->isOne())
return Temp;
// shl setcc result by log2 n2c
return DAG.getNode(
ISD::SHL, DL, N2.getValueType(), Temp,
DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
getShiftAmountTy(Temp.getValueType())));
}
}
// Check to see if this is an integer abs.
// select_cc setg[te] X, 0, X, -X ->
// select_cc setgt X, -1, X, -X ->
// select_cc setl[te] X, 0, -X, X ->
// select_cc setlt X, 1, -X, X ->
// Y = sra (X, size(X)-1); xor (add (X, Y), Y)
if (N1C) {
ConstantSDNode *SubC = nullptr;
if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
(N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
(N1C->isOne() && CC == ISD::SETLT)) &&
N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
EVT XType = N0.getValueType();
if (SubC && SubC->isNullValue() && XType.isInteger()) {
SDLoc DL(N0);
SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
N0,
DAG.getConstant(XType.getSizeInBits() - 1, DL,
getShiftAmountTy(N0.getValueType())));
SDValue Add = DAG.getNode(ISD::ADD, DL,
XType, N0, Shift);
AddToWorklist(Shift.getNode());
AddToWorklist(Add.getNode());
return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
}
}
// select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
// select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
// select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
// select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
// select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
// select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
// select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
// select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
SDValue ValueOnZero = N2;
SDValue Count = N3;
// If the condition is NE instead of E, swap the operands.
if (CC == ISD::SETNE)
std::swap(ValueOnZero, Count);
// Check if the value on zero is a constant equal to the bits in the type.
if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
// If the other operand is cttz/cttz_zero_undef of N0, and cttz is
// legal, combine to just cttz.
if ((Count.getOpcode() == ISD::CTTZ ||
Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
N0 == Count.getOperand(0) &&
(!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
return DAG.getNode(ISD::CTTZ, DL, VT, N0);
// If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
// legal, combine to just ctlz.
if ((Count.getOpcode() == ISD::CTLZ ||
Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
N0 == Count.getOperand(0) &&
(!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
return DAG.getNode(ISD::CTLZ, DL, VT, N0);
}
}
}
return SDValue();
}
/// This is a stub for TargetLowering::SimplifySetCC.
SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
ISD::CondCode Cond, const SDLoc &DL,
bool foldBooleans) {
TargetLowering::DAGCombinerInfo
DagCombineInfo(DAG, Level, false, this);
return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
}
/// Given an ISD::SDIV node expressing a divide by constant, return
/// a DAG expression to select that will generate the same value by multiplying
/// by a magic number.
/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
SDValue DAGCombiner::BuildSDIV(SDNode *N) {
// when optimising for minimum size, we don't want to expand a div to a mul
// and a shift.
if (DAG.getMachineFunction().getFunction()->optForMinSize())
return SDValue();
ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
if (!C)
return SDValue();
// Avoid division by zero.
if (C->isNullValue())
return SDValue();
std::vector<SDNode*> Built;
SDValue S =
TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
for (SDNode *N : Built)
AddToWorklist(N);
return S;
}
/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
/// DAG expression that will generate the same value by right shifting.
SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
if (!C)
return SDValue();
// Avoid division by zero.
if (C->isNullValue())
return SDValue();
std::vector<SDNode *> Built;
SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
for (SDNode *N : Built)
AddToWorklist(N);
return S;
}
/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
/// expression that will generate the same value by multiplying by a magic
/// number.
/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
SDValue DAGCombiner::BuildUDIV(SDNode *N) {
// when optimising for minimum size, we don't want to expand a div to a mul
// and a shift.
if (DAG.getMachineFunction().getFunction()->optForMinSize())
return SDValue();
ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
if (!C)
return SDValue();
// Avoid division by zero.
if (C->isNullValue())
return SDValue();
std::vector<SDNode*> Built;
SDValue S =
TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
for (SDNode *N : Built)
AddToWorklist(N);
return S;
}
/// Determines the LogBase2 value for a non-null input value using the
/// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
EVT VT = V.getValueType();
unsigned EltBits = VT.getScalarSizeInBits();
SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
SDValue Base = DAG.getConstant(EltBits - 1, DL, VT);
SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
return LogBase2;
}
/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
/// For the reciprocal, we need to find the zero of the function:
/// F(X) = A X - 1 [which has a zero at X = 1/A]
/// =>
/// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
/// does not require additional intermediate precision]
SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
if (Level >= AfterLegalizeDAG)
return SDValue();
// TODO: Handle half and/or extended types?
EVT VT = Op.getValueType();
if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
return SDValue();
// If estimates are explicitly disabled for this function, we're done.
MachineFunction &MF = DAG.getMachineFunction();
int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
if (Enabled == TLI.ReciprocalEstimate::Disabled)
return SDValue();
// Estimates may be explicitly enabled for this type with a custom number of
// refinement steps.
int Iterations = TLI.getDivRefinementSteps(VT, MF);
if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
AddToWorklist(Est.getNode());
if (Iterations) {
EVT VT = Op.getValueType();
SDLoc DL(Op);
SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
// Newton iterations: Est = Est + Est (1 - Arg * Est)
for (int i = 0; i < Iterations; ++i) {
SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
AddToWorklist(NewEst.getNode());
NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
AddToWorklist(NewEst.getNode());
NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
AddToWorklist(NewEst.getNode());
Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
AddToWorklist(Est.getNode());
}
}
return Est;
}
return SDValue();
}
/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
/// For the reciprocal sqrt, we need to find the zero of the function:
/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
/// =>
/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
/// As a result, we precompute A/2 prior to the iteration loop.
SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
unsigned Iterations,
SDNodeFlags *Flags, bool Reciprocal) {
EVT VT = Arg.getValueType();
SDLoc DL(Arg);
SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
// We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
// this entire sequence requires only one FP constant.
SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
AddToWorklist(HalfArg.getNode());
HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
AddToWorklist(HalfArg.getNode());
// Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
for (unsigned i = 0; i < Iterations; ++i) {
SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
AddToWorklist(NewEst.getNode());
NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
AddToWorklist(NewEst.getNode());
NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
AddToWorklist(NewEst.getNode());
Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
AddToWorklist(Est.getNode());
}
// If non-reciprocal square root is requested, multiply the result by Arg.
if (!Reciprocal) {
Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
AddToWorklist(Est.getNode());
}
return Est;
}
/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
/// For the reciprocal sqrt, we need to find the zero of the function:
/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
/// =>
/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
unsigned Iterations,
SDNodeFlags *Flags, bool Reciprocal) {
EVT VT = Arg.getValueType();
SDLoc DL(Arg);
SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
// This routine must enter the loop below to work correctly
// when (Reciprocal == false).
assert(Iterations > 0);
// Newton iterations for reciprocal square root:
// E = (E * -0.5) * ((A * E) * E + -3.0)
for (unsigned i = 0; i < Iterations; ++i) {
SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
AddToWorklist(AE.getNode());
SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
AddToWorklist(AEE.getNode());
SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
AddToWorklist(RHS.getNode());
// When calculating a square root at the last iteration build:
// S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
// (notice a common subexpression)
SDValue LHS;
if (Reciprocal || (i + 1) < Iterations) {
// RSQRT: LHS = (E * -0.5)
LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
} else {
// SQRT: LHS = (A * E) * -0.5
LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
}
AddToWorklist(LHS.getNode());
Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
AddToWorklist(Est.getNode());
}
return Est;
}
/// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
/// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
/// Op can be zero.
SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags *Flags,
bool Reciprocal) {
if (Level >= AfterLegalizeDAG)
return SDValue();
// TODO: Handle half and/or extended types?
EVT VT = Op.getValueType();
if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64)
return SDValue();
// If estimates are explicitly disabled for this function, we're done.
MachineFunction &MF = DAG.getMachineFunction();
int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
if (Enabled == TLI.ReciprocalEstimate::Disabled)
return SDValue();
// Estimates may be explicitly enabled for this type with a custom number of
// refinement steps.
int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
bool UseOneConstNR = false;
if (SDValue Est =
TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
Reciprocal)) {
AddToWorklist(Est.getNode());
if (Iterations) {
Est = UseOneConstNR
? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
: buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
if (!Reciprocal) {
// Unfortunately, Est is now NaN if the input was exactly 0.0.
// Select out this case and force the answer to 0.0.
EVT VT = Op.getValueType();
SDLoc DL(Op);
SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
EVT CCVT = getSetCCResultType(VT);
SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
AddToWorklist(ZeroCmp.getNode());
Est = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
ZeroCmp, FPZero, Est);
AddToWorklist(Est.getNode());
}
}
return Est;
}
return SDValue();
}
SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
return buildSqrtEstimateImpl(Op, Flags, true);
}
SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
return buildSqrtEstimateImpl(Op, Flags, false);
}
/// Return true if base is a frame index, which is known not to alias with
/// anything but itself. Provides base object and offset as results.
static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
const GlobalValue *&GV, const void *&CV) {
// Assume it is a primitive operation.
Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
// If it's an adding a simple constant then integrate the offset.
if (Base.getOpcode() == ISD::ADD) {
if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
Base = Base.getOperand(0);
Offset += C->getSExtValue();
}
}
// Return the underlying GlobalValue, and update the Offset. Return false
// for GlobalAddressSDNode since the same GlobalAddress may be represented
// by multiple nodes with different offsets.
if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
GV = G->getGlobal();
Offset += G->getOffset();
return false;
}
// Return the underlying Constant value, and update the Offset. Return false
// for ConstantSDNodes since the same constant pool entry may be represented
// by multiple nodes with different offsets.
if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
: (const void *)C->getConstVal();
Offset += C->getOffset();
return false;
}
// If it's any of the following then it can't alias with anything but itself.
return isa<FrameIndexSDNode>(Base);
}
/// Return true if there is any possibility that the two addresses overlap.
bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
// If they are the same then they must be aliases.
if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
// If they are both volatile then they cannot be reordered.
if (Op0->isVolatile() && Op1->isVolatile()) return true;
// If one operation reads from invariant memory, and the other may store, they
// cannot alias. These should really be checking the equivalent of mayWrite,
// but it only matters for memory nodes other than load /store.
if (Op0->isInvariant() && Op1->writeMem())
return false;
if (Op1->isInvariant() && Op0->writeMem())
return false;
// Gather base node and offset information.
SDValue Base1, Base2;
int64_t Offset1, Offset2;
const GlobalValue *GV1, *GV2;
const void *CV1, *CV2;
bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
Base1, Offset1, GV1, CV1);
bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
Base2, Offset2, GV2, CV2);
// If they have a same base address then check to see if they overlap.
if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
(Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
// It is possible for different frame indices to alias each other, mostly
// when tail call optimization reuses return address slots for arguments.
// To catch this case, look up the actual index of frame indices to compute
// the real alias relationship.
if (isFrameIndex1 && isFrameIndex2) {
MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
Offset1 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
Offset2 += MFI.getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
(Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
}
// Otherwise, if we know what the bases are, and they aren't identical, then
// we know they cannot alias.
if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
return false;
// If we know required SrcValue1 and SrcValue2 have relatively large alignment
// compared to the size and offset of the access, we may be able to prove they
// do not alias. This check is conservative for now to catch cases created by
// splitting vector types.
if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
(Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
(Op0->getMemoryVT().getSizeInBits() >> 3 ==
Op1->getMemoryVT().getSizeInBits() >> 3) &&
(Op0->getOriginalAlignment() > (Op0->getMemoryVT().getSizeInBits() >> 3))) {
int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
// There is no overlap between these relatively aligned accesses of similar
// size, return no alias.
if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
(OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
return false;
}
bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
? CombinerGlobalAA
: DAG.getSubtarget().useAA();
#ifndef NDEBUG
if (CombinerAAOnlyFunc.getNumOccurrences() &&
CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
UseAA = false;
#endif
if (UseAA &&
Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
// Use alias analysis information.
int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
Op1->getSrcValueOffset());
int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
Op0->getSrcValueOffset() - MinOffset;
int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
Op1->getSrcValueOffset() - MinOffset;
AliasResult AAResult =
AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
if (AAResult == NoAlias)
return false;
}
// Otherwise we have to assume they alias.
return true;
}
/// Walk up chain skipping non-aliasing memory nodes,
/// looking for aliasing nodes and adding them to the Aliases vector.
void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
SmallVectorImpl<SDValue> &Aliases) {
SmallVector<SDValue, 8> Chains; // List of chains to visit.
SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
// Get alias information for node.
bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
// Starting off.
Chains.push_back(OriginalChain);
unsigned Depth = 0;
// Look at each chain and determine if it is an alias. If so, add it to the
// aliases list. If not, then continue up the chain looking for the next
// candidate.
while (!Chains.empty()) {
SDValue Chain = Chains.pop_back_val();
// For TokenFactor nodes, look at each operand and only continue up the
// chain until we reach the depth limit.
//
// FIXME: The depth check could be made to return the last non-aliasing
// chain we found before we hit a tokenfactor rather than the original
// chain.
if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
Aliases.clear();
Aliases.push_back(OriginalChain);
return;
}
// Don't bother if we've been before.
if (!Visited.insert(Chain.getNode()).second)
continue;
switch (Chain.getOpcode()) {
case ISD::EntryToken:
// Entry token is ideal chain operand, but handled in FindBetterChain.
break;
case ISD::LOAD:
case ISD::STORE: {
// Get alias information for Chain.
bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
!cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
// If chain is alias then stop here.
if (!(IsLoad && IsOpLoad) &&
isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Aliases.push_back(Chain);
} else {
// Look further up the chain.
Chains.push_back(Chain.getOperand(0));
++Depth;
}
break;
}
case ISD::TokenFactor:
// We have to check each of the operands of the token factor for "small"
// token factors, so we queue them up. Adding the operands to the queue
// (stack) in reverse order maintains the original order and increases the
// likelihood that getNode will find a matching token factor (CSE.)
if (Chain.getNumOperands() > 16) {
Aliases.push_back(Chain);
break;
}
for (unsigned n = Chain.getNumOperands(); n;)
Chains.push_back(Chain.getOperand(--n));
++Depth;
break;
case ISD::CopyFromReg:
// Forward past CopyFromReg.
Chains.push_back(Chain.getOperand(0));
++Depth;
break;
default:
// For all other instructions we will just have to take what we can get.
Aliases.push_back(Chain);
break;
}
}
}
/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
/// (aliasing node.)
SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
// Accumulate all the aliases to this node.
GatherAllAliases(N, OldChain, Aliases);
// If no operands then chain to entry token.
if (Aliases.size() == 0)
return DAG.getEntryNode();
// If a single operand then chain to it. We don't need to revisit it.
if (Aliases.size() == 1)
return Aliases[0];
// Construct a custom tailored token factor.
return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
}
// This function tries to collect a bunch of potentially interesting
// nodes to improve the chains of, all at once. This might seem
// redundant, as this function gets called when visiting every store
// node, so why not let the work be done on each store as it's visited?
//
// I believe this is mainly important because MergeConsecutiveStores
// is unable to deal with merging stores of different sizes, so unless
// we improve the chains of all the potential candidates up-front
// before running MergeConsecutiveStores, it might only see some of
// the nodes that will eventually be candidates, and then not be able
// to go from a partially-merged state to the desired final
// fully-merged state.
bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
// This holds the base pointer, index, and the offset in bytes from the base
// pointer.
BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr(), DAG);
// We must have a base and an offset.
if (!BasePtr.Base.getNode())
return false;
// Do not handle stores to undef base pointers.
if (BasePtr.Base.isUndef())
return false;
SmallVector<StoreSDNode *, 8> ChainedStores;
ChainedStores.push_back(St);
// Walk up the chain and look for nodes with offsets from the same
// base pointer. Stop when reaching an instruction with a different kind
// or instruction which has a different base pointer.
StoreSDNode *Index = St;
while (Index) {
// If the chain has more than one use, then we can't reorder the mem ops.
if (Index != St && !SDValue(Index, 0)->hasOneUse())
break;
if (Index->isVolatile() || Index->isIndexed())
break;
// Find the base pointer and offset for this memory node.
BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr(), DAG);
// Check that the base pointer is the same as the original one.
if (!Ptr.equalBaseIndex(BasePtr))
break;
// Walk up the chain to find the next store node, ignoring any
// intermediate loads. Any other kind of node will halt the loop.
SDNode *NextInChain = Index->getChain().getNode();
while (true) {
if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
// We found a store node. Use it for the next iteration.
if (STn->isVolatile() || STn->isIndexed()) {
Index = nullptr;
break;
}
ChainedStores.push_back(STn);
Index = STn;
break;
} else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
NextInChain = Ldn->getChain().getNode();
continue;
} else {
Index = nullptr;
break;
}
} // end while
}
// At this point, ChainedStores lists all of the Store nodes
// reachable by iterating up through chain nodes matching the above
// conditions. For each such store identified, try to find an
// earlier chain to attach the store to which won't violate the
// required ordering.
bool MadeChangeToSt = false;
SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
for (StoreSDNode *ChainedStore : ChainedStores) {
SDValue Chain = ChainedStore->getChain();
SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
if (Chain != BetterChain) {
if (ChainedStore == St)
MadeChangeToSt = true;
BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
}
}
// Do all replacements after finding the replacements to make to avoid making
// the chains more complicated by introducing new TokenFactors.
for (auto Replacement : BetterChains)
replaceStoreChain(Replacement.first, Replacement.second);
return MadeChangeToSt;
}
/// This is the entry point for the file.
void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
CodeGenOpt::Level OptLevel) {
/// This is the main entry point to this class.
DAGCombiner(*this, AA, OptLevel).Run(Level);
}
| [
"frankyroeder@web.de"
] | frankyroeder@web.de |
c553bc896cc0d7e311219a8b895a5b01776971b5 | 3ea829b5ad3cf1cc9e6eb9b208532cf57b7ba90f | /libvpvl2/include/vpvl2/extensions/icu4c/String.h | 0f8f8347c36158c9dc7b439b9a687e2debd34c20 | [] | no_license | hkrn/MMDAI | 2ae70c9be7301e496e9113477d4a5ebdc5dc0a29 | 9ca74bf9f6f979f510f5355d80805f935cc7e610 | refs/heads/master | 2021-01-18T21:30:22.057260 | 2016-05-10T16:30:41 | 2016-05-10T16:30:41 | 1,257,502 | 74 | 22 | null | 2013-07-13T21:28:16 | 2011-01-15T12:05:26 | C++ | UTF-8 | C++ | false | false | 4,351 | h | /**
Copyright (c) 2010-2014 hkrn
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 MMDAI project team 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.
*/
#pragma once
#ifndef VPVL2_EXTENSIONS_ICU_STRING_H_
#define VPVL2_EXTENSIONS_ICU_STRING_H_
/* ICU */
#include <unicode/unistr.h>
#include <unicode/ucnv.h>
#include <string>
#include <vpvl2/IString.h>
namespace vpvl2
{
namespace VPVL2_VERSION_NS
{
namespace extensions
{
namespace icu4c
{
class VPVL2_API String VPVL2_DECL_FINAL : public IString {
public:
struct Converter {
Converter()
: shiftJIS(0),
utf8(0),
utf16(0)
{
}
~Converter() {
ucnv_close(utf8);
utf8 = 0;
ucnv_close(utf16);
utf16 = 0;
ucnv_close(shiftJIS);
shiftJIS = 0;
}
void initialize() {
UErrorCode status = U_ZERO_ERROR;
utf8 = ucnv_open("utf-8", &status);
utf16 = ucnv_open("utf-16le", &status);
shiftJIS = ucnv_open("ibm-943_P15A-2003", &status);
}
UConverter *converterFromCodec(IString::Codec codec) const {
switch (codec) {
case IString::kShiftJIS:
return shiftJIS;
case IString::kUTF8:
return utf8;
case IString::kUTF16:
return utf16;
case IString::kMaxCodecType:
default:
return 0;
}
}
UConverter *shiftJIS;
UConverter *utf8;
UConverter *utf16;
};
struct Less {
/* use custom std::less alternative to prevent warning on MSVC */
bool operator()(const UnicodeString &left, const UnicodeString &right) const {
return left.compare(right) == -1;
}
};
static IString *create(const std::string &value);
static std::string toStdString(const UnicodeString &value);
explicit String(const UnicodeString &value, IString::Codec codec = IString::kUTF8, const Converter *converterRef = 0);
~String();
bool startsWith(const IString *value) const;
bool contains(const IString *value) const;
bool endsWith(const IString *value) const;
void split(const IString *separator, int maxTokens, Array<IString *> &tokens) const;
IString *join(const Array<IString *> &tokens) const;
IString *clone() const;
const HashString toHashString() const;
bool equals(const IString *value) const;
UnicodeString value() const;
std::string toStdString() const;
const uint8 *toByteArray() const;
vsize size() const;
private:
const Converter *m_converterRef;
const UnicodeString m_value;
const IString::Codec m_codec;
const std::string m_utf8;
VPVL2_DISABLE_COPY_AND_ASSIGN(String)
};
} /* namespace icu */
} /* namespace extensions */
} /* namespace VPVL2_VERSION_NS */
using namespace VPVL2_VERSION_NS;
} /* namespace vpvl2 */
#endif
| [
"hikarin.jp@gmail.com"
] | hikarin.jp@gmail.com |
e15b6ff53ea4cb0c5617820374ad166457c67d5a | 877e454863f0b8ec8b25f472856e06b28d9683e0 | /c2c/Builder/C2ModuleLoader.h | 8298cd42aff3ad645eb9d01810208749b643fdd9 | [] | no_license | jtp6052/c2compiler | d1fc502132e89536a12e02bdf2cafe8336d964e8 | 7c012b84a849900a62a72f5b8c5443e130c888c3 | refs/heads/master | 2021-01-18T10:30:08.739835 | 2015-05-03T08:49:46 | 2015-05-03T08:49:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | h | /* Copyright 2013,2014,2015 Bas van den Berg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef BUILDER_C2MODULE_LOADER_H
#define BUILDER_C2MODULE_LOADER_H
#include <string>
namespace C2 {
class Module;
class C2ModuleLoader {
public:
Module* load(const std::string& name);
};
}
#endif
| [
"b.van.den.berg.nl@gmail.com"
] | b.van.den.berg.nl@gmail.com |
ce2c9346a2dae1fdd4af1705e41ac8e940087d83 | a5659d7e45eb0ca27b29f120d31a48d9c0d06613 | /starlab/core/plugins/gui_decorate/gui_decorate.h | 26f69f73af94574c3924c0ae8830893587ba7dc4 | [] | no_license | debayan/FAT | 9eaa64c8fcb6feb40b3fc0f2bcfa6dfbe6b0b567 | f986b9fd5d2becd635f2e137a016f68fab5968f2 | refs/heads/master | 2021-01-18T15:30:59.269163 | 2017-08-15T13:43:23 | 2017-08-15T13:43:23 | 100,380,880 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | h | #pragma once
#include <QToolBar>
#include "StarlabMainWindow.h"
#include "interfaces/GuiPlugin.h"
#include "interfaces/RenderPlugin.h"
#include "interfaces/DecoratePlugin.h"
class gui_decorate : public GuiPlugin{
Q_OBJECT
Q_INTERFACES(GuiPlugin)
/// @{ Load/Update
public:
void load();
void update();
private:
QActionGroup* decoratorGroup;
/// @}
/// @{ Decorate Logic
private:
QToolBar* toolbar(){ return mainWindow()->decorateToolbar; }
QMenu* menu(){ return mainWindow()->decorateMenu; }
public slots:
void toggleDecorator(QAction* );
/// @}
};
| [
"debayanin@gmail.com"
] | debayanin@gmail.com |
c821600150d07913eaf0000ef7a00b002566bf4c | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_5/R+rfi-datapl+rfilp-popa.c.cbmc_out.cpp | 73c68ca5fa1a70a83f3f25ea6ec496f86b829b63 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 48,642 | cpp | // Global variabls:
// 0:vars:2
// 2:atom_0_X5_2:1
// 3:atom_0_X2_1:1
// 4:atom_1_X2_2:1
// 5:atom_1_X3_0:1
// Local global variabls:
// 0:thr0:1
// 1:thr1:1
#define ADDRSIZE 6
#define LOCALADDRSIZE 2
#define NTHREAD 3
#define NCONTEXT 5
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// Declare arrays for intial value version in contexts
int local_mem[LOCALADDRSIZE];
// Dumping initializations
local_mem[0+0] = 0;
local_mem[1+0] = 0;
int cstart[NTHREAD];
int creturn[NTHREAD];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NTHREAD*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NTHREAD*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NTHREAD*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NTHREAD*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NTHREAD*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NTHREAD*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NTHREAD*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NTHREAD*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NTHREAD*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NTHREAD];
int cdy[NTHREAD];
int cds[NTHREAD];
int cdl[NTHREAD];
int cisb[NTHREAD];
int caddr[NTHREAD];
int cctrl[NTHREAD];
int r0= 0;
char creg_r0;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
char creg__r3__2_;
char creg__r0__1_;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
char creg__r4__2_;
char creg__r5__0_;
int r6= 0;
char creg_r6;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
char creg__r9__1_;
int r10= 0;
char creg_r10;
char creg__r10__2_;
int r11= 0;
char creg_r11;
int r12= 0;
char creg_r12;
int r13= 0;
char creg_r13;
int r14= 0;
char creg_r14;
int r15= 0;
char creg_r15;
int r16= 0;
char creg_r16;
int r17= 0;
char creg_r17;
int r18= 0;
char creg_r18;
int r19= 0;
char creg_r19;
char creg__r19__1_;
int r20= 0;
char creg_r20;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
buff(0,4) = 0;
pw(0,4) = 0;
cr(0,4) = 0;
iw(0,4) = 0;
cw(0,4) = 0;
cx(0,4) = 0;
is(0,4) = 0;
cs(0,4) = 0;
crmax(0,4) = 0;
buff(0,5) = 0;
pw(0,5) = 0;
cr(0,5) = 0;
iw(0,5) = 0;
cw(0,5) = 0;
cx(0,5) = 0;
is(0,5) = 0;
cs(0,5) = 0;
crmax(0,5) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
buff(1,4) = 0;
pw(1,4) = 0;
cr(1,4) = 0;
iw(1,4) = 0;
cw(1,4) = 0;
cx(1,4) = 0;
is(1,4) = 0;
cs(1,4) = 0;
crmax(1,4) = 0;
buff(1,5) = 0;
pw(1,5) = 0;
cr(1,5) = 0;
iw(1,5) = 0;
cw(1,5) = 0;
cx(1,5) = 0;
is(1,5) = 0;
cs(1,5) = 0;
crmax(1,5) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
buff(2,4) = 0;
pw(2,4) = 0;
cr(2,4) = 0;
iw(2,4) = 0;
cw(2,4) = 0;
cx(2,4) = 0;
is(2,4) = 0;
cs(2,4) = 0;
crmax(2,4) = 0;
buff(2,5) = 0;
pw(2,5) = 0;
cr(2,5) = 0;
iw(2,5) = 0;
cw(2,5) = 0;
cx(2,5) = 0;
is(2,5) = 0;
cs(2,5) = 0;
crmax(2,5) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(2+0,0) = 0;
mem(3+0,0) = 0;
mem(4+0,0) = 0;
mem(5+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
mem(0,1) = meminit(0,1);
co(0,1) = coinit(0,1);
delta(0,1) = deltainit(0,1);
mem(0,2) = meminit(0,2);
co(0,2) = coinit(0,2);
delta(0,2) = deltainit(0,2);
mem(0,3) = meminit(0,3);
co(0,3) = coinit(0,3);
delta(0,3) = deltainit(0,3);
mem(0,4) = meminit(0,4);
co(0,4) = coinit(0,4);
delta(0,4) = deltainit(0,4);
co(1,0) = 0;
delta(1,0) = -1;
mem(1,1) = meminit(1,1);
co(1,1) = coinit(1,1);
delta(1,1) = deltainit(1,1);
mem(1,2) = meminit(1,2);
co(1,2) = coinit(1,2);
delta(1,2) = deltainit(1,2);
mem(1,3) = meminit(1,3);
co(1,3) = coinit(1,3);
delta(1,3) = deltainit(1,3);
mem(1,4) = meminit(1,4);
co(1,4) = coinit(1,4);
delta(1,4) = deltainit(1,4);
co(2,0) = 0;
delta(2,0) = -1;
mem(2,1) = meminit(2,1);
co(2,1) = coinit(2,1);
delta(2,1) = deltainit(2,1);
mem(2,2) = meminit(2,2);
co(2,2) = coinit(2,2);
delta(2,2) = deltainit(2,2);
mem(2,3) = meminit(2,3);
co(2,3) = coinit(2,3);
delta(2,3) = deltainit(2,3);
mem(2,4) = meminit(2,4);
co(2,4) = coinit(2,4);
delta(2,4) = deltainit(2,4);
co(3,0) = 0;
delta(3,0) = -1;
mem(3,1) = meminit(3,1);
co(3,1) = coinit(3,1);
delta(3,1) = deltainit(3,1);
mem(3,2) = meminit(3,2);
co(3,2) = coinit(3,2);
delta(3,2) = deltainit(3,2);
mem(3,3) = meminit(3,3);
co(3,3) = coinit(3,3);
delta(3,3) = deltainit(3,3);
mem(3,4) = meminit(3,4);
co(3,4) = coinit(3,4);
delta(3,4) = deltainit(3,4);
co(4,0) = 0;
delta(4,0) = -1;
mem(4,1) = meminit(4,1);
co(4,1) = coinit(4,1);
delta(4,1) = deltainit(4,1);
mem(4,2) = meminit(4,2);
co(4,2) = coinit(4,2);
delta(4,2) = deltainit(4,2);
mem(4,3) = meminit(4,3);
co(4,3) = coinit(4,3);
delta(4,3) = deltainit(4,3);
mem(4,4) = meminit(4,4);
co(4,4) = coinit(4,4);
delta(4,4) = deltainit(4,4);
co(5,0) = 0;
delta(5,0) = -1;
mem(5,1) = meminit(5,1);
co(5,1) = coinit(5,1);
delta(5,1) = deltainit(5,1);
mem(5,2) = meminit(5,2);
co(5,2) = coinit(5,2);
delta(5,2) = deltainit(5,2);
mem(5,3) = meminit(5,3);
co(5,3) = coinit(5,3);
delta(5,3) = deltainit(5,3);
mem(5,4) = meminit(5,4);
co(5,4) = coinit(5,4);
delta(5,4) = deltainit(5,4);
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !40, metadata !DIExpression()), !dbg !61
// br label %label_1, !dbg !62
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !60), !dbg !63
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !41, metadata !DIExpression()), !dbg !64
// call void @llvm.dbg.value(metadata i64 1, metadata !44, metadata !DIExpression()), !dbg !64
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !65
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l22_c3
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l22_c3
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !46, metadata !DIExpression()), !dbg !66
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !67
// LD: Guess
old_cr = cr(1,0);
cr(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN LDCOM _l23_c15
// Check
ASSUME(active[cr(1,0)] == 1);
ASSUME(cr(1,0) >= iw(1,0));
ASSUME(cr(1,0) >= 0);
ASSUME(cr(1,0) >= cdy[1]);
ASSUME(cr(1,0) >= cisb[1]);
ASSUME(cr(1,0) >= cdl[1]);
ASSUME(cr(1,0) >= cl[1]);
// Update
creg_r0 = cr(1,0);
crmax(1,0) = max(crmax(1,0),cr(1,0));
caddr[1] = max(caddr[1],0);
if(cr(1,0) < cw(1,0)) {
r0 = buff(1,0);
ASSUME((!(( (cw(1,0) < 1) && (1 < crmax(1,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(1,0) < 2) && (2 < crmax(1,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(1,0) < 3) && (3 < crmax(1,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(1,0) < 4) && (4 < crmax(1,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(1,0) != co(0,cr(1,0))) {
ASSUME(cr(1,0) >= old_cr);
}
pw(1,0) = co(0,cr(1,0));
r0 = mem(0,cr(1,0));
}
ASSUME(creturn[1] >= cr(1,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !48, metadata !DIExpression()), !dbg !66
// %conv = trunc i64 %0 to i32, !dbg !68
// call void @llvm.dbg.value(metadata i32 %conv, metadata !45, metadata !DIExpression()), !dbg !61
// %xor = xor i32 %conv, %conv, !dbg !69
creg_r1 = creg_r0;
r1 = r0 ^ r0;
// call void @llvm.dbg.value(metadata i32 %xor, metadata !49, metadata !DIExpression()), !dbg !61
// %add = add nsw i32 %xor, 1, !dbg !70
creg_r2 = max(0,creg_r1);
r2 = r1 + 1;
// call void @llvm.dbg.value(metadata i32 %add, metadata !50, metadata !DIExpression()), !dbg !61
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !51, metadata !DIExpression()), !dbg !71
// %conv3 = sext i32 %add to i64, !dbg !72
// call void @llvm.dbg.value(metadata i64 %conv3, metadata !53, metadata !DIExpression()), !dbg !71
// store atomic i64 %conv3, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !72
// ST: Guess
// : Release
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l26_c3
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l26_c3
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= creg_r2);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
ASSUME(cw(1,0+1*1) >= cr(1,0+0));
ASSUME(cw(1,0+1*1) >= cr(1,0+1));
ASSUME(cw(1,0+1*1) >= cr(1,2+0));
ASSUME(cw(1,0+1*1) >= cr(1,3+0));
ASSUME(cw(1,0+1*1) >= cr(1,4+0));
ASSUME(cw(1,0+1*1) >= cr(1,5+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+1));
ASSUME(cw(1,0+1*1) >= cw(1,2+0));
ASSUME(cw(1,0+1*1) >= cw(1,3+0));
ASSUME(cw(1,0+1*1) >= cw(1,4+0));
ASSUME(cw(1,0+1*1) >= cw(1,5+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = r2;
mem(0+1*1,cw(1,0+1*1)) = r2;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
is(1,0+1*1) = iw(1,0+1*1);
cs(1,0+1*1) = cw(1,0+1*1);
ASSUME(creturn[1] >= cw(1,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !55, metadata !DIExpression()), !dbg !73
// %1 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !74
// LD: Guess
old_cr = cr(1,0+1*1);
cr(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN LDCOM _l27_c15
// Check
ASSUME(active[cr(1,0+1*1)] == 1);
ASSUME(cr(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cr(1,0+1*1) >= 0);
ASSUME(cr(1,0+1*1) >= cdy[1]);
ASSUME(cr(1,0+1*1) >= cisb[1]);
ASSUME(cr(1,0+1*1) >= cdl[1]);
ASSUME(cr(1,0+1*1) >= cl[1]);
// Update
creg_r3 = cr(1,0+1*1);
crmax(1,0+1*1) = max(crmax(1,0+1*1),cr(1,0+1*1));
caddr[1] = max(caddr[1],0);
if(cr(1,0+1*1) < cw(1,0+1*1)) {
r3 = buff(1,0+1*1);
ASSUME((!(( (cw(1,0+1*1) < 1) && (1 < crmax(1,0+1*1)) )))||(sforbid(0+1*1,1)> 0));
ASSUME((!(( (cw(1,0+1*1) < 2) && (2 < crmax(1,0+1*1)) )))||(sforbid(0+1*1,2)> 0));
ASSUME((!(( (cw(1,0+1*1) < 3) && (3 < crmax(1,0+1*1)) )))||(sforbid(0+1*1,3)> 0));
ASSUME((!(( (cw(1,0+1*1) < 4) && (4 < crmax(1,0+1*1)) )))||(sforbid(0+1*1,4)> 0));
} else {
if(pw(1,0+1*1) != co(0+1*1,cr(1,0+1*1))) {
ASSUME(cr(1,0+1*1) >= old_cr);
}
pw(1,0+1*1) = co(0+1*1,cr(1,0+1*1));
r3 = mem(0+1*1,cr(1,0+1*1));
}
ASSUME(creturn[1] >= cr(1,0+1*1));
// call void @llvm.dbg.value(metadata i64 %1, metadata !57, metadata !DIExpression()), !dbg !73
// %conv7 = trunc i64 %1 to i32, !dbg !75
// call void @llvm.dbg.value(metadata i32 %conv7, metadata !54, metadata !DIExpression()), !dbg !61
// %cmp = icmp eq i32 %conv7, 2, !dbg !76
creg__r3__2_ = max(0,creg_r3);
// %conv8 = zext i1 %cmp to i32, !dbg !76
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !58, metadata !DIExpression()), !dbg !61
// store i32 %conv8, i32* @atom_0_X5_2, align 4, !dbg !77, !tbaa !78
// ST: Guess
iw(1,2) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l29_c15
old_cw = cw(1,2);
cw(1,2) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l29_c15
// Check
ASSUME(active[iw(1,2)] == 1);
ASSUME(active[cw(1,2)] == 1);
ASSUME(sforbid(2,cw(1,2))== 0);
ASSUME(iw(1,2) >= creg__r3__2_);
ASSUME(iw(1,2) >= 0);
ASSUME(cw(1,2) >= iw(1,2));
ASSUME(cw(1,2) >= old_cw);
ASSUME(cw(1,2) >= cr(1,2));
ASSUME(cw(1,2) >= cl[1]);
ASSUME(cw(1,2) >= cisb[1]);
ASSUME(cw(1,2) >= cdy[1]);
ASSUME(cw(1,2) >= cdl[1]);
ASSUME(cw(1,2) >= cds[1]);
ASSUME(cw(1,2) >= cctrl[1]);
ASSUME(cw(1,2) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,2) = (r3==2);
mem(2,cw(1,2)) = (r3==2);
co(2,cw(1,2))+=1;
delta(2,cw(1,2)) = -1;
ASSUME(creturn[1] >= cw(1,2));
// %cmp9 = icmp eq i32 %conv, 1, !dbg !82
creg__r0__1_ = max(0,creg_r0);
// %conv10 = zext i1 %cmp9 to i32, !dbg !82
// call void @llvm.dbg.value(metadata i32 %conv10, metadata !59, metadata !DIExpression()), !dbg !61
// store i32 %conv10, i32* @atom_0_X2_1, align 4, !dbg !83, !tbaa !78
// ST: Guess
iw(1,3) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l31_c15
old_cw = cw(1,3);
cw(1,3) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l31_c15
// Check
ASSUME(active[iw(1,3)] == 1);
ASSUME(active[cw(1,3)] == 1);
ASSUME(sforbid(3,cw(1,3))== 0);
ASSUME(iw(1,3) >= creg__r0__1_);
ASSUME(iw(1,3) >= 0);
ASSUME(cw(1,3) >= iw(1,3));
ASSUME(cw(1,3) >= old_cw);
ASSUME(cw(1,3) >= cr(1,3));
ASSUME(cw(1,3) >= cl[1]);
ASSUME(cw(1,3) >= cisb[1]);
ASSUME(cw(1,3) >= cdy[1]);
ASSUME(cw(1,3) >= cdl[1]);
ASSUME(cw(1,3) >= cds[1]);
ASSUME(cw(1,3) >= cctrl[1]);
ASSUME(cw(1,3) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,3) = (r0==1);
mem(3,cw(1,3)) = (r0==1);
co(3,cw(1,3))+=1;
delta(3,cw(1,3)) = -1;
ASSUME(creturn[1] >= cw(1,3));
// ret i8* null, !dbg !84
ret_thread_1 = (- 1);
goto T1BLOCK_END;
T1BLOCK_END:
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !87, metadata !DIExpression()), !dbg !102
// br label %label_2, !dbg !57
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !101), !dbg !104
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !88, metadata !DIExpression()), !dbg !105
// call void @llvm.dbg.value(metadata i64 2, metadata !90, metadata !DIExpression()), !dbg !105
// store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !60
// ST: Guess
// : Release
iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l37_c3
old_cw = cw(2,0+1*1);
cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l37_c3
// Check
ASSUME(active[iw(2,0+1*1)] == 2);
ASSUME(active[cw(2,0+1*1)] == 2);
ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(cw(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cw(2,0+1*1) >= old_cw);
ASSUME(cw(2,0+1*1) >= cr(2,0+1*1));
ASSUME(cw(2,0+1*1) >= cl[2]);
ASSUME(cw(2,0+1*1) >= cisb[2]);
ASSUME(cw(2,0+1*1) >= cdy[2]);
ASSUME(cw(2,0+1*1) >= cdl[2]);
ASSUME(cw(2,0+1*1) >= cds[2]);
ASSUME(cw(2,0+1*1) >= cctrl[2]);
ASSUME(cw(2,0+1*1) >= caddr[2]);
ASSUME(cw(2,0+1*1) >= cr(2,0+0));
ASSUME(cw(2,0+1*1) >= cr(2,0+1));
ASSUME(cw(2,0+1*1) >= cr(2,2+0));
ASSUME(cw(2,0+1*1) >= cr(2,3+0));
ASSUME(cw(2,0+1*1) >= cr(2,4+0));
ASSUME(cw(2,0+1*1) >= cr(2,5+0));
ASSUME(cw(2,0+1*1) >= cw(2,0+0));
ASSUME(cw(2,0+1*1) >= cw(2,0+1));
ASSUME(cw(2,0+1*1) >= cw(2,2+0));
ASSUME(cw(2,0+1*1) >= cw(2,3+0));
ASSUME(cw(2,0+1*1) >= cw(2,4+0));
ASSUME(cw(2,0+1*1) >= cw(2,5+0));
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+1*1) = 2;
mem(0+1*1,cw(2,0+1*1)) = 2;
co(0+1*1,cw(2,0+1*1))+=1;
delta(0+1*1,cw(2,0+1*1)) = -1;
is(2,0+1*1) = iw(2,0+1*1);
cs(2,0+1*1) = cw(2,0+1*1);
ASSUME(creturn[2] >= cw(2,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !92, metadata !DIExpression()), !dbg !107
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !62
// LD: Guess
old_cr = cr(2,0+1*1);
cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l38_c16
// Check
ASSUME(active[cr(2,0+1*1)] == 2);
ASSUME(cr(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cr(2,0+1*1) >= 0);
ASSUME(cr(2,0+1*1) >= cdy[2]);
ASSUME(cr(2,0+1*1) >= cisb[2]);
ASSUME(cr(2,0+1*1) >= cdl[2]);
ASSUME(cr(2,0+1*1) >= cl[2]);
// Update
creg_r4 = cr(2,0+1*1);
crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1));
caddr[2] = max(caddr[2],0);
if(cr(2,0+1*1) < cw(2,0+1*1)) {
r4 = buff(2,0+1*1);
ASSUME((!(( (cw(2,0+1*1) < 1) && (1 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,1)> 0));
ASSUME((!(( (cw(2,0+1*1) < 2) && (2 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,2)> 0));
ASSUME((!(( (cw(2,0+1*1) < 3) && (3 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,3)> 0));
ASSUME((!(( (cw(2,0+1*1) < 4) && (4 < crmax(2,0+1*1)) )))||(sforbid(0+1*1,4)> 0));
} else {
if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) {
ASSUME(cr(2,0+1*1) >= old_cr);
}
pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1));
r4 = mem(0+1*1,cr(2,0+1*1));
}
ASSUME(creturn[2] >= cr(2,0+1*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !94, metadata !DIExpression()), !dbg !107
// %conv = trunc i64 %0 to i32, !dbg !63
// call void @llvm.dbg.value(metadata i32 %conv, metadata !91, metadata !DIExpression()), !dbg !102
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !96, metadata !DIExpression()), !dbg !110
// %1 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) acquire, align 8, !dbg !65
// LD: Guess
// : Acquire
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l39_c16
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
ASSUME(cr(2,0) >= cx(2,0));
ASSUME(cr(2,0) >= cs(2,0+0));
ASSUME(cr(2,0) >= cs(2,0+1));
ASSUME(cr(2,0) >= cs(2,2+0));
ASSUME(cr(2,0) >= cs(2,3+0));
ASSUME(cr(2,0) >= cs(2,4+0));
ASSUME(cr(2,0) >= cs(2,5+0));
// Update
creg_r5 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r5 = buff(2,0);
ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r5 = mem(0,cr(2,0));
}
cl[2] = max(cl[2],cr(2,0));
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %1, metadata !98, metadata !DIExpression()), !dbg !110
// %conv4 = trunc i64 %1 to i32, !dbg !66
// call void @llvm.dbg.value(metadata i32 %conv4, metadata !95, metadata !DIExpression()), !dbg !102
// %cmp = icmp eq i32 %conv, 2, !dbg !67
creg__r4__2_ = max(0,creg_r4);
// %conv5 = zext i1 %cmp to i32, !dbg !67
// call void @llvm.dbg.value(metadata i32 %conv5, metadata !99, metadata !DIExpression()), !dbg !102
// store i32 %conv5, i32* @atom_1_X2_2, align 4, !dbg !68, !tbaa !69
// ST: Guess
iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l41_c15
old_cw = cw(2,4);
cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l41_c15
// Check
ASSUME(active[iw(2,4)] == 2);
ASSUME(active[cw(2,4)] == 2);
ASSUME(sforbid(4,cw(2,4))== 0);
ASSUME(iw(2,4) >= creg__r4__2_);
ASSUME(iw(2,4) >= 0);
ASSUME(cw(2,4) >= iw(2,4));
ASSUME(cw(2,4) >= old_cw);
ASSUME(cw(2,4) >= cr(2,4));
ASSUME(cw(2,4) >= cl[2]);
ASSUME(cw(2,4) >= cisb[2]);
ASSUME(cw(2,4) >= cdy[2]);
ASSUME(cw(2,4) >= cdl[2]);
ASSUME(cw(2,4) >= cds[2]);
ASSUME(cw(2,4) >= cctrl[2]);
ASSUME(cw(2,4) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,4) = (r4==2);
mem(4,cw(2,4)) = (r4==2);
co(4,cw(2,4))+=1;
delta(4,cw(2,4)) = -1;
ASSUME(creturn[2] >= cw(2,4));
// %cmp6 = icmp eq i32 %conv4, 0, !dbg !73
creg__r5__0_ = max(0,creg_r5);
// %conv7 = zext i1 %cmp6 to i32, !dbg !73
// call void @llvm.dbg.value(metadata i32 %conv7, metadata !100, metadata !DIExpression()), !dbg !102
// store i32 %conv7, i32* @atom_1_X3_0, align 4, !dbg !74, !tbaa !69
// ST: Guess
iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l43_c15
old_cw = cw(2,5);
cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l43_c15
// Check
ASSUME(active[iw(2,5)] == 2);
ASSUME(active[cw(2,5)] == 2);
ASSUME(sforbid(5,cw(2,5))== 0);
ASSUME(iw(2,5) >= creg__r5__0_);
ASSUME(iw(2,5) >= 0);
ASSUME(cw(2,5) >= iw(2,5));
ASSUME(cw(2,5) >= old_cw);
ASSUME(cw(2,5) >= cr(2,5));
ASSUME(cw(2,5) >= cl[2]);
ASSUME(cw(2,5) >= cisb[2]);
ASSUME(cw(2,5) >= cdy[2]);
ASSUME(cw(2,5) >= cdl[2]);
ASSUME(cw(2,5) >= cds[2]);
ASSUME(cw(2,5) >= cctrl[2]);
ASSUME(cw(2,5) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,5) = (r5==0);
mem(5,cw(2,5)) = (r5==0);
co(5,cw(2,5))+=1;
delta(5,cw(2,5)) = -1;
ASSUME(creturn[2] >= cw(2,5));
// ret i8* null, !dbg !75
ret_thread_2 = (- 1);
goto T2BLOCK_END;
T2BLOCK_END:
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !125, metadata !DIExpression()), !dbg !157
// call void @llvm.dbg.value(metadata i8** %argv, metadata !126, metadata !DIExpression()), !dbg !157
// %0 = bitcast i64* %thr0 to i8*, !dbg !77
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !77
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !127, metadata !DIExpression()), !dbg !159
// %1 = bitcast i64* %thr1 to i8*, !dbg !79
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !79
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !131, metadata !DIExpression()), !dbg !161
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !132, metadata !DIExpression()), !dbg !162
// call void @llvm.dbg.value(metadata i64 0, metadata !134, metadata !DIExpression()), !dbg !162
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !82
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l51_c3
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l51_c3
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !135, metadata !DIExpression()), !dbg !164
// call void @llvm.dbg.value(metadata i64 0, metadata !137, metadata !DIExpression()), !dbg !164
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !84
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l52_c3
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l52_c3
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// store i32 0, i32* @atom_0_X5_2, align 4, !dbg !85, !tbaa !86
// ST: Guess
iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l53_c15
old_cw = cw(0,2);
cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l53_c15
// Check
ASSUME(active[iw(0,2)] == 0);
ASSUME(active[cw(0,2)] == 0);
ASSUME(sforbid(2,cw(0,2))== 0);
ASSUME(iw(0,2) >= 0);
ASSUME(iw(0,2) >= 0);
ASSUME(cw(0,2) >= iw(0,2));
ASSUME(cw(0,2) >= old_cw);
ASSUME(cw(0,2) >= cr(0,2));
ASSUME(cw(0,2) >= cl[0]);
ASSUME(cw(0,2) >= cisb[0]);
ASSUME(cw(0,2) >= cdy[0]);
ASSUME(cw(0,2) >= cdl[0]);
ASSUME(cw(0,2) >= cds[0]);
ASSUME(cw(0,2) >= cctrl[0]);
ASSUME(cw(0,2) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,2) = 0;
mem(2,cw(0,2)) = 0;
co(2,cw(0,2))+=1;
delta(2,cw(0,2)) = -1;
ASSUME(creturn[0] >= cw(0,2));
// store i32 0, i32* @atom_0_X2_1, align 4, !dbg !90, !tbaa !86
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l54_c15
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l54_c15
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// store i32 0, i32* @atom_1_X2_2, align 4, !dbg !91, !tbaa !86
// ST: Guess
iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l55_c15
old_cw = cw(0,4);
cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l55_c15
// Check
ASSUME(active[iw(0,4)] == 0);
ASSUME(active[cw(0,4)] == 0);
ASSUME(sforbid(4,cw(0,4))== 0);
ASSUME(iw(0,4) >= 0);
ASSUME(iw(0,4) >= 0);
ASSUME(cw(0,4) >= iw(0,4));
ASSUME(cw(0,4) >= old_cw);
ASSUME(cw(0,4) >= cr(0,4));
ASSUME(cw(0,4) >= cl[0]);
ASSUME(cw(0,4) >= cisb[0]);
ASSUME(cw(0,4) >= cdy[0]);
ASSUME(cw(0,4) >= cdl[0]);
ASSUME(cw(0,4) >= cds[0]);
ASSUME(cw(0,4) >= cctrl[0]);
ASSUME(cw(0,4) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,4) = 0;
mem(4,cw(0,4)) = 0;
co(4,cw(0,4))+=1;
delta(4,cw(0,4)) = -1;
ASSUME(creturn[0] >= cw(0,4));
// store i32 0, i32* @atom_1_X3_0, align 4, !dbg !92, !tbaa !86
// ST: Guess
iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l56_c15
old_cw = cw(0,5);
cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l56_c15
// Check
ASSUME(active[iw(0,5)] == 0);
ASSUME(active[cw(0,5)] == 0);
ASSUME(sforbid(5,cw(0,5))== 0);
ASSUME(iw(0,5) >= 0);
ASSUME(iw(0,5) >= 0);
ASSUME(cw(0,5) >= iw(0,5));
ASSUME(cw(0,5) >= old_cw);
ASSUME(cw(0,5) >= cr(0,5));
ASSUME(cw(0,5) >= cl[0]);
ASSUME(cw(0,5) >= cisb[0]);
ASSUME(cw(0,5) >= cdy[0]);
ASSUME(cw(0,5) >= cdl[0]);
ASSUME(cw(0,5) >= cds[0]);
ASSUME(cw(0,5) >= cctrl[0]);
ASSUME(cw(0,5) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,5) = 0;
mem(5,cw(0,5)) = 0;
co(5,cw(0,5))+=1;
delta(5,cw(0,5)) = -1;
ASSUME(creturn[0] >= cw(0,5));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !93
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call3 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !94
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %2 = load i64, i64* %thr0, align 8, !dbg !95, !tbaa !96
r7 = local_mem[0];
// %call4 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !98
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %3 = load i64, i64* %thr1, align 8, !dbg !99, !tbaa !96
r8 = local_mem[1];
// %call5 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !100
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cw(0,4+0));
ASSUME(cdy[0] >= cw(0,5+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(cdy[0] >= cr(0,4+0));
ASSUME(cdy[0] >= cr(0,5+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !139, metadata !DIExpression()), !dbg !178
// %4 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !102
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l64_c13
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r9 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r9 = buff(0,0);
ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r9 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %4, metadata !141, metadata !DIExpression()), !dbg !178
// %conv = trunc i64 %4 to i32, !dbg !103
// call void @llvm.dbg.value(metadata i32 %conv, metadata !138, metadata !DIExpression()), !dbg !157
// %cmp = icmp eq i32 %conv, 1, !dbg !104
creg__r9__1_ = max(0,creg_r9);
// %conv6 = zext i1 %cmp to i32, !dbg !104
// call void @llvm.dbg.value(metadata i32 %conv6, metadata !142, metadata !DIExpression()), !dbg !157
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !144, metadata !DIExpression()), !dbg !182
// %5 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !106
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l66_c13
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r10 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r10 = buff(0,0+1*1);
ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0));
ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0));
ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0));
ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0));
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r10 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %5, metadata !146, metadata !DIExpression()), !dbg !182
// %conv10 = trunc i64 %5 to i32, !dbg !107
// call void @llvm.dbg.value(metadata i32 %conv10, metadata !143, metadata !DIExpression()), !dbg !157
// %cmp11 = icmp eq i32 %conv10, 2, !dbg !108
creg__r10__2_ = max(0,creg_r10);
// %conv12 = zext i1 %cmp11 to i32, !dbg !108
// call void @llvm.dbg.value(metadata i32 %conv12, metadata !147, metadata !DIExpression()), !dbg !157
// %6 = load i32, i32* @atom_0_X5_2, align 4, !dbg !109, !tbaa !86
// LD: Guess
old_cr = cr(0,2);
cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l68_c13
// Check
ASSUME(active[cr(0,2)] == 0);
ASSUME(cr(0,2) >= iw(0,2));
ASSUME(cr(0,2) >= 0);
ASSUME(cr(0,2) >= cdy[0]);
ASSUME(cr(0,2) >= cisb[0]);
ASSUME(cr(0,2) >= cdl[0]);
ASSUME(cr(0,2) >= cl[0]);
// Update
creg_r11 = cr(0,2);
crmax(0,2) = max(crmax(0,2),cr(0,2));
caddr[0] = max(caddr[0],0);
if(cr(0,2) < cw(0,2)) {
r11 = buff(0,2);
ASSUME((!(( (cw(0,2) < 1) && (1 < crmax(0,2)) )))||(sforbid(2,1)> 0));
ASSUME((!(( (cw(0,2) < 2) && (2 < crmax(0,2)) )))||(sforbid(2,2)> 0));
ASSUME((!(( (cw(0,2) < 3) && (3 < crmax(0,2)) )))||(sforbid(2,3)> 0));
ASSUME((!(( (cw(0,2) < 4) && (4 < crmax(0,2)) )))||(sforbid(2,4)> 0));
} else {
if(pw(0,2) != co(2,cr(0,2))) {
ASSUME(cr(0,2) >= old_cr);
}
pw(0,2) = co(2,cr(0,2));
r11 = mem(2,cr(0,2));
}
ASSUME(creturn[0] >= cr(0,2));
// call void @llvm.dbg.value(metadata i32 %6, metadata !148, metadata !DIExpression()), !dbg !157
// %7 = load i32, i32* @atom_0_X2_1, align 4, !dbg !110, !tbaa !86
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l69_c13
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r12 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r12 = buff(0,3);
ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0));
ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0));
ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0));
ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0));
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r12 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i32 %7, metadata !149, metadata !DIExpression()), !dbg !157
// %8 = load i32, i32* @atom_1_X2_2, align 4, !dbg !111, !tbaa !86
// LD: Guess
old_cr = cr(0,4);
cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l70_c13
// Check
ASSUME(active[cr(0,4)] == 0);
ASSUME(cr(0,4) >= iw(0,4));
ASSUME(cr(0,4) >= 0);
ASSUME(cr(0,4) >= cdy[0]);
ASSUME(cr(0,4) >= cisb[0]);
ASSUME(cr(0,4) >= cdl[0]);
ASSUME(cr(0,4) >= cl[0]);
// Update
creg_r13 = cr(0,4);
crmax(0,4) = max(crmax(0,4),cr(0,4));
caddr[0] = max(caddr[0],0);
if(cr(0,4) < cw(0,4)) {
r13 = buff(0,4);
ASSUME((!(( (cw(0,4) < 1) && (1 < crmax(0,4)) )))||(sforbid(4,1)> 0));
ASSUME((!(( (cw(0,4) < 2) && (2 < crmax(0,4)) )))||(sforbid(4,2)> 0));
ASSUME((!(( (cw(0,4) < 3) && (3 < crmax(0,4)) )))||(sforbid(4,3)> 0));
ASSUME((!(( (cw(0,4) < 4) && (4 < crmax(0,4)) )))||(sforbid(4,4)> 0));
} else {
if(pw(0,4) != co(4,cr(0,4))) {
ASSUME(cr(0,4) >= old_cr);
}
pw(0,4) = co(4,cr(0,4));
r13 = mem(4,cr(0,4));
}
ASSUME(creturn[0] >= cr(0,4));
// call void @llvm.dbg.value(metadata i32 %8, metadata !150, metadata !DIExpression()), !dbg !157
// %9 = load i32, i32* @atom_1_X3_0, align 4, !dbg !112, !tbaa !86
// LD: Guess
old_cr = cr(0,5);
cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l71_c13
// Check
ASSUME(active[cr(0,5)] == 0);
ASSUME(cr(0,5) >= iw(0,5));
ASSUME(cr(0,5) >= 0);
ASSUME(cr(0,5) >= cdy[0]);
ASSUME(cr(0,5) >= cisb[0]);
ASSUME(cr(0,5) >= cdl[0]);
ASSUME(cr(0,5) >= cl[0]);
// Update
creg_r14 = cr(0,5);
crmax(0,5) = max(crmax(0,5),cr(0,5));
caddr[0] = max(caddr[0],0);
if(cr(0,5) < cw(0,5)) {
r14 = buff(0,5);
ASSUME((!(( (cw(0,5) < 1) && (1 < crmax(0,5)) )))||(sforbid(5,1)> 0));
ASSUME((!(( (cw(0,5) < 2) && (2 < crmax(0,5)) )))||(sforbid(5,2)> 0));
ASSUME((!(( (cw(0,5) < 3) && (3 < crmax(0,5)) )))||(sforbid(5,3)> 0));
ASSUME((!(( (cw(0,5) < 4) && (4 < crmax(0,5)) )))||(sforbid(5,4)> 0));
} else {
if(pw(0,5) != co(5,cr(0,5))) {
ASSUME(cr(0,5) >= old_cr);
}
pw(0,5) = co(5,cr(0,5));
r14 = mem(5,cr(0,5));
}
ASSUME(creturn[0] >= cr(0,5));
// call void @llvm.dbg.value(metadata i32 %9, metadata !151, metadata !DIExpression()), !dbg !157
// %and = and i32 %8, %9, !dbg !113
creg_r15 = max(creg_r13,creg_r14);
r15 = r13 & r14;
// call void @llvm.dbg.value(metadata i32 %and, metadata !152, metadata !DIExpression()), !dbg !157
// %and13 = and i32 %7, %and, !dbg !114
creg_r16 = max(creg_r12,creg_r15);
r16 = r12 & r15;
// call void @llvm.dbg.value(metadata i32 %and13, metadata !153, metadata !DIExpression()), !dbg !157
// %and14 = and i32 %6, %and13, !dbg !115
creg_r17 = max(creg_r11,creg_r16);
r17 = r11 & r16;
// call void @llvm.dbg.value(metadata i32 %and14, metadata !154, metadata !DIExpression()), !dbg !157
// %and15 = and i32 %conv12, %and14, !dbg !116
creg_r18 = max(creg__r10__2_,creg_r17);
r18 = (r10==2) & r17;
// call void @llvm.dbg.value(metadata i32 %and15, metadata !155, metadata !DIExpression()), !dbg !157
// %and16 = and i32 %conv6, %and15, !dbg !117
creg_r19 = max(creg__r9__1_,creg_r18);
r19 = (r9==1) & r18;
// call void @llvm.dbg.value(metadata i32 %and16, metadata !156, metadata !DIExpression()), !dbg !157
// %cmp17 = icmp eq i32 %and16, 1, !dbg !118
creg__r19__1_ = max(0,creg_r19);
// br i1 %cmp17, label %if.then, label %if.end, !dbg !120
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg__r19__1_);
if((r19==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([108 x i8], [108 x i8]* @.str.1, i64 0, i64 0), i32 noundef 77, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !121
// unreachable, !dbg !121
r20 = 1;
goto T0BLOCK_END;
T0BLOCK2:
// %10 = bitcast i64* %thr1 to i8*, !dbg !124
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !124
// %11 = bitcast i64* %thr0 to i8*, !dbg !124
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !124
// ret i32 0, !dbg !125
ret_thread_0 = 0;
goto T0BLOCK_END;
T0BLOCK_END:
ASSUME(meminit(0,1) == mem(0,0));
ASSUME(coinit(0,1) == co(0,0));
ASSUME(deltainit(0,1) == delta(0,0));
ASSUME(meminit(0,2) == mem(0,1));
ASSUME(coinit(0,2) == co(0,1));
ASSUME(deltainit(0,2) == delta(0,1));
ASSUME(meminit(0,3) == mem(0,2));
ASSUME(coinit(0,3) == co(0,2));
ASSUME(deltainit(0,3) == delta(0,2));
ASSUME(meminit(0,4) == mem(0,3));
ASSUME(coinit(0,4) == co(0,3));
ASSUME(deltainit(0,4) == delta(0,3));
ASSUME(meminit(1,1) == mem(1,0));
ASSUME(coinit(1,1) == co(1,0));
ASSUME(deltainit(1,1) == delta(1,0));
ASSUME(meminit(1,2) == mem(1,1));
ASSUME(coinit(1,2) == co(1,1));
ASSUME(deltainit(1,2) == delta(1,1));
ASSUME(meminit(1,3) == mem(1,2));
ASSUME(coinit(1,3) == co(1,2));
ASSUME(deltainit(1,3) == delta(1,2));
ASSUME(meminit(1,4) == mem(1,3));
ASSUME(coinit(1,4) == co(1,3));
ASSUME(deltainit(1,4) == delta(1,3));
ASSUME(meminit(2,1) == mem(2,0));
ASSUME(coinit(2,1) == co(2,0));
ASSUME(deltainit(2,1) == delta(2,0));
ASSUME(meminit(2,2) == mem(2,1));
ASSUME(coinit(2,2) == co(2,1));
ASSUME(deltainit(2,2) == delta(2,1));
ASSUME(meminit(2,3) == mem(2,2));
ASSUME(coinit(2,3) == co(2,2));
ASSUME(deltainit(2,3) == delta(2,2));
ASSUME(meminit(2,4) == mem(2,3));
ASSUME(coinit(2,4) == co(2,3));
ASSUME(deltainit(2,4) == delta(2,3));
ASSUME(meminit(3,1) == mem(3,0));
ASSUME(coinit(3,1) == co(3,0));
ASSUME(deltainit(3,1) == delta(3,0));
ASSUME(meminit(3,2) == mem(3,1));
ASSUME(coinit(3,2) == co(3,1));
ASSUME(deltainit(3,2) == delta(3,1));
ASSUME(meminit(3,3) == mem(3,2));
ASSUME(coinit(3,3) == co(3,2));
ASSUME(deltainit(3,3) == delta(3,2));
ASSUME(meminit(3,4) == mem(3,3));
ASSUME(coinit(3,4) == co(3,3));
ASSUME(deltainit(3,4) == delta(3,3));
ASSUME(meminit(4,1) == mem(4,0));
ASSUME(coinit(4,1) == co(4,0));
ASSUME(deltainit(4,1) == delta(4,0));
ASSUME(meminit(4,2) == mem(4,1));
ASSUME(coinit(4,2) == co(4,1));
ASSUME(deltainit(4,2) == delta(4,1));
ASSUME(meminit(4,3) == mem(4,2));
ASSUME(coinit(4,3) == co(4,2));
ASSUME(deltainit(4,3) == delta(4,2));
ASSUME(meminit(4,4) == mem(4,3));
ASSUME(coinit(4,4) == co(4,3));
ASSUME(deltainit(4,4) == delta(4,3));
ASSUME(meminit(5,1) == mem(5,0));
ASSUME(coinit(5,1) == co(5,0));
ASSUME(deltainit(5,1) == delta(5,0));
ASSUME(meminit(5,2) == mem(5,1));
ASSUME(coinit(5,2) == co(5,1));
ASSUME(deltainit(5,2) == delta(5,1));
ASSUME(meminit(5,3) == mem(5,2));
ASSUME(coinit(5,3) == co(5,2));
ASSUME(deltainit(5,3) == delta(5,2));
ASSUME(meminit(5,4) == mem(5,3));
ASSUME(coinit(5,4) == co(5,3));
ASSUME(deltainit(5,4) == delta(5,3));
ASSERT(r20== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
60d7d3eb27c6fbbd4e60834340ee957609e0ba9a | 04b9831df2d2d0e6d34556cc4e3426d1c1e25346 | /razerz_v0.00.1/source/modualz/milieu/partical_env.cpp | a1850741e6a6a54a0d902bbef4cc9310e6454959 | [] | no_license | zeplaz/razerz_backup | 50f167a169a49701372676ed5a0aa78d933de427 | f30567f2d5fbb83dac5a4da297c5e0cc23d5623f | refs/heads/master | 2022-04-13T09:44:58.998155 | 2020-04-01T06:48:02 | 2020-04-01T06:48:02 | 231,964,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,533 | cpp | #include "partical_env.hpp"
long comput_partic_sim::frame_count =0;
void compute_partic_attracto::init()
{
glGenVertexArrays(1, &render_vao);
glBindVertexArray(render_vao);
set_uniform_loc();
//
//glGenBuffers(1, &orgin_ID);
//glBindBuffer(GL_UNIFORM_BUFFER, orgin_ID);
//glBufferData(GL_UNIFORM_BUFFER,sizeof(glm::vec4), glm::value_ptr(orgin), GL_STATIC_COPY);
//glBindBufferBase(GL_UNIFORM_BUFFER, PARTCL_UNI_BIDN_INDX, orgin_ID);
glGenBuffers(2,p_buffz);
glBindBuffer(GL_ARRAY_BUFFER,position_buffer);
glBufferData(GL_ARRAY_BUFFER, PARTICLE_COUNT * sizeof(glm::vec4), NULL, GL_DYNAMIC_COPY);
glm::vec4* positions = (glm::vec4*)glMapBufferRange(GL_ARRAY_BUFFER,
0,
PARTICLE_COUNT * sizeof(glm::vec4),
GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
for(int i = 0; i<PARTICLE_COUNT; i++)
{
positions[i] = orgin+ glm::vec4(random_vector(-10.0f, 10.0f), random_float());
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glVertexAttribPointer(VERTEX_BINDER, 4, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(VERTEX_BINDER);
glBindBuffer(GL_ARRAY_BUFFER, velocity_buffer);
glBufferData(GL_ARRAY_BUFFER, PARTICLE_COUNT * sizeof(glm::vec4), NULL, GL_DYNAMIC_COPY);
glm::vec4 * velocities = (glm::vec4 *)glMapBufferRange(GL_ARRAY_BUFFER,
0,
PARTICLE_COUNT * sizeof(glm::vec4),
GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
for (int i = 0; i < PARTICLE_COUNT; i++)
{
velocities[i] = glm::vec4(random_vector(-0.1f, 0.1f), 0.0f);
}
glUnmapBuffer(GL_ARRAY_BUFFER);
glGenTextures(2, tbos);
for (int i = 0; i < 2; i++)
{
glBindTexture(GL_TEXTURE_BUFFER, tbos[i]);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, p_buffz[i]);
}
glGenBuffers(1, &attractor_buffer);
glBindBuffer(GL_UNIFORM_BUFFER, attractor_buffer);
glBufferData(GL_UNIFORM_BUFFER, MAX_ATTRACTORS * sizeof(glm::vec4), NULL, GL_DYNAMIC_COPY);
for (int i = 0; i < MAX_ATTRACTORS; i++)
{
attractor_masses[i] = 0.5f + random_float() * 1.5f;
}
glBindBufferBase(GL_UNIFORM_BUFFER, PARTCL_UNI_BIDN_INDX, attractor_buffer);
}
void compute_partic_attracto::partical_dispaly()
{
start_ticks = static_cast<GLuint>(tick_current_return())-100000;
current_time = static_cast<GLuint>(tick_current_return());
time = ((start_ticks - current_time) & 0xFFFFF) / float(0xFFFFF);
delta_time = (float)(current_time - last_ticks) * 0.075;
std::cout<<"\n TIMEDISPLAYZVALZ" << "start:" <<start_ticks << " current:" <<current_time << " last:" <<last_ticks <<'\n'
<< "time::"<<time << " delta_time::" << delta_time << '\n';
if (delta_time < 0.01f)
{
return;
}
//glBindBuffer(GL_UNIFORM_BUFFER, attractor_buffer);
glm::vec4 * attractors = (glm::vec4 *)glMapBufferRange(GL_UNIFORM_BUFFER,
0,
MAX_ATTRACTORS * sizeof(glm::vec4),
GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
for(int i = 0; i<MAX_ATTRACTORS;i++)
{
attractors[i] = glm::vec4(sinf(time * (float)(i + 4) * 7.5f * 20.0f) * 50.0f,
cosf(time * (float)(i + 7) * 3.9f * 20.0f) * 50.0f,
sinf(time * (float)(i + 3) * 5.3f * 20.0f) * cosf(time * (float)(i + 5) * 9.1f) * 100.0f,
attractor_masses[i]);
/*std::cout << "\n attractornum:" << i << "\n mass:"<< attractor_masses[i] << '\n'
<< attractors[i].x << '\n'
<< attractors[i].y << '\n'
<< attractors[i].z << '\n'
<< attractors[i].w << '\n' ;*/
/*attractors[i] = glm::vec4(sinf(time * (float)(i + 2) * 4.5f * 10.0f) * 30.0f,
cosf(time * (float)(i + 2) * 3.9f * 10.0f) * 30.0f,
sinf(time * (float)(i + 3) * 4.3f * 10.0f) * cosf(time * (float)(i + 4) * 6.1f) * 70.0f,
attractor_masses[i]);*/
}
glUnmapBuffer(GL_UNIFORM_BUFFER);
if (delta_time >= 2.0f)
{
delta_time = 2.0f;
}
std::cout << "deltatime:" << delta_time <<'\n';
glUseProgram(comput_prog_ID);
glBindImageTexture(PARTCL_U_VELOC_INDEX, velocity_tbo, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
glBindImageTexture(PARTCL_U_POS_INDEX, position_tbo, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA32F);
// Set delta time
glUniform1f(dt_location, delta_time);
glUniform4fv(orgin_loc, 1,glm::value_ptr(orgin));
// Dispatch
glDispatchCompute(PARTICLE_GROUP_COUNT, 1, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
glm::mat4 mvp = glm::perspective(45.0f, active_lenz->aspect_ratio_cal(), 0.1f, 1000.0f) *
glm::translate(glm::mat4(1.f), glm::vec3(0.0f, 0.0f, -160.0f)) *
glm::rotate(glm::mat4(1.f),time * 1000.0f, glm::vec3(0.0f, 1.0f, 0.0f));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glUseProgram(render_prog_ID);
glUniformMatrix4fv(0, 1, GL_FALSE, glm::value_ptr(mvp));
glBindVertexArray(render_vao);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glDrawArrays(GL_POINTS, 0, PARTICLE_COUNT);
last_ticks = current_time;
}
| [
"life.in.the.vivid.dream@gmail.com"
] | life.in.the.vivid.dream@gmail.com |
fa366c25dab24747b281a19d30e5690155434fec | bb512814479e2ce521cc442f7bce776e6b78d1ef | /moore/moorenode/daemon.hpp | 59b389f287c548f0ff175ac135fcbf8c3411610b | [
"BSD-2-Clause"
] | permissive | guanzhongheng/project_my | 3cbdf94b7b4ba2f8fc9f91c028338285a4aade35 | 6268a73222dcf3263f5cf8192f374e5c7119ec29 | refs/heads/master | 2020-04-12T10:36:58.724854 | 2018-12-21T07:26:02 | 2018-12-21T07:26:02 | 162,435,264 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | hpp | #include <moore/node/node.hpp>
#include <moore/node/rpc.hpp>
namespace moore_daemon
{
class daemon
{
public:
void run (boost::filesystem::path const &);
};
class daemon_config
{
public:
daemon_config (boost::filesystem::path const &);
bool deserialize_json (bool &, boost::property_tree::ptree &);
void serialize_json (boost::property_tree::ptree &);
bool upgrade_json (unsigned, boost::property_tree::ptree &);
bool rpc_enable;
rai::rpc_config rpc;
rai::node_config node;
bool opencl_enable;
rai::opencl_config opencl;
};
}
| [
"373284103@qq.com"
] | 373284103@qq.com |
a01111c3c75894761dceb209aff765f568dc0eb1 | 12f72860c03aae2895ad9cadfc760a71843afea6 | /2013/software/src/sensors/camera3D/StereoSource.hpp | 760867be4d2b47ad50dabdb8d935b236fdb276a2 | [] | no_license | bennuttle/igvc-software | 01af6034ab8cac8108edda0ce7b2b314d87aa39f | f8e42d020e92d23d12bccd9ed40537d220e2108f | refs/heads/master | 2021-01-17T13:59:38.769914 | 2014-02-26T18:01:15 | 2014-02-26T18:01:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 856 | hpp | #ifndef STEREOSOURCE_H
#define STEREOSOURCE_H
#include "sensors/camera3D/StereoPair.hpp"
#include "sensors/DataStructures/StereoImageData.hpp"
#include "events/Event.hpp"
#include <boost/thread/thread.hpp>
class StereoSource
{
public:
StereoSource() : _running(true) {}
inline bool Running() {return _running;}
inline void Running(bool newState) {_running = newState;}
inline void LockImages() {_imagesLock.lock();}
inline void UnlockImages() {_imagesLock.unlock();}
inline void LockRunning() {_runningLock.lock();}
inline void UnlockRunning() {_runningLock.unlock();}
Event<StereoImageData> onNewData;
virtual ~StereoSource() {}
private:
bool _running;
boost::mutex _runningLock;
boost::mutex _imagesLock;
};
#endif // STEREOSOURCE_H
| [
"alexander.trimm@gmail.com"
] | alexander.trimm@gmail.com |
33f50f9c543a87bb1e97de48f6d63988be04f4d5 | df1e5024eb33f5526e4495022539b7d87a2a234a | /jian/test.hpp | 2694f0975265e3f14893e0e746f7921a86afd247 | [] | no_license | hust220/jian | 696e19411eca694892326be8e741caf4b8aedbf8 | 0e6f484d44b4c31ab98317b69883510296c20edb | refs/heads/master | 2021-01-11T20:26:49.089144 | 2017-04-17T06:45:04 | 2017-04-17T06:45:04 | 79,116,594 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44 | hpp | #pragma once
#include "test/UnitTest.hpp"
| [
"wj_hust08@hust.edu.cn"
] | wj_hust08@hust.edu.cn |
bd42e4b7e2bade87b94ea776e5ce61d535c968e7 | c03be8c14d1f50f0f5aa4140dcd72aae0e8d54a5 | /chartdelegate.h | 5a58e617c34f5f822d5a8dd47104e19a40cc9cfc | [] | no_license | reignofwebber/chart | 74a26a549fc0b63be01cdfca4297c9c152a84019 | 4c69c1399c98c1bcba134fe774347ded8b287ad5 | refs/heads/master | 2020-04-14T00:17:47.836127 | 2019-01-04T07:48:46 | 2019-01-04T07:48:46 | 163,529,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | h | #ifndef CHARTDELEGATE_H
#define CHARTDELEGATE_H
#include <QStyledItemDelegate>
class ChartCheckBoxDelegate : public QStyledItemDelegate
{
public:
ChartCheckBoxDelegate(QObject *parent = 0);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
};
class ChartButtonDelegate : public QStyledItemDelegate
{
public:
ChartButtonDelegate(QObject *parent = 0);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);
};
#endif // CHARTDELEGATE_H
| [
"shadowitnesslasher@gmail.com"
] | shadowitnesslasher@gmail.com |
b1479c7d603d3575f0ce0e82de431cf475fcc7f2 | e0bfa24bacce73eeb68673f26bd152b7963ef855 | /workspace1/ABC過去問/ABC169/A.cpp | 5160224546791fe1cc2026ebe5ac257574127d2a | [] | no_license | kenji132/Competitive-Programming | 52b1147d5e846000355cd7ee4805fad639e186d5 | 89c0336139dae002a3187fa372fda7652fd466cb | refs/heads/master | 2023-04-25T08:29:04.657607 | 2021-05-12T09:35:20 | 2021-05-12T09:35:20 | 314,996,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 149 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int a,b,ans;
cin >> a >> b;
ans = a*b;
cout << ans << endl;
return 0;
} | [
"ue52483@gmail.com"
] | ue52483@gmail.com |
90a7f97bf306efc26d68be3cb808f4adea4e30e6 | d044d94f3af1f057c118a583ce3c05c597a6253d | /src/luabind/test/test_user_defined_converter.cpp | 552680d6c5bc23f4b46e086ad1b9583cddd0f748 | [
"MIT"
] | permissive | lonski/amarlon_dependencies | 3e4c08f40cea0cf8263f7d5ead593f981591cf17 | 1e07f90ffa3bf1aeba92ad9a9203aae4df6103e3 | refs/heads/master | 2021-01-10T08:17:16.101370 | 2016-03-28T21:29:39 | 2016-03-28T21:29:39 | 43,238,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,327 | cpp | // Copyright Daniel Wallin 2008. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "test.hpp"
#include <luabind/luabind.hpp>
namespace {
struct X
{
X(lua_Integer value_)
: value(value_)
{}
lua_Integer value;
};
lua_Integer take(X x)
{
return x.value;
}
X get(lua_Integer value)
{
return X(value);
}
} // namespace unnamed
namespace luabind {
template <>
struct default_converter<X>
: native_converter_base<X>
{
int compute_score(lua_State* L, int index)
{
return cv.compute_score(L, index);
}
X from(lua_State* L, int index)
{
return X(lua_tointeger(L, index));
}
void to(lua_State* L, X const& x)
{
lua_pushinteger(L, x.value);
}
default_converter<int> cv;
};
} // namespace luabind
void test_main(lua_State* L)
{
using namespace luabind;
module(L) [
def("take", &take),
def("get", &get)
];
DOSTRING(L,
"assert(take(1) == 1)\n"
"assert(take(2) == 2)\n"
);
DOSTRING(L,
"assert(get(1) == 1)\n"
"assert(get(2) == 2)\n"
);
}
| [
"michal@lonski.pl"
] | michal@lonski.pl |
c6a30f65d2aa75eaf23c503ca5c134e2e51370c1 | f5e74e06f86e3bc7f82fd02bbcdd2cbe465c75e2 | /GameFramework/PP01.HelloSDL/InputHandler.cpp | fca198cc0bd728b0a3546a1465a3a0a9dc7d5ed4 | [] | no_license | vRien/20171118 | 9bc719c71cd685dbe4571a19eb1701ae7b59a75f | 12198866bb99caa305aa0ac98fb84e7091f7719b | refs/heads/master | 2020-04-05T07:16:30.271418 | 2018-11-15T17:59:04 | 2018-11-15T17:59:04 | 156,669,485 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,012 | cpp | #include "InputHandler.h"
#include "Game.h"
InputHandler* InputHandler::s_pInstance = 0;
InputHandler::InputHandler()
{
m_mousePosition = new Vector2D(0, 0);
for (int i = 0; i < 3; i++)
{
m_mouseButtonStates.push_back(false);
}
}
void InputHandler::clean()
{
// ÇâÈÄ Ãß°¡
}
void InputHandler::update()
{
SDL_PollEvent(&event);
switch (event.type)
{
case SDL_QUIT:
TheGame::Instance()->quit();
break;
case SDL_MOUSEMOTION:
onMouseMove(event);
break;
case SDL_MOUSEBUTTONDOWN:
onMouseButtonDown(event);
break;
case SDL_MOUSEBUTTONUP:
onMouseButtonUp(event);
break;
case SDL_KEYDOWN:
onKeyDown();
break;
case SDL_KEYUP:
onKeyUp();
break;
default:
break;
}
if (event.type == SDL_KEYUP)
{
m_keystates = SDL_GetKeyboardState(0);
}
if (event.type == SDL_KEYDOWN)
{
m_keystates = SDL_GetKeyboardState(0);
}
if (event.type == SDL_MOUSEMOTION)
{
m_mousePosition->setX(event.motion.x);
m_mousePosition->setY(event.motion.y);
}
else if (event.type == SDL_MOUSEBUTTONDOWN)
{
if (event.button.button == SDL_BUTTON_LEFT)
{
m_mouseButtonStates[LEFT] = true;
}
if (event.button.button == SDL_BUTTON_MIDDLE)
{
m_mouseButtonStates[MIDDLE] = true;
}
if (event.button.button == SDL_BUTTON_RIGHT)
{
m_mouseButtonStates[RIGHT] = true;
}
}
else if (event.type == SDL_MOUSEBUTTONUP)
{
if (event.button.button == SDL_BUTTON_LEFT)
{
m_mouseButtonStates[LEFT] = false;
}
if (event.button.button == SDL_BUTTON_MIDDLE)
{
m_mouseButtonStates[MIDDLE] = false;
}
if (event.button.button == SDL_BUTTON_RIGHT)
{
m_mouseButtonStates[RIGHT] = false;
}
}
}
bool InputHandler::isKeyDown(SDL_Scancode key)
{
if (m_keystates != 0) {
if (m_keystates[key] == 1)
{
return true;
}
else {
return false;
}
}
return false;
}
bool InputHandler::getMouseButtonState(int buttonNumber)
{
return m_mouseButtonStates[buttonNumber];
}
Vector2D* InputHandler::getMousePosition()
{
return m_mousePosition;
} | [
"kuna3844@naver.com"
] | kuna3844@naver.com |
60e948562e9dfa8b11052231db2ee52982da881a | 303b48eb9354338542e0a4ca68df1978dd8d038b | /include/fox/FXDVec.h | d5f5ca3c3cd9c41a471e629458a0f9c1aada6401 | [
"BSD-3-Clause"
] | permissive | ldematte/beppe | fa98a212bbe4a27c5d63defaf386898a48d72deb | 53369e0635d37d2dc58aa0b6317e664b3cf67547 | refs/heads/master | 2020-06-04T00:05:39.688233 | 2013-01-06T16:37:03 | 2013-01-06T16:37:03 | 7,469,184 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,389 | h | /********************************************************************************
* *
* D o u b l e - V e c t o r O p e r a t i o n s *
* *
*********************************************************************************
* Copyright (C) 1994,2002 by Jeroen van der Zijp. All Rights Reserved. *
*********************************************************************************
* This 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. *
* *
* This 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 this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
*********************************************************************************
* $Id: FXDVec.h,v 1.7 2002/01/18 22:42:52 jeroen Exp $ *
********************************************************************************/
#ifndef FXDVEC_H
#define FXDVEC_H
/// Double-precision vector class
class FXAPI FXDVec {
protected:
FXdouble v[3];
public:
/// Default constructor
FXDVec(){}
/// Copy constructor
FXDVec(const FXDVec& w){v[0]=w.v[0];v[1]=w.v[1];v[2]=w.v[2];}
/// Initialize with components
FXDVec(FXdouble x,FXdouble y,FXdouble z){v[0]=x;v[1]=y;v[2]=z;}
/// Initialize with color
FXDVec(FXColor color);
/// Return a non-const reference to the ith element
FXdouble& operator[](FXint i){return v[i];}
/// Return a const reference to the ith element
const FXdouble& operator[](FXint i) const {return v[i];}
/// Assign color
FXDVec& operator=(FXColor color);
/// Assignment
FXDVec& operator=(const FXDVec& w){v[0]=w.v[0];v[1]=w.v[1];v[2]=w.v[2];return *this;}
/// Assigning operators
FXDVec& operator+=(const FXDVec& a){v[0]+=a.v[0];v[1]+=a.v[1];v[2]+=a.v[2];return *this;}
FXDVec& operator-=(const FXDVec& a){v[0]-=a.v[0];v[1]-=a.v[1];v[2]-=a.v[2];return *this;}
FXDVec& operator*=(FXdouble n){v[0]*=n;v[1]*=n;v[2]*=n;return *this;}
FXDVec& operator/=(FXdouble n){v[0]/=n;v[1]/=n;v[2]/=n;return *this;}
/// Conversions
operator FXdouble*(){return v;}
operator const FXdouble*() const {return v;}
/// Convert to color
operator FXColor() const;
/// Other operators
friend FXDVec operator-(const FXDVec& a){return FXDVec(-a.v[0],-a.v[1],-a.v[2]);}
friend FXDVec operator!(const FXDVec& a){return a.v[0]==0.0 && a.v[1]==0.0 && a.v[2]==0.0;}
friend FXDVec operator+(const FXDVec& a,const FXDVec& b){return FXDVec(a.v[0]+b.v[0],a.v[1]+b.v[1],a.v[2]+b.v[2]);}
friend FXDVec operator-(const FXDVec& a,const FXDVec& b){return FXDVec(a.v[0]-b.v[0],a.v[1]-b.v[1],a.v[2]-b.v[2]);}
friend FXDVec operator*(const FXDVec& a,FXdouble n){return FXDVec(a.v[0]*n,a.v[1]*n,a.v[2]*n);}
friend FXDVec operator*(FXdouble n,const FXDVec& a){return FXDVec(n*a.v[0],n*a.v[1],n*a.v[2]);}
friend FXDVec operator/(const FXDVec& a,FXdouble n){return FXDVec(a.v[0]/n,a.v[1]/n,a.v[2]/n);}
friend FXDVec operator/(FXdouble n,const FXDVec& a){return FXDVec(n/a.v[0],n/a.v[1],n/a.v[2]);}
/// Dot and cross products
friend FXdouble operator*(const FXDVec& a,const FXDVec& b){return a.v[0]*b.v[0]+a.v[1]*b.v[1]+a.v[2]*b.v[2];}
friend FXDVec operator^(const FXDVec& a,const FXDVec& b){return FXDVec(a.v[1]*b.v[2]-a.v[2]*b.v[1], a.v[2]*b.v[0]-a.v[0]*b.v[2], a.v[0]*b.v[1]-a.v[1]*b.v[0]);}
/// Equality tests
friend int operator==(const FXDVec& a,const FXDVec& b){return a.v[0]==b.v[0] && a.v[1]==b.v[1] && a.v[2]==b.v[2];}
friend int operator==(const FXDVec& a,FXdouble n){return a.v[0]==n && a.v[1]==n && a.v[2]==n;}
friend int operator==(FXdouble n,const FXDVec& a){return n==a.v[0] && n==a.v[1] && n==a.v[2];}
friend int operator!=(const FXDVec& a,const FXDVec& b){return a.v[0]!=b.v[0] || a.v[1]!=b.v[1] || a.v[2]!=b.v[2];}
friend int operator!=(const FXDVec& a,FXdouble n){return a.v[0]!=n || a.v[1]!=n || a.v[2]!=n;}
friend int operator!=(FXdouble n,const FXDVec& a){return n!=a.v[0] || n!=a.v[1] || n!=a.v[2];}
/// Other functions
friend FXAPI FXdouble len(const FXDVec& a);
friend FXAPI FXDVec normalize(const FXDVec& a);
friend FXAPI FXDVec lo(const FXDVec& a,const FXDVec& b);
friend FXAPI FXDVec hi(const FXDVec& a,const FXDVec& b);
/// Save to a stream
friend FXAPI FXStream& operator<<(FXStream& store,const FXDVec& v);
/// Load from a stream
friend FXAPI FXStream& operator>>(FXStream& store,FXDVec& v);
};
#endif
| [
"lorenzo.dematte@gmail.com"
] | lorenzo.dematte@gmail.com |
06a06baea8b762cf0a3f1c7b70cbbd386277fa01 | 42d4dd15792f5e86d8b2a629b82e11cc94bb45e2 | /windows/RCTPdf/ReactPackageProvider.cpp | af554dd03afeaa06599e8e9e3ebaa33973ddede7 | [
"MIT"
] | permissive | wonday/react-native-pdf | 0286ab24119d36a27bb63389edde7d0ead5bf57f | ff4fa464fcad9adb388b977d0a8c70febad2ec8d | refs/heads/master | 2023-07-22T16:48:40.187069 | 2023-06-25T16:49:30 | 2023-06-25T16:49:30 | 89,375,180 | 1,483 | 538 | MIT | 2023-08-30T08:45:33 | 2017-04-25T15:12:58 | C++ | UTF-8 | C++ | false | false | 481 | cpp | #include "pch.h"
#include "ReactPackageProvider.h"
#if __has_include("ReactPackageProvider.g.cpp")
# include "ReactPackageProvider.g.cpp"
#endif
#include "RCTPdfViewManager.h"
using namespace winrt::Microsoft::ReactNative;
namespace winrt::RCTPdf::implementation {
void ReactPackageProvider::CreatePackage(IReactPackageBuilder const &packageBuilder) noexcept {
packageBuilder.AddViewManager(L"RCTPdfViewManager", []() { return winrt::make<RCTPdfViewManager>(); });
}
}
| [
"bartosz@janeasystems.com"
] | bartosz@janeasystems.com |
44feb85996c247847678a8efb5ab3afa0979363f | 9eea40ddd084afd5da7b057c21b7f1032b40375d | /v8-link/jsc-v8-isolate.cc.inl | f66797eccf75c2918e38e8e279e87b285ed4e426 | [
"BSD-3-Clause"
] | permissive | zhj149/ngui | 7ef982f5fb018532fed1c27a1285c87a9c73d449 | f5c9a82b2ce64eb914727a23299dbb86286f26dc | refs/heads/master | 2021-05-10T21:07:24.764653 | 2018-01-16T02:17:39 | 2018-01-16T02:17:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,069 | inl | /* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2015, xuewen.chu
* 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 xuewen.chu 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 xuewen.chu 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.
*
* ***** END LICENSE BLOCK ***** */
v8_ns(internal)
static pthread_key_t specific_key;
static pthread_once_t specific_init_done = PTHREAD_ONCE_INIT;
static std::string unknown("[Unknown]");
static std::mutex* global_isolate_mutex = nullptr;
static int global_isolate_count = 0;
static Isolate* global_isolate = nullptr;
static int id = 0;
static const char* v8_version_string = V8_VERSION_STRING;
struct ThreadSpecific {
Isolate* isolate;
static void init() {
int err = pthread_key_create(&specific_key, destructor);
global_isolate_mutex = new std::mutex;
}
static void destructor(void * ptr) {
delete reinterpret_cast<ThreadSpecific*>(ptr);
}
static ThreadSpecific* get_data() {
auto ptr = reinterpret_cast<ThreadSpecific*>(pthread_getspecific(specific_key));
if ( !ptr ) {
ptr = new ThreadSpecific();
memset(ptr, 0, sizeof(ThreadSpecific));
pthread_setspecific(specific_key, ptr);
}
return ptr;
}
};
// -------------------------------------------------------------
static const int64_t DECIMAL_MULTIPLE[] = {
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
};
struct JSCStringTraits: public DefaultTraits {
inline static bool Retain(JSStringRef str) {
if ( str ) return JSStringRetain(str); else return false;
}
inline static void Release(JSStringRef str) {
if ( str ) JSStringRelease(str);
}
};
struct JSCPropertyNameArrayTraits: public DefaultTraits {
inline static bool Retain(JSPropertyNameArrayRef arr) {
if ( arr ) return JSPropertyNameArrayRetain(arr); else return false;
}
inline static void Release(JSPropertyNameArrayRef arr) {
if ( arr ) JSPropertyNameArrayRelease(arr);
}
};
typedef UniquePtr<OpaqueJSString, JSCStringTraits> JSCStringPtr;
typedef UniquePtr<OpaqueJSPropertyNameArray, JSCPropertyNameArrayTraits> JSCPropertyNameArrayPtr;
template<class T = Value>
inline Local<T> Cast(JSValueRef o) {
return *reinterpret_cast<Local<T>*>(&o);
}
template<class T = Value>
inline Local<T> Cast(const Object* o) {
return *reinterpret_cast<Local<T>*>(const_cast<Object**>(&o));
}
template<class T = JSValueRef, class S>
inline T Back(Local<S> o) {
return reinterpret_cast<T>(*o);
}
template<class T = JSValueRef>
inline T Back(const Value* v) {
return reinterpret_cast<T>(const_cast<Value*>(v));
}
template<class T>
static T* Retain(T* t) {
if (t) {
t->retain(); return t;
}
return nullptr;
}
static JSValueRef Retain(JSContextRef ctx, JSValueRef t) {
if (t) {
JSValueProtect(ctx, t);
return t;
}
return nullptr;
}
inline JSValueRef ScopeRetain(Isolate* isolate, JSValueRef value);
template<class T>
static T* Release(T* t) {
if (t) {
t->release(); return t;
}
return nullptr;
}
static JSValueRef Release(JSContextRef ctx, JSValueRef t) {
if (t) {
JSValueUnprotect(ctx, t);
return t;
}
return nullptr;
}
class Microtask {
public:
enum CallbackStyle {
Callback,
JSFunction,
};
Microtask(const Microtask& micro) = delete;
inline Microtask(Microtask&& micro)
: m_style(micro.m_style)
, m_microtask(micro.m_microtask)
, m_data(micro.m_data) {
micro.m_microtask = nullptr;
micro.m_data = nullptr;
}
inline Microtask(MicrotaskCallback microtask, void* data = nullptr)
: m_style(Callback)
, m_microtask((void*)microtask), m_data(data) {
}
inline Microtask(Isolate* isolate, Local<Function> microtask);
inline ~Microtask() { Reset(); }
inline void Reset();
inline bool Run(Isolate* isolate);
private:
CallbackStyle m_style = Callback;
void* m_microtask = nullptr;
void* m_data = nullptr;
};
class IsolateData {
public:
void Initialize(JSGlobalContextRef ctx) {
#define __ok() &ex); do { CHECK(ex==nullptr); }while(0
#define SET_ARRTIBUTES(name) m_##name = (JSObjectRef) \
JSObjectGetProperty(ctx, exports, i::name##_s, __ok()); \
JSValueProtect(ctx, m_##name);
m_ctx = ctx;
JSValueRef ex = nullptr;
auto exports = run_native_script(ctx, (const char*)
native_js::JSC_native_js_code_jsc_v8_isolate_,
"[jsc-v8-isolate.js]");
JS_ISOLATE_DATA(SET_ARRTIBUTES)
}
void Destroy() {
#define DEL_ARRTIBUTES(name) JSValueUnprotect(m_ctx, m_##name);
JS_ISOLATE_DATA(DEL_ARRTIBUTES)
}
static JSObjectRef run_native_script(JSGlobalContextRef ctx,
const char* script, const char* name) {
JSValueRef ex = nullptr;
JSObjectRef global = (JSObjectRef)JSContextGetGlobalObject(ctx);
JSCStringPtr jsc_v8_js = JSStringCreateWithUTF8CString(name);
JSCStringPtr script2 = JSStringCreateWithUTF8CString(script);
auto fn = (JSObjectRef)JSEvaluateScript(ctx, *script2, 0, *jsc_v8_js, 1, __ok());
auto exports = JSObjectMake(ctx, 0, 0);
JSValueRef argv[2] = { exports, global };
JSObjectCallAsFunction(ctx, fn, 0, 2, argv, __ok());
return exports;
}
private:
JSGlobalContextRef m_ctx;
#define DEF_ARRTIBUTES(name) \
public: JSObjectRef name() { return m_##name; } \
private: JSObjectRef m_##name;
JS_ISOLATE_DATA(DEF_ARRTIBUTES)
};
class ContextData {
public:
void Initialize(JSGlobalContextRef ctx) {
m_ctx = ctx;
JSValueRef ex = nullptr;
auto exports = IsolateData::run_native_script(ctx, (const char*)
native_js::JSC_native_js_code_jsc_v8_context_,
"[jsc-v8-context.js]");
JS_CONTEXT_DATA(SET_ARRTIBUTES)
}
void Destroy() {
JS_CONTEXT_DATA(DEL_ARRTIBUTES)
}
void Reset() {
#define RESET_ARRTIBUTES(name) JSValueUnprotect(m_ctx, m_##name);
JS_CONTEXT_DATA(RESET_ARRTIBUTES)
}
private:
JSGlobalContextRef m_ctx;
JS_CONTEXT_DATA(DEF_ARRTIBUTES)
#undef SET_ARRTIBUTES
#undef DEF_ARRTIBUTES
#undef DEL_ARRTIBUTES
#undef RESET_ARRTIBUTES
};
/**
* @class i::Isloate
*/
class Isolate {
private:
void add_global_isolate() {
ThreadSpecific::get_data()->isolate = this;
if (global_isolate_count) {
global_isolate = nullptr;
} else {
global_isolate = this;
}
global_isolate_count++;
}
void clear_global_isolate() {
ThreadSpecific::get_data()->isolate = nullptr;
if (global_isolate == this) {
global_isolate = nullptr;
}
global_isolate_count--;
}
Isolate() {
pthread_once(&specific_init_done, ThreadSpecific::init);
std::lock_guard<std::mutex> scope(*global_isolate_mutex);
CHECK(ThreadSpecific::get_data()->isolate == nullptr);
add_global_isolate();
m_group = JSContextGroupCreate();
m_default_jsc_ctx = JSGlobalContextCreateInGroup(m_group, nullptr);
ScopeClear clear([this]() {
JSGlobalContextRelease(m_default_jsc_ctx);
JSContextGroupRelease(m_group);
clear_global_isolate();
});
Initialize();
clear.cancel();
}
void Initialize() {
#define ok() &ex); do { CHECK(ex==nullptr); }while(0
m_thread_id = std::this_thread::get_id();
m_microtask_policy = MicrotasksPolicy::kAuto;
auto ctx = m_default_jsc_ctx;
JSObjectRef global = (JSObjectRef)JSContextGetGlobalObject(ctx);
JSValueRef ex = nullptr;
Isolate* isolate = this;
v8::HandleScope scope(reinterpret_cast<v8::Isolate*>(this));
m_undefined = JSValueMakeUndefined(ctx); JSValueProtect(ctx, m_undefined);
m_null = JSValueMakeNull(ctx); JSValueProtect(ctx, m_null);
m_true = JSValueMakeBoolean(ctx, true); JSValueProtect(ctx, m_true);
m_false = JSValueMakeBoolean(ctx, false); JSValueProtect(ctx, m_false);
m_empty_s = JSValueMakeString(ctx, empty_s); JSValueProtect(ctx, m_empty_s);
m_isolate_data.Initialize(ctx);
m_default_context_data.Initialize(ctx);
InitializeTemplate();
// LOG("%d", v8::HandleScope::NumberOfHandles(reinterpret_cast<v8::Isolate*>(this)));
#undef ok
}
~Isolate() {
std::lock_guard<std::mutex> scope(*global_isolate_mutex);
CHECK(!m_cur_ctx);
m_has_terminated = true;
m_exception = nullptr;
auto ctx = m_default_jsc_ctx;
JSValueUnprotect(ctx, m_undefined);
JSValueUnprotect(ctx, m_null);
JSValueUnprotect(ctx, m_true);
JSValueUnprotect(ctx, m_false);
JSValueUnprotect(ctx, m_empty_s);
if (m_message_listener_data) {
JSValueUnprotect(ctx, m_message_listener_data);
}
DisposeTemplate();
m_isolate_data.Destroy();
m_default_context_data.Destroy();
m_has_destroy = true;
JSGlobalContextRelease(m_default_jsc_ctx);
JSContextGroupRelease(m_group);
clear_global_isolate();
}
void InitializeTemplate();
void DisposeTemplate();
public:
inline static v8::Isolate* New(const v8::Isolate::CreateParams& params) {
auto isolate = (i::Isolate*)malloc(sizeof(i::Isolate));
memset(isolate, 0, sizeof(i::Isolate));
new(isolate) Isolate();
return reinterpret_cast<v8::Isolate*>(isolate);
}
inline JSGlobalContextRef jscc() const;
Local<String> New(const char* str, bool ascii = false) {
if (ascii) {
return String::NewFromOneByte(reinterpret_cast<v8::Isolate*>(this), (const uint8_t*)str);
} else {
return String::NewFromUtf8(reinterpret_cast<v8::Isolate*>(this), str);
}
}
inline JSObjectRef NewError(const char* message) {
auto str = JSValueMakeString(jscc(), JSStringCreateWithUTF8CString(message));
auto error = JSObjectCallAsConstructor(jscc(), Error(), 1, &str, 0);
DCHECK(error);
return error;
}
void ThrowException(JSValueRef exception, i::Message* message) {
CHECK(m_exception == nullptr ||
exception == m_exception, "Throw too many exceptions");
if (!JSValueIsObject(jscc(), exception)) {
exception = JSObjectCallAsConstructor(jscc(), Error(), 1, &exception, 0);
DCHECK(exception);
}
m_exception = exception;
if (m_try_catch || m_call_stack == 0) {
i::Message* m = message;
if (!m) {
auto msg = Exception::CreateMessage(reinterpret_cast<v8::Isolate*>(this),
i::Cast(exception));
m = reinterpret_cast<i::Message*>(*msg);
}
if (m_try_catch) {
m_try_catch->message_obj_ = m;
} else { // top stack throw
auto data = m_message_listener_data ? m_message_listener_data : exception;
if (m_message_listener) {
m_message_listener(Cast<v8::Message>(reinterpret_cast<class Object*>(m)),
Cast(data));
} else {
PrintMessage(m);
}
}
}
}
void ThrowException(JSValueRef exception) {
ThrowException(exception, nullptr);
}
static inline void PrintMessage(i::Message* message);
bool AddMessageListener(MessageCallback that, Local<Value> data) {
m_message_listener = that;
if (m_message_listener_data) {
JSValueUnprotect(jscc(), m_message_listener_data);
m_message_listener_data = nullptr;
}
if (!data.IsEmpty()) {
m_message_listener_data = Back(data);
JSValueProtect(jscc(), m_message_listener_data);
}
return true;
}
static JSValueRef ScopeRetain(HandleScope* scope, JSValueRef value) {
struct HS {
Isolate* isolate;
HandleScope* prev;
std::vector<JSValueRef>* values;
};
auto hs = reinterpret_cast<HS*>(scope);
if (!hs->isolate->HasDestroy()) {
JSValueProtect(hs->isolate->jscc(), value);
hs->values->push_back(value);
}
return value;
}
inline JSValueRef ScopeRetain(JSValueRef value) {
return ScopeRetain(m_handle_scope, value);
}
inline static Isolate* Current() {
if (global_isolate)
return global_isolate;
auto isolate = ThreadSpecific::get_data()->isolate;
DCHECK(isolate);
return isolate;
}
inline static Isolate* Current(const v8::Isolate* isolate) {
DCHECK(isolate);
return reinterpret_cast<Isolate*>(const_cast<v8::Isolate*>(isolate));
}
inline static Isolate* Current(Isolate* isolate) {
DCHECK(isolate);
return isolate;
}
inline static JSStringRef ToJSString(Isolate* isolate, Local<Value> value) {
return ToJSString(isolate, i::Back(value));
}
inline static JSStringRef ToJSString(Isolate* isolate, JSValueRef value) {
JSStringRef r = JSValueToStringCopy(JSC_CTX(isolate), value, 0);
CHECK(r); return r;
}
inline static std::string ToSTDString(Isolate* isolate, Local<Value> value) {
v8::String::Utf8Value utf8(value);
return *utf8;
}
inline static std::string ToSTDString(Isolate* isolate, JSValueRef value) {
return ToSTDString(isolate, Cast(value));
}
static std::string ToSTDString(Isolate* isolate, JSStringRef value) {
size_t bufferSize = JSStringGetMaximumUTF8CStringSize(value);
char* str = (char*)malloc(bufferSize);
JSStringGetUTF8CString(value, str, bufferSize);
std::string r = str;
free(str);
return r;
}
inline static JSStringRef IndexedToPropertyName(Isolate* isolate, uint32_t index) {
char s[11];
sprintf(s, "%u", index);
JSStringRef r = JSStringCreateWithUTF8CString(s);
CHECK(r); return r;
}
static bool PropertyNameToIndexed(JSStringRef propertyName, uint32_t& out) {
out = 0;
uint len = (uint)JSStringGetLength(propertyName);
if ( len > 10 ) { // 32无符号最长表示为`4294967295`
return false;
}
const JSChar* chars = JSStringGetCharactersPtr(propertyName);
for ( int i = 0; i < len; i++ ) {
JSChar num = chars[i] - '0';
if ( 0 <= num && num <= 9 ) {
out += (num * DECIMAL_MULTIPLE[len - 1 - i]);
} else {
return false; // not int number
}
}
return true;
}
inline void Dispose() {
delete this;
}
inline void SetEmbedderData(uint32_t slot, void* data) {
CHECK(slot < Internals::kNumIsolateDataSlots);
m_data[slot] = data;
}
inline void* GetEmbedderData(uint32_t slot) const {
CHECK(slot < Internals::kNumIsolateDataSlots);
return m_data[slot];
}
inline Local<v8::Context> GetCurrentContext() {
return *reinterpret_cast<Local<v8::Context>*>(&m_cur_ctx);
}
inline Context* GetContext() { return m_cur_ctx; }
void RunMicrotasks(bool Explicit);
inline JSValueRef Undefined() { return m_undefined; }
inline JSValueRef TheHoleValue() { return m_the_hole_value; }
inline JSValueRef Null() { return m_null; }
inline JSValueRef True() { return m_true; }
inline JSValueRef False() { return m_true; }
inline JSValueRef Empty() { return m_empty_s; }
inline JSObjectRef External() { return m_External; }
inline ObjectTemplate* ExternalTemplate() { return m_external_template; }
inline ObjectTemplate* DefaultPlaceholderTemplate() { return m_default_placeholder_template; }
inline ObjectTemplate* CInfoPlaceholderTemplate() { return m_cinfo_placeholder_template; }
inline FatalErrorCallback ExceptionBehavior() const { return m_exception_behavior; }
inline bool HasTerminated() const { return m_has_terminated; }
inline bool HasDestroy() const { return m_has_destroy; }
inline std::thread::id ThreadID() const { return m_thread_id; }
inline int CallStackCount() const { return m_call_stack; }
void Terminated() {}
void CancelTerminated() {}
#define DEF_ARRTIBUTES(NAME) \
public: JSObjectRef NAME() { return m_isolate_data.NAME(); }
JS_ISOLATE_DATA(DEF_ARRTIBUTES)
#undef DEF_ARRTIBUTES
#define DEF_ARRTIBUTES(NAME) \
public: JSObjectRef NAME();
JS_CONTEXT_DATA(DEF_ARRTIBUTES)
#undef DEF_ARRTIBUTES
private:
JSContextGroupRef m_group;
JSGlobalContextRef m_default_jsc_ctx;
JSValueRef m_exception;
Context* m_cur_ctx;
JSValueRef m_undefined; // kUndefinedValueRootIndex = 4;
JSValueRef m_the_hole_value;// kTheHoleValueRootIndex = 5;
JSValueRef m_null; // kNullValueRootIndex = 6;
JSValueRef m_true; // kTrueValueRootIndex = 7;
JSValueRef m_false; // kFalseValueRootIndex = 8;
JSValueRef m_empty_s; // kEmptyStringRootIndex = 9;
JSObjectRef m_External;
ObjectTemplate* m_external_template;
ObjectTemplate* m_default_placeholder_template;
ObjectTemplate* m_cinfo_placeholder_template;
TryCatch* m_try_catch;
HandleScope* m_handle_scope;
MessageCallback m_message_listener;
JSValueRef m_message_listener_data;
FatalErrorCallback m_exception_behavior;
v8::Isolate::AbortOnUncaughtExceptionCallback m_abort_on_uncaught_exception_callback;
std::map<size_t, MicrotasksCompletedCallback> m_microtasks_completed_callback;
std::vector<PrivateData*> m_garbage_handle;
std::mutex m_garbage_handle_mutex;
std::thread::id m_thread_id;
std::vector<Microtask> m_microtask;
MicrotasksPolicy m_microtask_policy;
IsolateData m_isolate_data;
ContextData m_default_context_data;
bool m_has_terminated;
bool m_has_destroy;
int m_call_stack;
void* m_data[Internals::kNumIsolateDataSlots];
friend class Context;
friend class v8::Isolate;
friend class v8::Context;
friend class v8::TryCatch;
friend struct CallbackInfo;
friend class v8::Utils;
friend class v8::Private;
friend class v8::Symbol;
friend class PrivateData;
friend class v8::HandleScope;
friend class v8::EscapableHandleScope;
};
JSValueRef ScopeRetain(Isolate* isolate, JSValueRef value) {
return isolate->ScopeRetain(value);
}
Microtask::Microtask(Isolate* isolate, Local<Function> microtask)
: m_style(JSFunction)
, m_microtask(*microtask)
, m_data(isolate) {
DCHECK(m_microtask);
JSValueProtect(JSC_CTX(isolate), reinterpret_cast<JSValueRef>(m_microtask));
}
void Microtask::Reset() {
if (m_microtask) {
if (m_style == JSFunction) {
DCHECK(m_data);
auto isolate = reinterpret_cast<Isolate*>(m_data);
JSValueUnprotect(JSC_CTX(isolate), reinterpret_cast<JSValueRef>(m_microtask));
}
m_microtask = nullptr;
}
}
bool Microtask::Run(Isolate* iso) {
if (m_style == Callback) {
reinterpret_cast<MicrotaskCallback>(m_microtask)(m_data);
} else {
ENV(iso);
auto f = reinterpret_cast<JSObjectRef>(m_microtask);
JSObjectCallAsFunction(ctx, f, 0, 0, 0, OK(false));
}
return true;
}
void Isolate::RunMicrotasks(bool Explicit) {
if (m_microtask.size()) {
std::vector<Microtask> microtask = std::move(m_microtask);
for (auto& i: microtask) {
if (!i.Run(this)) return;
}
if (Explicit) {
for (auto& i: m_microtasks_completed_callback) {
i.second(reinterpret_cast<v8::Isolate*>(this));
}
}
}
}
v8_ns_end
// --- I s o l a t e ---
V8_EXPORT JSGlobalContextRef javascriptcore_context(v8::Isolate* isolate) {
return ISOLATE(isolate)->jscc();
}
HeapProfiler* Isolate::GetHeapProfiler() {
static uint64_t ptr = 0;
return reinterpret_cast<HeapProfiler*>(&ptr);
}
CpuProfiler* Isolate::GetCpuProfiler() {
static uint64_t ptr = 0;
return reinterpret_cast<CpuProfiler*>(&ptr);
}
bool Isolate::InContext() {
return reinterpret_cast<v8::Isolate*>(ISOLATE()) == this;
}
v8::Local<v8::Context> Isolate::GetCurrentContext() {
return ISOLATE(this)->GetCurrentContext();
}
v8::Local<Value> Isolate::ThrowException(v8::Local<v8::Value> value) {
ENV(this);
isolate->ThrowException(i::Back(value));
return i::Cast(isolate->Undefined());
}
Isolate* Isolate::GetCurrent() {
return reinterpret_cast<v8::Isolate*>(ISOLATE());
}
Isolate* Isolate::New(const Isolate::CreateParams& params) {
return i::Isolate::New(params);
}
void Isolate::Dispose() {
ISOLATE(this)->Dispose();
}
void Isolate::TerminateExecution() {
return ISOLATE(this)->Terminated();
}
bool Isolate::IsExecutionTerminating() {
return ISOLATE(this)->HasTerminated();
}
void Isolate::CancelTerminateExecution() {
ISOLATE(this)->CancelTerminated();
}
void Isolate::LowMemoryNotification() {
JSGarbageCollect(JSC_CTX(this));
}
bool Isolate::AddMessageListener(MessageCallback that, Local<Value> data) {
return ISOLATE(this)->AddMessageListener(that, data);
}
void Isolate::SetFatalErrorHandler(FatalErrorCallback that) {
ISOLATE(this)->m_exception_behavior = that;
}
void Isolate::SetAbortOnUncaughtExceptionCallback(AbortOnUncaughtExceptionCallback callback) {
ISOLATE(this)->m_abort_on_uncaught_exception_callback = callback;
}
// --- Isolate Microtasks ---
void Isolate::AddMicrotasksCompletedCallback(MicrotasksCompletedCallback callback) {
ISOLATE(this)->m_microtasks_completed_callback[size_t(callback)] = callback;
}
void Isolate::RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallback callback) {
ISOLATE(this)->m_microtasks_completed_callback.erase(size_t(callback));
}
void Isolate::RunMicrotasks() {
ISOLATE(this)->RunMicrotasks(true);
}
void Isolate::EnqueueMicrotask(Local<Function> microtask) {
ISOLATE(this)->m_microtask.push_back(i::Microtask(ISOLATE(this), microtask));
}
void Isolate::EnqueueMicrotask(MicrotaskCallback microtask, void* data) {
ISOLATE(this)->m_microtask.push_back(i::Microtask(microtask, data));
}
void Isolate::SetAutorunMicrotasks(bool autorun) {
ISOLATE(this)->m_microtask_policy =
autorun ? MicrotasksPolicy::kAuto : MicrotasksPolicy::kExplicit;
}
bool Isolate::WillAutorunMicrotasks() const {
return false;
}
void Isolate::SetMicrotasksPolicy(MicrotasksPolicy policy) {
ISOLATE(this)->m_microtask_policy = policy;
}
MicrotasksPolicy Isolate::GetMicrotasksPolicy() const {
return ISOLATE(this)->m_microtask_policy;
}
| [
"louistru@hotmail.com"
] | louistru@hotmail.com |
cd60407d8656305839b66062abeb0c9407381f9f | 4351d2d9b23429ce0ea215e435cff91a9c7a37c3 | /code_base/src/dynamic_modules/NonHoloEMA3D.cpp | a45b85af7fde0fe329b3b6064b5ce9e8074d221d | [] | no_license | islers/molar | bd0c802d936438a883dc19ca74e7508b79f2577d | e98de87b48862ec897256a1e172880d9d4de9521 | refs/heads/master | 2021-01-13T04:44:26.660386 | 2015-03-05T22:41:46 | 2015-03-05T22:41:46 | 28,885,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,368 | cpp | /* Copyright (c) 2014, Stefan Isler, islerstefan@bluewin.ch
*
This file is part of MOLAR (Multiple Object Localization And Recognition),
which was originally developed as part of a Bachelor thesis at the
Institute of Robotics and Intelligent Systems (IRIS) of ETH Zurich.
MOLAR 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 3 of the License, or
(at your option) any later version.
MOLAR 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 MOLAR. If not, see <http://www.gnu.org/licenses/>.
*/
#include "NonHoloEMA3D.h"
NonHoloEMA3d::NonHoloEMA3d( Ptr<GenericObject> _objectPointer ):NonHoloEMA(_objectPointer)
{
pPosAlpha = 0.4;
pAngAlpha = 0.8;
pSwitchAlpha = 0.05;
pDirectionSwitch = 0.5; // chosen measure for certainty about current direction (0...1) switch performed if it falls under 0.5
pHasPredicted = false;
pReflectionOccured = 0;
pLengthMax=0;
}
NonHoloEMA3d::~NonHoloEMA3d(void)
{
}
Ptr<SceneObject::State> NonHoloEMA3d::rawState( double _rawX, double _rawY, double _time, double _rawAngle, double _rawTheta, double /*_rawArea*/ ) const
{
Ptr<NonHoloEMA3d::State> rawState = new State();
rawState->raw_x = _rawX;
rawState->raw_y = _rawY;
rawState->raw_angle = _rawAngle;
rawState->type = classId;
rawState->time = _time;
rawState->thetaEstimated_raw = _rawTheta;
return rawState;
}
Ptr<GenericObject::Dynamics> NonHoloEMA3d::sfmCreator( Ptr<GenericObject> _objectPointer )
{
return new NonHoloEMA3d(_objectPointer);
}
void NonHoloEMA3d::setOptions( GenericMultiLevelMap<string>& _dynamicsOptions )
{
if( _dynamicsOptions.hasKey("position_alpha") ) pPosAlpha = _dynamicsOptions["position_alpha"].as<double>();
if( _dynamicsOptions.hasKey("angle_alpha") ) pAngAlpha = _dynamicsOptions["angle_alpha"].as<double>();
if( _dynamicsOptions.hasKey("switch_alpha") ) this->pSwitchAlpha = _dynamicsOptions["switch_alpha"].as<double>();
return;
}
void NonHoloEMA3d::getOptions( GenericMultiLevelMap<string>& _optionLink )
{
_optionLink["position_alpha"].as<double>() = pPosAlpha;
_optionLink["angle_alpha"].as<double>() = pAngAlpha;
_optionLink["switch_alpha"].as<double>() = pSwitchAlpha;
return;
}
void NonHoloEMA3d::setStandardOptions( GenericMultiLevelMap<string>& _optLink )
{
_optLink["position_alpha"].as<double>() = 0.4;
_optLink["angle_alpha"].as<double>() = 0.8;
_optLink["switch_alpha"].as<double>() = 0.05;
return;
}
Ptr<SceneObject::State> NonHoloEMA3d::newState( Mat& _state, RectangleRegion& _region, vector<Point>& /*_contour*/, Mat& _invImg, double _time )
{
double angle;
if( pHistory().size()!=0 )
{
Angle conv(_state.at<float>(2));
conv.toClosestHalfEquivalent( pHistory().back()->angle );
conv.toZero2Pi();
angle = conv.rad();
}
else angle = _state.at<float>(2);
bool imageBorderTouched = pObjectPointer->touchesImageBorder();
double thetaEstimation = 0;
// update rod geometry estimates - freeze properties if state infered from group image or from object at image border
if( !_invImg.empty() && !imageBorderTouched ) // the inverse image is empty if the state was infered from a group
{
double length = _region.width();
double diameter = _region.height();
if( length>pLengthMax ) pLengthMax = length;
pWidth = diameter;
// estimate theta
if( pLengthMax!=0 && pWidth!=0 )
{
thetaEstimation = asin( length/sqrt(pLengthMax*pLengthMax+pWidth*pWidth) ) - atan(pLengthMax/pWidth); // from trigonometric formulas
if( pHistory().size()!=0 )
{
if( pHistory().back()->type == classId ) // adjust theta
{
Angle thetaConv(thetaEstimation);
Ptr<State> lastState = pHistory().back();
thetaConv.toClosestHalfEquivalent( lastState->thetaEstimated );
thetaConv.toZero2Pi();
thetaEstimation = thetaConv.rad();
}
}
}
// else (shouldn't happen, but if) assume robot in plane (theta=0)
}
else // freeze geometric properties
{
if( pHistory().size()!=0 ) // if previous states exist
{
if( pHistory().back()->type==classId )
{
Ptr<State> lastState = pHistory().back();
thetaEstimation = lastState->thetaEstimated;
}
}
// else theta is unknown, assume robot in image plane (theta=0)
}
Ptr<SceneObject::State> newState = rawState( _state.at<float>(0), _state.at<float>(1), _time, angle, thetaEstimation, 0.0 );
return newState;
}
bool NonHoloEMA3d::addState( Ptr<SceneObject::State> _newState, RectangleRegion& _regionOfInterest, vector<Point>& _contour )
{
if( _newState->type!=classId ) return false;
Ptr<NonHoloEMA3d::State> newState = _newState;
// find closest angle equivalent of measured angle to predicted angle in order to get the correct prediction error of the Kalman filter ->already done when creating the state in newState(...)
if( pHistory().size()==0 )
{
newState->x = newState->raw_x;
newState->y = newState->raw_y;
newState->angle = newState->raw_angle;
newState->thetaEstimated = newState->thetaEstimated_raw;
}
else
{
// run prediction if not yet done (necessary to predict rotations through image plane normal)
predict();
Ptr<SceneObject::State> lastState = pHistory().back();
// update positions, EMA-smoothed
newState->x = pPosAlpha*newState->raw_x + (1-pPosAlpha)*lastState->x;
newState->y = pPosAlpha*newState->raw_y + (1-pPosAlpha)*lastState->y;
// check if still happy with chosen direction (using smoothed positions)
vector<double> currentDirection = direction( newState->raw_angle );
double scalProd = currentDirection[0]*( newState->x - lastState->x ) + currentDirection[1]*( newState->y - lastState->y );
int correctDirection = (scalProd>=0)?1:0;
// update certainty measure
pDirectionSwitch = pSwitchAlpha*correctDirection + (1-pSwitchAlpha)*pDirectionSwitch;
// EMA of angle - the old angle is moved to the closest value to raw_angle with 2*pi additions/subtractions to prevent slips over the border range between 2*pi and zero
double smoothedAngle = pAngAlpha*newState->raw_angle + (1-pAngAlpha)*Angle(lastState->angle).closestEquivalent(newState->raw_angle).rad();
double smoothedTheta = newState->thetaEstimated_raw;
if( lastState->type==classId ) // EMA of theta
{
Ptr<State> convLS = lastState;
smoothedTheta = pAngAlpha*newState->thetaEstimated_raw + (1-pAngAlpha)*Angle(convLS->thetaEstimated).closestEquivalent(newState->thetaEstimated_raw).rad();
}
Angle smooth(smoothedAngle);
// switch direction if either average velocity vector indicates it's necessary or a rotation through the image normal was predicted
if( pDirectionSwitch<0.5 || pReflectionOccured==1 )
{
Angle rawToSwitch( newState->raw_angle );
smooth++; //increments the angle with pi
rawToSwitch++;
rawToSwitch.toZero2Pi(); //ensures it is still inside range
newState->raw_angle = rawToSwitch.rad();
pDirectionSwitch = 0.5;
}
smooth.toZero2Pi();
newState->angle = smooth.rad();
newState->thetaEstimated = smoothedTheta;
}
pHistory().push_back( newState );
pHasPredicted = false;
if( !trace_states() )
{
while( pHistory().size()>3 ) pHistory().pop_front();
}
_regionOfInterest.points( pROI() );
pLastContour() = _contour;
if( pTimeSincePredictionReset()>=-1 ) pTimeSincePredictionReset()++;
if( pTimeSincePredictionReset() > 1 ) pTimeSincePredictionReset()=-1; // prediction reset has no effect anymore
return true;
}
void NonHoloEMA3d::resetPrediction()
{
pDirectionSwitch = 0.5;
pHasPredicted = false;
return;
}
void NonHoloEMA3d::predict()
{
if( pHasPredicted ) return;
pHasPredicted = true;
if( pHistory().size()==0 )
{
pXPre = 0;
pYPre = 0;
pAngPre = 0;
return;
}
else if( pHistory().size()==1 )
{
pXPre = pHistory().back()->x;
pYPre = pHistory().back()->y;
pAngPre = pHistory().back()->angle;
return;
}
else
{
double xVel = pHistory().back()->x - pHistory()[pHistory().size()-2]->x;
double yVel = pHistory().back()->y - pHistory()[pHistory().size()-2]->y;
double angVel = SceneObject::calcAngleVelocity( pHistory()[pHistory().size()-2]->angle, pHistory().back()->angle );
double lastTheta=0;
double thetaVel=0;
if( pHistory().back()->type==classId )
{
Ptr<State> last = pHistory().back();
lastTheta = last->thetaEstimated;
if( pHistory()[ pHistory().size()-2 ]->type==classId )
{
Ptr<State> beforeLast = pHistory()[ pHistory().size()-2 ];
// velocity depends on whether it was previously predicted that theta passes through the normal axis or image plane (which are not traceable directly, since theta is bound to [0...pi/2])
if( pReflectionOccured==0 ) thetaVel = last->thetaEstimated - beforeLast->thetaEstimated; // nothing happened
else if( pReflectionOccured==1 ) thetaVel = last->thetaEstimated + beforeLast->thetaEstimated - Angle::pi; // passed through normal axis
else if( pReflectionOccured==2 ) thetaVel = last->thetaEstimated + beforeLast->thetaEstimated; // passed through image plane
if( thetaVel>Angle::pi_half ) thetaVel = Angle::pi_half; // any higher velocity is untraceable and results in problems for the following calculations
}
}
double absVel = sqrt( xVel*xVel + yVel*yVel );
// predict values
pXPre = pHistory().back()->x + absVel*cos( pHistory().back()->angle )*cos(lastTheta);
pYPre = pHistory().back()->y + absVel*sin( pHistory().back()->angle )*cos(lastTheta);
double predTheta = lastTheta+thetaVel;
// theta is bounded in [0...pi/2]
if( predTheta>Angle::pi_half )
{
//predTheta = Angle::pi-predTheta;
pReflectionOccured = 1;
}
else if( predTheta<0 )
{
//predTheta = -predTheta;
pReflectionOccured = 2;
}
else
{
//predTheta = predTheta;
pReflectionOccured = 0;
}
Angle pred( pHistory().back()->angle + angVel );
// orientation changes if reflection through pi/2 occured
if( pReflectionOccured==1 ) pred++;
pred.toZero2Pi();
pAngPre = pred.rad();
return;
}
}
int NonHoloEMA3d::registerFactoryFunction()
{
string info = "Nonholonomic movement where the direction of movement is aligned with the axis. Smoothed positions with an exponential average filter. Prediction based on constant velocity assumption. It is targeted at rod-like objects, their three-dimensional posture is estimated from 2d imagery.";
GenericMultiLevelMap<string> options;
setStandardOptions(options);
int _classId = Dynamics::registerDynamics( DynamicsFacEntry( "NonHoloEMA3d", &sfmCreator, info, options ) );
return _classId;
}
int NonHoloEMA3d::classId = registerFactoryFunction();
NonHoloEMA3d::State::State()
{
type = classId;
}
NonHoloEMA3d::State::~State()
{
}
NonHoloEMA3d::State::State( double _x, double _y, double time, double _angle, double _area ):FilteredDynamics::State( _x, _y, time, _angle, _area )
{
type=classId;
thetaEstimated = 0;
}
NonHoloEMA3d::State::State( Point _pos, double time, double _angle, double _area ):FilteredDynamics::State( _pos, time, _angle, _area )
{
type=classId;
thetaEstimated = 0;
}
| [
"islerstefan@bluewin.ch"
] | islerstefan@bluewin.ch |
9260af6b2cb6800046b50d9bc3f194ab7e9ab64d | c7acadf346ad19d10d103cc6f4b29eb1d39c93a7 | /Touch/Touch.ino | b83d241c05b24d44e64a5eed37d8b149ba7cca2f | [] | no_license | saparhadi/ESP32 | 312e0bfd0670eac4ecd4571a682346c156269eed | 8d067afc9631c50ced076906e157b7c9d6396f5a | refs/heads/master | 2020-08-21T13:37:24.896974 | 2019-11-04T09:18:33 | 2019-11-04T09:18:33 | 216,162,914 | 0 | 0 | null | 2019-10-19T07:23:20 | 2019-10-19T06:54:07 | C++ | UTF-8 | C++ | false | false | 269 | ino | int TOUCH = T3;
//Harus ditambahin "T" soalnya pake sensor Touch, pake nama pin juga bisa
int LED = 23;
int TRESHOLD = 50;
void setup() {
Serial.begin(9600);
Serial.println("Eh kesentuh :P");
}
void loop() {
Serial.println(touchRead(touch);
delay(500);
}
| [
"saparhadi@gmail.com"
] | saparhadi@gmail.com |
d2916283572c49c84e591846790dfd0b53deb643 | e1c68264ea40e3318f22bbd3610b8eddb9191884 | /snake_clion/view.cpp | 267508215a20eefe54c2f47a83aa0c6748b8c8aa | [] | no_license | Arv1k/4_sem | 6a5aef79ab33711066305c8aaf8bc771d10f7186 | 39347a655311a9ef7382a8f61703e4f66ddb5243 | refs/heads/master | 2021-01-02T16:57:48.102794 | 2020-07-17T20:23:42 | 2020-07-17T20:23:42 | 239,628,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | #include "view.h"
#include "tui.h"
View* View::inst_ = nullptr;
View::~View() {
inst_ = nullptr;
}
View* View::get() {
if (inst_ != nullptr) {
return inst_;
}
inst_ = new Tui;
return inst_;
}
void View::setOnTimer(int time, Timeoutable timer) {
std::pair<long, Timeoutable> res;
res.first = time;
res.second = timer;
timer_.emplace_back(res);
} | [
"you@example.com"
] | you@example.com |
40fe37f02eea19b0c99e8167dbb300a21a39aa7b | 71599d9781f65a725e450208944c069a5b062358 | /Codeforces/cf-215/A.cpp | 4daa9a2f827283252d21152ec6eb9426482588c0 | [] | no_license | shuangde/ACM-ICPC-Record | 74babe24f5fe13ea5b9d33b29de5af138eef54cc | 1f450d543e7c434af84c0dcaf9de752956aef94f | refs/heads/master | 2021-01-17T12:07:19.159554 | 2014-08-16T08:04:02 | 2014-08-16T08:04:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,423 | cpp |
//shuangde
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <cstring>
#include <string>
#include <map>
#include <set>
#define MP make_pair
#define SQ ((x)*(x))
#define CLR(a,b) memset(a, (b), sizeof(a))
#define cmax(a,b) a=max(a, (b))
#define cmin(a,b) a=max(a, (b))
#define rep(i, n) for(int i=0;i<n;++i)
#define ff(i, n) for(int i=1;i<=n;++i)
using namespace std;
typedef pair<int, int >PII;
typedef long long int64;
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
int n, m;
char str[100010];
int cnt[100010][3];
int main() {
gets(str+1);
int len = strlen(str+1);
CLR(cnt[0], 0);
for (int i = 1; i <= len; ++i) {
rep(j, 3) cnt[i][j] = cnt[i-1][j];
cnt[i][str[i]-'x']++;
}
scanf("%d", &m);
while (m--) {
int l, r;
scanf("%d%d", &l, &r);
int c[3];
rep(i, 3) c[i] = cnt[r][i]-cnt[l-1][i];
int len = r - l + 1;
if (len < 3) {
puts("YES"); continue;
}
if (len % 3 == 0) {
if (c[0]==c[1]&&c[1]==c[2]) puts("YES");
else puts("NO");
} else if (len%3==1) {
if (c[0]==c[1] && c[1]==c[2]-1 ||
c[0]==c[2] && c[2]==c[1]-1 ||
c[1]==c[2] && c[2]==c[0]-1) puts("YES");
else puts("NO");
} else if (len%3==2) {
if (c[0]+1==c[1] && c[1]==c[2] ||
c[1]+1==c[2] && c[2]==c[0] ||
c[2]+1==c[0] && c[0]==c[1]) puts("YES");
else puts("NO");
}
}
return 0;
}
| [
"zengshuangde@gmail.com"
] | zengshuangde@gmail.com |
d5d779f52a1f9951ebbf66aadf5204ebd47a740c | f9d043f436bd7127d02ba6fa79729c97800b65b9 | /자료구조/lab 4 reform palindrome/lab 4 reform palindrome/소스.cpp | 59c821c0492fadb8df54149bc5cf0d43af051b2f | [] | no_license | kjuk02/repository | 90200ceb3be5f2df4231aac5843ca2dd26cb087c | 294366b424512bd295e9d8a71f88195bbb25fc28 | refs/heads/master | 2022-01-06T12:31:13.538544 | 2019-05-04T05:16:47 | 2019-05-04T05:16:47 | 103,889,131 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,409 | cpp | #include <iostream>
#include <cstdlib>
#include<fstream>
#include<string>
#include<vector>
const char stackSize = 100;
char stack[stackSize];
int top;
using namespace std;
void create_stack();
void push(char num);
void displayStack();
int pop();
int isFull();
int isEmpty();
int main()
{
string num;
ifstream instream;
instream.open("input.txt");
int numcase = 0;
instream >> numcase;
for(int i=0;i<numcase;++i)
{ create_stack();
int count = 0;
instream >> num;
for (int i = 0; i < num.size(); i++)
{
if (num[i] == '(' || num[i] == '{' || num[i] == '[')
push(num[i]);
else if (num[i] == ')' || num[i] == '}' || num[i] == ']')
{
if (num[i] == ')'&&stack[top] == '(')
{
pop();
}
else if (num[i] == ']'&&stack[top] == '[')
{
pop();
}
else if (num[i] == '}'&&stack[top] == '{')
{
pop();
}
else
{
count = 1;
cout << 0 << endl;
break;
}
}
}
if ((top != -1) && count == 0)
{
cout << 0 << endl;
}
else
{
if (count == 0)
cout << 1 << endl;
}
//char input[5];
//while (1)
//{
// cout << "1.Push 2.Pop 3.Displaystack 7.exit \n";
// cin >> input;
// if (strcmp(input, "1") == 0) //푸쉬
// {
// if (!isFull())
// {
// cout << "Enter an char to push => ";
// cin >> num;
// push(num);
// }
// else
// cout << "Stack is full!\n";
// }
// else if (strcmp(input, "2") == 0) //팝
// {
// if (!isEmpty())
// {
// num = pop();
// cout << num << endl;
// }
// else
// cout << "Stack Empty!\n";
// }
// else if (strcmp(input, "5") == 0) //디스플레이스택
// displayStack();
// else if (strcmp(input, "7") == 0) //나가기
// exit(0);
// else
// cout << "Bad Command!\n";
//}
}
instream.close();
return 0;
}
//스택 정의
//함수 정의
void create_stack() //스텍 생성
{
top = -1;
}
void push(char num) //값 입력
{
++top;
stack[top] = num;
}
int pop() //출력
{
return stack[top--];
}
int isFull()
{
if (top == stackSize - 1)
return 1;
else
return 0;
}
int isEmpty()
{
if (top == -1)
return 1;
else
return 0;
}
void displayStack() //스택 나열
{
if (isEmpty())
cout << "Stack is empty!" << endl;
else
{
for (int sp = 0; sp <= top; sp++)
{
cout << stack[sp] << " ";
}
cout << endl;
}
} | [
"kjuk02@naver.com"
] | kjuk02@naver.com |
f9d84f692bfa046346544c26d7d05b93a209568e | c57819bebe1a3e1d305ae0cb869cdcc48c7181d1 | /src/qt/src/3rdparty/webkit/Source/WebCore/platform/graphics/win/MediaPlayerPrivateQuickTimeVisualContext.cpp | 66019e81b62fa6d29be395d7b699910543a313b6 | [
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"Qt-LGPL-exception-1.1",
"LicenseRef-scancode-generic-exception",
"GPL-3.0-only",
"GPL-1.0-or-later",
"GFDL-1.3-only",
"BSD-3-Clause"
] | permissive | blowery/phantomjs | 255829570e90a28d1cd597192e20314578ef0276 | f929d2b04a29ff6c3c5b47cd08a8f741b1335c72 | refs/heads/master | 2023-04-08T01:22:35.426692 | 2012-10-11T17:43:24 | 2012-10-11T17:43:24 | 6,177,895 | 1 | 0 | BSD-3-Clause | 2023-04-03T23:09:40 | 2012-10-11T17:39:25 | C++ | UTF-8 | C++ | false | false | 43,845 | cpp | /*
* Copyright (C) 2007, 2008, 2009, 2010, 2011 Apple, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#if ENABLE(VIDEO)
#include "MediaPlayerPrivateQuickTimeVisualContext.h"
#include "ApplicationCacheHost.h"
#include "ApplicationCacheResource.h"
#include "Cookie.h"
#include "CookieJar.h"
#include "DocumentLoader.h"
#include "Frame.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "KURL.h"
#include "MediaPlayerPrivateTaskTimer.h"
#include "QTCFDictionary.h"
#include "QTDecompressionSession.h"
#include "QTMovie.h"
#include "QTMovieTask.h"
#include "QTMovieVisualContext.h"
#include "ScrollView.h"
#include "Settings.h"
#include "SoftLinking.h"
#include "TimeRanges.h"
#include "Timer.h"
#include <AssertMacros.h>
#include <CoreGraphics/CGAffineTransform.h>
#include <CoreGraphics/CGContext.h>
#include <QuartzCore/CATransform3D.h>
#include <Wininet.h>
#include <wtf/CurrentTime.h>
#include <wtf/HashSet.h>
#include <wtf/MainThread.h>
#include <wtf/MathExtras.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringHash.h>
#if USE(ACCELERATED_COMPOSITING)
#include "PlatformCALayer.h"
#include "WKCAImageQueue.h"
#endif
using namespace std;
namespace WebCore {
static CGImageRef CreateCGImageFromPixelBuffer(QTPixelBuffer buffer);
static bool requiredDllsAvailable();
SOFT_LINK_LIBRARY(Wininet)
SOFT_LINK(Wininet, InternetSetCookieExW, DWORD, WINAPI, (LPCWSTR lpszUrl, LPCWSTR lpszCookieName, LPCWSTR lpszCookieData, DWORD dwFlags, DWORD_PTR dwReserved), (lpszUrl, lpszCookieName, lpszCookieData, dwFlags, dwReserved))
// Interface declaration for MediaPlayerPrivateQuickTimeVisualContext's QTMovieClient aggregate
class MediaPlayerPrivateQuickTimeVisualContext::MovieClient : public QTMovieClient {
public:
MovieClient(MediaPlayerPrivateQuickTimeVisualContext* parent) : m_parent(parent) {}
virtual ~MovieClient() { m_parent = 0; }
virtual void movieEnded(QTMovie*);
virtual void movieLoadStateChanged(QTMovie*);
virtual void movieTimeChanged(QTMovie*);
private:
MediaPlayerPrivateQuickTimeVisualContext* m_parent;
};
#if USE(ACCELERATED_COMPOSITING)
class MediaPlayerPrivateQuickTimeVisualContext::LayerClient : public PlatformCALayerClient {
public:
LayerClient(MediaPlayerPrivateQuickTimeVisualContext* parent) : m_parent(parent) {}
virtual ~LayerClient() { m_parent = 0; }
private:
virtual void platformCALayerLayoutSublayersOfLayer(PlatformCALayer*);
virtual bool platformCALayerRespondsToLayoutChanges() const { return true; }
virtual void platformCALayerAnimationStarted(CFTimeInterval beginTime) { }
virtual GraphicsLayer::CompositingCoordinatesOrientation platformCALayerContentsOrientation() const { return GraphicsLayer::CompositingCoordinatesBottomUp; }
virtual void platformCALayerPaintContents(GraphicsContext&, const IntRect& inClip) { }
virtual bool platformCALayerShowDebugBorders() const { return false; }
virtual bool platformCALayerShowRepaintCounter() const { return false; }
virtual int platformCALayerIncrementRepaintCount() { return 0; }
virtual bool platformCALayerContentsOpaque() const { return false; }
virtual bool platformCALayerDrawsContent() const { return false; }
virtual void platformCALayerLayerDidDisplay(PlatformLayer*) { }
MediaPlayerPrivateQuickTimeVisualContext* m_parent;
};
void MediaPlayerPrivateQuickTimeVisualContext::LayerClient::platformCALayerLayoutSublayersOfLayer(PlatformCALayer* layer)
{
ASSERT(m_parent);
ASSERT(m_parent->m_transformLayer == layer);
FloatSize parentSize = layer->bounds().size();
FloatSize naturalSize = m_parent->naturalSize();
// Calculate the ratio of these two sizes and use that ratio to scale the qtVideoLayer:
FloatSize ratio(parentSize.width() / naturalSize.width(), parentSize.height() / naturalSize.height());
int videoWidth = 0;
int videoHeight = 0;
m_parent->m_movie->getNaturalSize(videoWidth, videoHeight);
FloatRect videoBounds(0, 0, videoWidth * ratio.width(), videoHeight * ratio.height());
FloatPoint3D videoAnchor = m_parent->m_qtVideoLayer->anchorPoint();
// Calculate the new position based on the parent's size:
FloatPoint position(parentSize.width() * 0.5 - videoBounds.width() * (0.5 - videoAnchor.x()),
parentSize.height() * 0.5 - videoBounds.height() * (0.5 - videoAnchor.y()));
m_parent->m_qtVideoLayer->setBounds(videoBounds);
m_parent->m_qtVideoLayer->setPosition(position);
}
#endif
class MediaPlayerPrivateQuickTimeVisualContext::VisualContextClient : public QTMovieVisualContextClient {
public:
VisualContextClient(MediaPlayerPrivateQuickTimeVisualContext* parent) : m_parent(parent) {}
virtual ~VisualContextClient() { m_parent = 0; }
void imageAvailableForTime(const QTCVTimeStamp*);
static void retrieveCurrentImageProc(void*);
private:
MediaPlayerPrivateQuickTimeVisualContext* m_parent;
};
PassOwnPtr<MediaPlayerPrivateInterface> MediaPlayerPrivateQuickTimeVisualContext::create(MediaPlayer* player)
{
return adoptPtr(new MediaPlayerPrivateQuickTimeVisualContext(player));
}
void MediaPlayerPrivateQuickTimeVisualContext::registerMediaEngine(MediaEngineRegistrar registrar)
{
if (isAvailable())
registrar(create, getSupportedTypes, supportsType, 0, 0, 0);
}
MediaPlayerPrivateQuickTimeVisualContext::MediaPlayerPrivateQuickTimeVisualContext(MediaPlayer* player)
: m_player(player)
, m_seekTo(-1)
, m_seekTimer(this, &MediaPlayerPrivateQuickTimeVisualContext::seekTimerFired)
, m_visualContextTimer(this, &MediaPlayerPrivateQuickTimeVisualContext::visualContextTimerFired)
, m_networkState(MediaPlayer::Empty)
, m_readyState(MediaPlayer::HaveNothing)
, m_enabledTrackCount(0)
, m_totalTrackCount(0)
, m_hasUnsupportedTracks(false)
, m_startedPlaying(false)
, m_isStreaming(false)
, m_visible(false)
, m_newFrameAvailable(false)
, m_movieClient(adoptPtr(new MediaPlayerPrivateQuickTimeVisualContext::MovieClient(this)))
#if USE(ACCELERATED_COMPOSITING)
, m_layerClient(adoptPtr(new MediaPlayerPrivateQuickTimeVisualContext::LayerClient(this)))
, m_movieTransform(CGAffineTransformIdentity)
#endif
, m_visualContextClient(adoptPtr(new MediaPlayerPrivateQuickTimeVisualContext::VisualContextClient(this)))
, m_delayingLoad(false)
, m_privateBrowsing(false)
, m_preload(MediaPlayer::Auto)
{
}
MediaPlayerPrivateQuickTimeVisualContext::~MediaPlayerPrivateQuickTimeVisualContext()
{
tearDownVideoRendering();
cancelCallOnMainThread(&VisualContextClient::retrieveCurrentImageProc, this);
}
bool MediaPlayerPrivateQuickTimeVisualContext::supportsFullscreen() const
{
#if USE(ACCELERATED_COMPOSITING)
Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument();
if (document && document->settings())
return document->settings()->acceleratedCompositingEnabled();
#endif
return false;
}
PlatformMedia MediaPlayerPrivateQuickTimeVisualContext::platformMedia() const
{
PlatformMedia p;
p.type = PlatformMedia::QTMovieVisualContextType;
p.media.qtMovieVisualContext = m_visualContext.get();
return p;
}
#if USE(ACCELERATED_COMPOSITING)
PlatformLayer* MediaPlayerPrivateQuickTimeVisualContext::platformLayer() const
{
return m_transformLayer ? m_transformLayer->platformLayer() : 0;
}
#endif
String MediaPlayerPrivateQuickTimeVisualContext::rfc2616DateStringFromTime(CFAbsoluteTime time)
{
static const char* const dayStrings[] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
static const char* const monthStrings[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
static const CFStringRef dateFormatString = CFSTR("%s, %02d %s %04d %02d:%02d:%02d GMT");
static CFTimeZoneRef gmtTimeZone;
if (!gmtTimeZone)
gmtTimeZone = CFTimeZoneCopyDefault();
CFGregorianDate dateValue = CFAbsoluteTimeGetGregorianDate(time, gmtTimeZone);
if (!CFGregorianDateIsValid(dateValue, kCFGregorianAllUnits))
return String();
time = CFGregorianDateGetAbsoluteTime(dateValue, gmtTimeZone);
SInt32 day = CFAbsoluteTimeGetDayOfWeek(time, 0);
RetainPtr<CFStringRef> dateCFString(AdoptCF, CFStringCreateWithFormat(0, 0, dateFormatString, dayStrings[day - 1], dateValue.day,
monthStrings[dateValue.month - 1], dateValue.year, dateValue.hour, dateValue.minute, (int)dateValue.second));
return dateCFString.get();
}
static void addCookieParam(StringBuilder& cookieBuilder, const String& name, const String& value)
{
if (name.isEmpty())
return;
// If this isn't the first parameter added, terminate the previous one.
if (cookieBuilder.length())
cookieBuilder.append("; ");
// Add parameter name, and value if there is one.
cookieBuilder.append(name);
if (!value.isEmpty()) {
cookieBuilder.append('=');
cookieBuilder.append(value);
}
}
void MediaPlayerPrivateQuickTimeVisualContext::setUpCookiesForQuickTime(const String& url)
{
// WebCore loaded the page with the movie URL with CFNetwork but QuickTime will
// use WinINet to download the movie, so we need to copy any cookies needed to
// download the movie into WinInet before asking QuickTime to open it.
Document* document = m_player->mediaPlayerClient()->mediaPlayerOwningDocument();
Frame* frame = document ? document->frame() : 0;
if (!frame || !frame->page() || !frame->page()->cookieEnabled())
return;
KURL movieURL = KURL(KURL(), url);
Vector<Cookie> documentCookies;
if (!getRawCookies(frame->document(), movieURL, documentCookies))
return;
for (size_t ndx = 0; ndx < documentCookies.size(); ndx++) {
const Cookie& cookie = documentCookies[ndx];
if (cookie.name.isEmpty())
continue;
// Build up the cookie string with as much information as we can get so WinINet
// knows what to do with it.
StringBuilder cookieBuilder;
addCookieParam(cookieBuilder, cookie.name, cookie.value);
addCookieParam(cookieBuilder, "path", cookie.path);
if (cookie.expires)
addCookieParam(cookieBuilder, "expires", rfc2616DateStringFromTime(cookie.expires));
if (cookie.httpOnly)
addCookieParam(cookieBuilder, "httpOnly", String());
cookieBuilder.append(';');
String cookieURL;
if (!cookie.domain.isEmpty()) {
StringBuilder urlBuilder;
urlBuilder.append(movieURL.protocol());
urlBuilder.append("://");
if (cookie.domain[0] == '.')
urlBuilder.append(cookie.domain.substring(1));
else
urlBuilder.append(cookie.domain);
if (cookie.path.length() > 1)
urlBuilder.append(cookie.path);
cookieURL = urlBuilder.toString();
} else
cookieURL = movieURL;
InternetSetCookieExW(cookieURL.charactersWithNullTermination(), 0, cookieBuilder.toString().charactersWithNullTermination(), 0, 0);
}
}
static void disableComponentsOnce()
{
static bool sComponentsDisabled = false;
if (sComponentsDisabled)
return;
sComponentsDisabled = true;
uint32_t componentsToDisable[][5] = {
{'eat ', 'TEXT', 'text', 0, 0},
{'eat ', 'TXT ', 'text', 0, 0},
{'eat ', 'utxt', 'text', 0, 0},
{'eat ', 'TEXT', 'tx3g', 0, 0},
};
for (size_t i = 0; i < WTF_ARRAY_LENGTH(componentsToDisable); ++i)
QTMovie::disableComponent(componentsToDisable[i]);
}
void MediaPlayerPrivateQuickTimeVisualContext::resumeLoad()
{
m_delayingLoad = false;
if (!m_movieURL.isEmpty())
loadInternal(m_movieURL);
}
void MediaPlayerPrivateQuickTimeVisualContext::load(const String& url)
{
m_movieURL = url;
if (m_preload == MediaPlayer::None) {
m_delayingLoad = true;
return;
}
loadInternal(url);
}
void MediaPlayerPrivateQuickTimeVisualContext::loadInternal(const String& url)
{
if (!QTMovie::initializeQuickTime()) {
// FIXME: is this the right error to return?
m_networkState = MediaPlayer::DecodeError;
m_player->networkStateChanged();
return;
}
disableComponentsOnce();
// Initialize the task timer.
MediaPlayerPrivateTaskTimer::initialize();
if (m_networkState != MediaPlayer::Loading) {
m_networkState = MediaPlayer::Loading;
m_player->networkStateChanged();
}
if (m_readyState != MediaPlayer::HaveNothing) {
m_readyState = MediaPlayer::HaveNothing;
m_player->readyStateChanged();
}
cancelSeek();
setUpCookiesForQuickTime(url);
m_movie = adoptRef(new QTMovie(m_movieClient.get()));
#if ENABLE(OFFLINE_WEB_APPLICATIONS)
Frame* frame = m_player->frameView() ? m_player->frameView()->frame() : 0;
ApplicationCacheHost* cacheHost = frame ? frame->loader()->documentLoader()->applicationCacheHost() : 0;
ApplicationCacheResource* resource = 0;
if (cacheHost && cacheHost->shouldLoadResourceFromApplicationCache(ResourceRequest(url), resource) && resource && !resource->path().isEmpty())
m_movie->load(resource->path().characters(), resource->path().length(), m_player->preservesPitch());
else
#endif
m_movie->load(url.characters(), url.length(), m_player->preservesPitch());
m_movie->setVolume(m_player->volume());
}
void MediaPlayerPrivateQuickTimeVisualContext::prepareToPlay()
{
if (!m_movie || m_delayingLoad)
resumeLoad();
}
void MediaPlayerPrivateQuickTimeVisualContext::play()
{
if (!m_movie)
return;
m_startedPlaying = true;
m_movie->play();
m_visualContextTimer.startRepeating(1.0 / 30);
}
void MediaPlayerPrivateQuickTimeVisualContext::pause()
{
if (!m_movie)
return;
m_startedPlaying = false;
m_movie->pause();
m_visualContextTimer.stop();
}
float MediaPlayerPrivateQuickTimeVisualContext::duration() const
{
if (!m_movie)
return 0;
return m_movie->duration();
}
float MediaPlayerPrivateQuickTimeVisualContext::currentTime() const
{
if (!m_movie)
return 0;
return m_movie->currentTime();
}
void MediaPlayerPrivateQuickTimeVisualContext::seek(float time)
{
cancelSeek();
if (!m_movie)
return;
if (time > duration())
time = duration();
m_seekTo = time;
if (maxTimeLoaded() >= m_seekTo)
doSeek();
else
m_seekTimer.start(0, 0.5f);
}
void MediaPlayerPrivateQuickTimeVisualContext::doSeek()
{
float oldRate = m_movie->rate();
if (oldRate)
m_movie->setRate(0);
m_movie->setCurrentTime(m_seekTo);
float timeAfterSeek = currentTime();
// restore playback only if not at end, othewise QTMovie will loop
if (oldRate && timeAfterSeek < duration())
m_movie->setRate(oldRate);
cancelSeek();
}
void MediaPlayerPrivateQuickTimeVisualContext::cancelSeek()
{
m_seekTo = -1;
m_seekTimer.stop();
}
void MediaPlayerPrivateQuickTimeVisualContext::seekTimerFired(Timer<MediaPlayerPrivateQuickTimeVisualContext>*)
{
if (!m_movie || !seeking() || currentTime() == m_seekTo) {
cancelSeek();
updateStates();
m_player->timeChanged();
return;
}
if (maxTimeLoaded() >= m_seekTo)
doSeek();
else {
MediaPlayer::NetworkState state = networkState();
if (state == MediaPlayer::Empty || state == MediaPlayer::Loaded) {
cancelSeek();
updateStates();
m_player->timeChanged();
}
}
}
bool MediaPlayerPrivateQuickTimeVisualContext::paused() const
{
if (!m_movie)
return true;
return (!m_movie->rate());
}
bool MediaPlayerPrivateQuickTimeVisualContext::seeking() const
{
if (!m_movie)
return false;
return m_seekTo >= 0;
}
IntSize MediaPlayerPrivateQuickTimeVisualContext::naturalSize() const
{
if (!m_movie)
return IntSize();
int width;
int height;
m_movie->getNaturalSize(width, height);
#if USE(ACCELERATED_COMPOSITING)
CGSize originalSize = {width, height};
CGSize transformedSize = CGSizeApplyAffineTransform(originalSize, m_movieTransform);
return IntSize(abs(transformedSize.width), abs(transformedSize.height));
#else
return IntSize(width, height);
#endif
}
bool MediaPlayerPrivateQuickTimeVisualContext::hasVideo() const
{
if (!m_movie)
return false;
return m_movie->hasVideo();
}
bool MediaPlayerPrivateQuickTimeVisualContext::hasAudio() const
{
if (!m_movie)
return false;
return m_movie->hasAudio();
}
void MediaPlayerPrivateQuickTimeVisualContext::setVolume(float volume)
{
if (!m_movie)
return;
m_movie->setVolume(volume);
}
void MediaPlayerPrivateQuickTimeVisualContext::setRate(float rate)
{
if (!m_movie)
return;
// Do not call setRate(...) unless we have started playing; otherwise
// QuickTime's VisualContext can get wedged waiting for a rate change
// call which will never come.
if (m_startedPlaying)
m_movie->setRate(rate);
}
void MediaPlayerPrivateQuickTimeVisualContext::setPreservesPitch(bool preservesPitch)
{
if (!m_movie)
return;
m_movie->setPreservesPitch(preservesPitch);
}
bool MediaPlayerPrivateQuickTimeVisualContext::hasClosedCaptions() const
{
if (!m_movie)
return false;
return m_movie->hasClosedCaptions();
}
void MediaPlayerPrivateQuickTimeVisualContext::setClosedCaptionsVisible(bool visible)
{
if (!m_movie)
return;
m_movie->setClosedCaptionsVisible(visible);
}
PassRefPtr<TimeRanges> MediaPlayerPrivateQuickTimeVisualContext::buffered() const
{
RefPtr<TimeRanges> timeRanges = TimeRanges::create();
float loaded = maxTimeLoaded();
// rtsp streams are not buffered
if (!m_isStreaming && loaded > 0)
timeRanges->add(0, loaded);
return timeRanges.release();
}
float MediaPlayerPrivateQuickTimeVisualContext::maxTimeSeekable() const
{
// infinite duration means live stream
return !isfinite(duration()) ? 0 : maxTimeLoaded();
}
float MediaPlayerPrivateQuickTimeVisualContext::maxTimeLoaded() const
{
if (!m_movie)
return 0;
return m_movie->maxTimeLoaded();
}
unsigned MediaPlayerPrivateQuickTimeVisualContext::bytesLoaded() const
{
if (!m_movie)
return 0;
float dur = duration();
float maxTime = maxTimeLoaded();
if (!dur)
return 0;
return totalBytes() * maxTime / dur;
}
unsigned MediaPlayerPrivateQuickTimeVisualContext::totalBytes() const
{
if (!m_movie)
return 0;
return m_movie->dataSize();
}
void MediaPlayerPrivateQuickTimeVisualContext::cancelLoad()
{
if (m_networkState < MediaPlayer::Loading || m_networkState == MediaPlayer::Loaded)
return;
tearDownVideoRendering();
// Cancel the load by destroying the movie.
m_movie.clear();
updateStates();
}
void MediaPlayerPrivateQuickTimeVisualContext::updateStates()
{
MediaPlayer::NetworkState oldNetworkState = m_networkState;
MediaPlayer::ReadyState oldReadyState = m_readyState;
long loadState = m_movie ? m_movie->loadState() : QTMovieLoadStateError;
if (loadState >= QTMovieLoadStateLoaded && m_readyState < MediaPlayer::HaveMetadata) {
m_movie->disableUnsupportedTracks(m_enabledTrackCount, m_totalTrackCount);
if (m_player->inMediaDocument()) {
if (!m_enabledTrackCount || m_enabledTrackCount != m_totalTrackCount) {
// This is a type of media that we do not handle directly with a <video>
// element, eg. QuickTime VR, a movie with a sprite track, etc. Tell the
// MediaPlayerClient that we won't support it.
sawUnsupportedTracks();
return;
}
} else if (!m_enabledTrackCount)
loadState = QTMovieLoadStateError;
}
// "Loaded" is reserved for fully buffered movies, never the case when streaming
if (loadState >= QTMovieLoadStateComplete && !m_isStreaming) {
m_networkState = MediaPlayer::Loaded;
m_readyState = MediaPlayer::HaveEnoughData;
} else if (loadState >= QTMovieLoadStatePlaythroughOK) {
m_readyState = MediaPlayer::HaveEnoughData;
} else if (loadState >= QTMovieLoadStatePlayable) {
// FIXME: This might not work correctly in streaming case, <rdar://problem/5693967>
m_readyState = currentTime() < maxTimeLoaded() ? MediaPlayer::HaveFutureData : MediaPlayer::HaveCurrentData;
} else if (loadState >= QTMovieLoadStateLoaded) {
m_readyState = MediaPlayer::HaveMetadata;
} else if (loadState > QTMovieLoadStateError) {
m_networkState = MediaPlayer::Loading;
m_readyState = MediaPlayer::HaveNothing;
} else {
if (m_player->inMediaDocument()) {
// Something went wrong in the loading of media within a standalone file.
// This can occur with chained ref movies that eventually resolve to a
// file we don't support.
sawUnsupportedTracks();
return;
}
float loaded = maxTimeLoaded();
if (!loaded)
m_readyState = MediaPlayer::HaveNothing;
if (!m_enabledTrackCount)
m_networkState = MediaPlayer::FormatError;
else {
// FIXME: We should differentiate between load/network errors and decode errors <rdar://problem/5605692>
if (loaded > 0)
m_networkState = MediaPlayer::DecodeError;
else
m_readyState = MediaPlayer::HaveNothing;
}
}
if (isReadyForRendering() && !hasSetUpVideoRendering())
setUpVideoRendering();
if (seeking())
m_readyState = MediaPlayer::HaveNothing;
if (m_networkState != oldNetworkState)
m_player->networkStateChanged();
if (m_readyState != oldReadyState)
m_player->readyStateChanged();
}
bool MediaPlayerPrivateQuickTimeVisualContext::isReadyForRendering() const
{
return m_readyState >= MediaPlayer::HaveMetadata && m_player->visible();
}
void MediaPlayerPrivateQuickTimeVisualContext::sawUnsupportedTracks()
{
m_movie->setDisabled(true);
m_hasUnsupportedTracks = true;
m_player->mediaPlayerClient()->mediaPlayerSawUnsupportedTracks(m_player);
}
void MediaPlayerPrivateQuickTimeVisualContext::didEnd()
{
if (m_hasUnsupportedTracks)
return;
m_startedPlaying = false;
updateStates();
m_player->timeChanged();
}
void MediaPlayerPrivateQuickTimeVisualContext::setSize(const IntSize& size)
{
if (m_hasUnsupportedTracks || !m_movie || m_size == size)
return;
m_size = size;
}
void MediaPlayerPrivateQuickTimeVisualContext::setVisible(bool visible)
{
if (m_hasUnsupportedTracks || !m_movie || m_visible == visible)
return;
m_visible = visible;
if (m_visible) {
if (isReadyForRendering())
setUpVideoRendering();
} else
tearDownVideoRendering();
}
void MediaPlayerPrivateQuickTimeVisualContext::paint(GraphicsContext* p, const IntRect& r)
{
MediaRenderingMode currentMode = currentRenderingMode();
if (currentMode == MediaRenderingNone)
return;
if (currentMode == MediaRenderingSoftwareRenderer && !m_visualContext)
return;
QTPixelBuffer buffer = m_visualContext->imageForTime(0);
if (buffer.pixelBufferRef()) {
#if USE(ACCELERATED_COMPOSITING)
if (m_qtVideoLayer) {
// We are probably being asked to render the video into a canvas, but
// there's a good chance the QTPixelBuffer is not ARGB and thus can't be
// drawn using CG. If so, fire up an ICMDecompressionSession and convert
// the current frame into something which can be rendered by CG.
if (!buffer.pixelFormatIs32ARGB() && !buffer.pixelFormatIs32BGRA()) {
// The decompression session will only decompress a specific pixelFormat
// at a specific width and height; if these differ, the session must be
// recreated with the new parameters.
if (!m_decompressionSession || !m_decompressionSession->canDecompress(buffer))
m_decompressionSession = QTDecompressionSession::create(buffer.pixelFormatType(), buffer.width(), buffer.height());
buffer = m_decompressionSession->decompress(buffer);
}
}
#endif
CGImageRef image = CreateCGImageFromPixelBuffer(buffer);
CGContextRef context = p->platformContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, r.x(), r.y());
CGContextTranslateCTM(context, 0, r.height());
CGContextScaleCTM(context, 1, -1);
CGContextDrawImage(context, CGRectMake(0, 0, r.width(), r.height()), image);
CGContextRestoreGState(context);
CGImageRelease(image);
}
paintCompleted(*p, r);
}
void MediaPlayerPrivateQuickTimeVisualContext::paintCompleted(GraphicsContext& context, const IntRect& rect)
{
m_newFrameAvailable = false;
}
void MediaPlayerPrivateQuickTimeVisualContext::VisualContextClient::retrieveCurrentImageProc(void* refcon)
{
static_cast<MediaPlayerPrivateQuickTimeVisualContext*>(refcon)->retrieveCurrentImage();
}
void MediaPlayerPrivateQuickTimeVisualContext::VisualContextClient::imageAvailableForTime(const QTCVTimeStamp* timeStamp)
{
// This call may come in on another thread, so marshall to the main thread first:
callOnMainThread(&retrieveCurrentImageProc, m_parent);
// callOnMainThread must be paired with cancelCallOnMainThread in the destructor,
// in case this object is deleted before the main thread request is handled.
}
void MediaPlayerPrivateQuickTimeVisualContext::visualContextTimerFired(Timer<MediaPlayerPrivateQuickTimeVisualContext>*)
{
if (m_visualContext && m_visualContext->isImageAvailableForTime(0))
retrieveCurrentImage();
}
static CFDictionaryRef QTCFDictionaryCreateWithDataCallback(CFAllocatorRef allocator, const UInt8* bytes, CFIndex length)
{
RetainPtr<CFDataRef> data(AdoptCF, CFDataCreateWithBytesNoCopy(allocator, bytes, length, kCFAllocatorNull));
if (!data)
return 0;
return reinterpret_cast<CFDictionaryRef>(CFPropertyListCreateFromXMLData(allocator, data.get(), kCFPropertyListImmutable, 0));
}
static CGImageRef CreateCGImageFromPixelBuffer(QTPixelBuffer buffer)
{
#if USE(ACCELERATED_COMPOSITING)
CGDataProviderRef provider = 0;
CGColorSpaceRef colorSpace = 0;
CGImageRef image = 0;
size_t bitsPerComponent = 0;
size_t bitsPerPixel = 0;
CGImageAlphaInfo alphaInfo = kCGImageAlphaNone;
if (buffer.pixelFormatIs32BGRA()) {
bitsPerComponent = 8;
bitsPerPixel = 32;
alphaInfo = (CGImageAlphaInfo)(kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little);
} else if (buffer.pixelFormatIs32ARGB()) {
bitsPerComponent = 8;
bitsPerPixel = 32;
alphaInfo = (CGImageAlphaInfo)(kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Big);
} else {
// All other pixel formats are currently unsupported:
ASSERT_NOT_REACHED();
}
CGDataProviderDirectAccessCallbacks callbacks = {
&QTPixelBuffer::dataProviderGetBytePointerCallback,
&QTPixelBuffer::dataProviderReleaseBytePointerCallback,
&QTPixelBuffer::dataProviderGetBytesAtPositionCallback,
&QTPixelBuffer::dataProviderReleaseInfoCallback,
};
// Colorspace should be device, so that Quartz does not have to do an extra render.
colorSpace = CGColorSpaceCreateDeviceRGB();
require(colorSpace, Bail);
provider = CGDataProviderCreateDirectAccess(buffer.pixelBufferRef(), buffer.dataSize(), &callbacks);
require(provider, Bail);
// CGDataProvider does not retain the buffer, but it will release it later, so do an extra retain here:
QTPixelBuffer::retainCallback(buffer.pixelBufferRef());
image = CGImageCreate(buffer.width(), buffer.height(), bitsPerComponent, bitsPerPixel, buffer.bytesPerRow(), colorSpace, alphaInfo, provider, 0, false, kCGRenderingIntentDefault);
Bail:
// Once the image is created we can release our reference to the provider and the colorspace, they are retained by the image
if (provider)
CGDataProviderRelease(provider);
if (colorSpace)
CGColorSpaceRelease(colorSpace);
return image;
#else
return 0;
#endif
}
void MediaPlayerPrivateQuickTimeVisualContext::retrieveCurrentImage()
{
if (!m_visualContext)
return;
#if USE(ACCELERATED_COMPOSITING)
if (m_qtVideoLayer) {
QTPixelBuffer buffer = m_visualContext->imageForTime(0);
if (!buffer.pixelBufferRef())
return;
PlatformCALayer* layer = m_qtVideoLayer.get();
if (!buffer.lockBaseAddress()) {
if (requiredDllsAvailable()) {
if (!m_imageQueue) {
m_imageQueue = adoptPtr(new WKCAImageQueue(buffer.width(), buffer.height(), 30));
m_imageQueue->setFlags(WKCAImageQueue::Fill, WKCAImageQueue::Fill);
layer->setContents(m_imageQueue->get());
}
// Debug QuickTime links against a non-Debug version of CoreFoundation, so the
// CFDictionary attached to the CVPixelBuffer cannot be directly passed on into the
// CAImageQueue without being converted to a non-Debug CFDictionary. Additionally,
// old versions of QuickTime used a non-AAS CoreFoundation, so the types are not
// interchangable even in the release case.
RetainPtr<CFDictionaryRef> attachments(AdoptCF, QTCFDictionaryCreateCopyWithDataCallback(kCFAllocatorDefault, buffer.attachments(), &QTCFDictionaryCreateWithDataCallback));
CFTimeInterval imageTime = QTMovieVisualContext::currentHostTime();
m_imageQueue->collect();
uint64_t imageId = m_imageQueue->registerPixelBuffer(buffer.baseAddress(), buffer.dataSize(), buffer.bytesPerRow(), buffer.width(), buffer.height(), buffer.pixelFormatType(), attachments.get(), 0);
if (m_imageQueue->insertImage(imageTime, WKCAImageQueue::Buffer, imageId, WKCAImageQueue::Opaque | WKCAImageQueue::Flush, &QTPixelBuffer::imageQueueReleaseCallback, buffer.pixelBufferRef())) {
// Retain the buffer one extra time so it doesn't dissappear before CAImageQueue decides to release it:
QTPixelBuffer::retainCallback(buffer.pixelBufferRef());
}
} else {
CGImageRef image = CreateCGImageFromPixelBuffer(buffer);
layer->setContents(image);
CGImageRelease(image);
}
buffer.unlockBaseAddress();
layer->setNeedsCommit();
}
} else
#endif
m_player->repaint();
m_visualContext->task();
}
static HashSet<String> mimeTypeCache()
{
DEFINE_STATIC_LOCAL(HashSet<String>, typeCache, ());
static bool typeListInitialized = false;
if (!typeListInitialized) {
unsigned count = QTMovie::countSupportedTypes();
for (unsigned n = 0; n < count; n++) {
const UChar* character;
unsigned len;
QTMovie::getSupportedType(n, character, len);
if (len)
typeCache.add(String(character, len));
}
typeListInitialized = true;
}
return typeCache;
}
static CFStringRef createVersionStringFromModuleName(LPCWSTR moduleName)
{
HMODULE module = GetModuleHandleW(moduleName);
if (!module)
return 0;
wchar_t filePath[MAX_PATH] = {0};
if (!GetModuleFileNameW(module, filePath, MAX_PATH))
return 0;
DWORD versionInfoSize = GetFileVersionInfoSizeW(filePath, 0);
if (!versionInfoSize)
return 0;
CFStringRef versionString = 0;
void* versionInfo = calloc(versionInfoSize, sizeof(char));
if (GetFileVersionInfo(filePath, 0, versionInfoSize, versionInfo)) {
VS_FIXEDFILEINFO* fileInfo = 0;
UINT fileInfoLength = 0;
if (VerQueryValueW(versionInfo, L"\\", reinterpret_cast<LPVOID*>(&fileInfo), &fileInfoLength)) {
versionString = CFStringCreateWithFormat(kCFAllocatorDefault, 0, CFSTR("%d.%d.%d.%d"),
HIWORD(fileInfo->dwFileVersionMS), LOWORD(fileInfo->dwFileVersionMS),
HIWORD(fileInfo->dwFileVersionLS), LOWORD(fileInfo->dwFileVersionLS));
}
}
free(versionInfo);
return versionString;
}
static bool requiredDllsAvailable()
{
static bool s_prerequisitesChecked = false;
static bool s_prerequisitesSatisfied;
static const CFStringRef kMinQuartzCoreVersion = CFSTR("1.0.42.0");
static const CFStringRef kMinCoreVideoVersion = CFSTR("1.0.1.0");
if (s_prerequisitesChecked)
return s_prerequisitesSatisfied;
s_prerequisitesChecked = true;
s_prerequisitesSatisfied = false;
CFStringRef quartzCoreString = createVersionStringFromModuleName(L"QuartzCore");
if (!quartzCoreString)
quartzCoreString = createVersionStringFromModuleName(L"QuartzCore_debug");
CFStringRef coreVideoString = createVersionStringFromModuleName(L"CoreVideo");
if (!coreVideoString)
coreVideoString = createVersionStringFromModuleName(L"CoreVideo_debug");
s_prerequisitesSatisfied = (quartzCoreString && coreVideoString
&& CFStringCompare(quartzCoreString, kMinQuartzCoreVersion, kCFCompareNumerically) != kCFCompareLessThan
&& CFStringCompare(coreVideoString, kMinCoreVideoVersion, kCFCompareNumerically) != kCFCompareLessThan);
if (quartzCoreString)
CFRelease(quartzCoreString);
if (coreVideoString)
CFRelease(coreVideoString);
return s_prerequisitesSatisfied;
}
void MediaPlayerPrivateQuickTimeVisualContext::getSupportedTypes(HashSet<String>& types)
{
types = mimeTypeCache();
}
bool MediaPlayerPrivateQuickTimeVisualContext::isAvailable()
{
return QTMovie::initializeQuickTime();
}
MediaPlayer::SupportsType MediaPlayerPrivateQuickTimeVisualContext::supportsType(const String& type, const String& codecs)
{
// only return "IsSupported" if there is no codecs parameter for now as there is no way to ask QT if it supports an
// extended MIME type
return mimeTypeCache().contains(type) ? (codecs.isEmpty() ? MediaPlayer::MayBeSupported : MediaPlayer::IsSupported) : MediaPlayer::IsNotSupported;
}
void MediaPlayerPrivateQuickTimeVisualContext::MovieClient::movieEnded(QTMovie* movie)
{
if (m_parent->m_hasUnsupportedTracks)
return;
m_parent->m_visualContextTimer.stop();
ASSERT(m_parent->m_movie.get() == movie);
m_parent->didEnd();
}
void MediaPlayerPrivateQuickTimeVisualContext::MovieClient::movieLoadStateChanged(QTMovie* movie)
{
if (m_parent->m_hasUnsupportedTracks)
return;
ASSERT(m_parent->m_movie.get() == movie);
m_parent->updateStates();
}
void MediaPlayerPrivateQuickTimeVisualContext::MovieClient::movieTimeChanged(QTMovie* movie)
{
if (m_parent->m_hasUnsupportedTracks)
return;
ASSERT(m_parent->m_movie.get() == movie);
m_parent->updateStates();
m_parent->m_player->timeChanged();
}
bool MediaPlayerPrivateQuickTimeVisualContext::hasSingleSecurityOrigin() const
{
// We tell quicktime to disallow resources that come from different origins
// so we all media is single origin.
return true;
}
void MediaPlayerPrivateQuickTimeVisualContext::setPreload(MediaPlayer::Preload preload)
{
m_preload = preload;
if (m_delayingLoad && m_preload != MediaPlayer::None)
resumeLoad();
}
float MediaPlayerPrivateQuickTimeVisualContext::mediaTimeForTimeValue(float timeValue) const
{
long timeScale;
if (m_readyState < MediaPlayer::HaveMetadata || !(timeScale = m_movie->timeScale()))
return timeValue;
long mediaTimeValue = lroundf(timeValue * timeScale);
return static_cast<float>(mediaTimeValue) / timeScale;
}
MediaPlayerPrivateQuickTimeVisualContext::MediaRenderingMode MediaPlayerPrivateQuickTimeVisualContext::currentRenderingMode() const
{
if (!m_movie)
return MediaRenderingNone;
#if USE(ACCELERATED_COMPOSITING)
if (m_qtVideoLayer)
return MediaRenderingMovieLayer;
#endif
return m_visualContext ? MediaRenderingSoftwareRenderer : MediaRenderingNone;
}
MediaPlayerPrivateQuickTimeVisualContext::MediaRenderingMode MediaPlayerPrivateQuickTimeVisualContext::preferredRenderingMode() const
{
if (!m_player->frameView() || !m_movie)
return MediaRenderingNone;
#if USE(ACCELERATED_COMPOSITING)
if (supportsAcceleratedRendering() && m_player->mediaPlayerClient()->mediaPlayerRenderingCanBeAccelerated(m_player))
return MediaRenderingMovieLayer;
#endif
return MediaRenderingSoftwareRenderer;
}
void MediaPlayerPrivateQuickTimeVisualContext::setUpVideoRendering()
{
MediaRenderingMode currentMode = currentRenderingMode();
MediaRenderingMode preferredMode = preferredRenderingMode();
#if !USE(ACCELERATED_COMPOSITING)
ASSERT(preferredMode != MediaRenderingMovieLayer);
#endif
if (currentMode == preferredMode && currentMode != MediaRenderingNone)
return;
if (currentMode != MediaRenderingNone)
tearDownVideoRendering();
if (preferredMode == MediaRenderingMovieLayer)
createLayerForMovie();
#if USE(ACCELERATED_COMPOSITING)
if (currentMode == MediaRenderingMovieLayer || preferredMode == MediaRenderingMovieLayer)
m_player->mediaPlayerClient()->mediaPlayerRenderingModeChanged(m_player);
#endif
QTPixelBuffer::Type contextType = requiredDllsAvailable() && preferredMode == MediaRenderingMovieLayer ? QTPixelBuffer::ConfigureForCAImageQueue : QTPixelBuffer::ConfigureForCGImage;
m_visualContext = QTMovieVisualContext::create(m_visualContextClient.get(), contextType);
m_visualContext->setMovie(m_movie.get());
}
void MediaPlayerPrivateQuickTimeVisualContext::tearDownVideoRendering()
{
#if USE(ACCELERATED_COMPOSITING)
if (m_qtVideoLayer)
destroyLayerForMovie();
#endif
m_visualContext = 0;
}
bool MediaPlayerPrivateQuickTimeVisualContext::hasSetUpVideoRendering() const
{
#if USE(ACCELERATED_COMPOSITING)
return m_qtVideoLayer || (currentRenderingMode() != MediaRenderingMovieLayer && m_visualContext);
#else
return true;
#endif
}
void MediaPlayerPrivateQuickTimeVisualContext::retrieveAndResetMovieTransform()
{
#if USE(ACCELERATED_COMPOSITING)
// First things first, reset the total movie transform so that
// we can bail out early:
m_movieTransform = CGAffineTransformIdentity;
if (!m_movie || !m_movie->hasVideo())
return;
// This trick will only work on movies with a single video track,
// so bail out early if the video contains more than one (or zero)
// video tracks.
QTTrackArray videoTracks = m_movie->videoTracks();
if (videoTracks.size() != 1)
return;
QTTrack* track = videoTracks[0].get();
ASSERT(track);
CGAffineTransform movieTransform = m_movie->getTransform();
if (!CGAffineTransformEqualToTransform(movieTransform, CGAffineTransformIdentity))
m_movie->resetTransform();
CGAffineTransform trackTransform = track->getTransform();
if (!CGAffineTransformEqualToTransform(trackTransform, CGAffineTransformIdentity))
track->resetTransform();
// Multiply the two transforms together, taking care to
// do so in the correct order, track * movie = final:
m_movieTransform = CGAffineTransformConcat(trackTransform, movieTransform);
#endif
}
void MediaPlayerPrivateQuickTimeVisualContext::createLayerForMovie()
{
#if USE(ACCELERATED_COMPOSITING)
ASSERT(supportsAcceleratedRendering());
if (!m_movie || m_qtVideoLayer)
return;
// Create a PlatformCALayer which will transform the contents of the video layer
// which is in m_qtVideoLayer.
m_transformLayer = PlatformCALayer::create(PlatformCALayer::LayerTypeLayer, m_layerClient.get());
if (!m_transformLayer)
return;
// Mark the layer as anchored in the top left.
m_transformLayer->setAnchorPoint(FloatPoint3D());
m_qtVideoLayer = PlatformCALayer::create(PlatformCALayer::LayerTypeLayer, 0);
if (!m_qtVideoLayer)
return;
if (CGAffineTransformEqualToTransform(m_movieTransform, CGAffineTransformIdentity))
retrieveAndResetMovieTransform();
CGAffineTransform t = m_movieTransform;
// Remove the translation portion of the transform, since we will always rotate about
// the layer's center point. In our limited use-case (a single video track), this is
// safe:
t.tx = t.ty = 0;
m_qtVideoLayer->setTransform(CATransform3DMakeAffineTransform(t));
#ifndef NDEBUG
m_qtVideoLayer->setName("Video layer");
#endif
m_transformLayer->appendSublayer(m_qtVideoLayer.get());
m_transformLayer->setNeedsLayout();
// The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration().
#endif
// Fill the newly created layer with image data, so we're not looking at
// an empty layer until the next time a new image is available, which could
// be a long time if we're paused.
if (m_visualContext)
retrieveCurrentImage();
}
void MediaPlayerPrivateQuickTimeVisualContext::destroyLayerForMovie()
{
#if USE(ACCELERATED_COMPOSITING)
if (m_qtVideoLayer) {
m_qtVideoLayer->removeFromSuperlayer();
m_qtVideoLayer = 0;
}
if (m_transformLayer)
m_transformLayer = 0;
if (m_imageQueue)
m_imageQueue = nullptr;
#endif
}
#if USE(ACCELERATED_COMPOSITING)
bool MediaPlayerPrivateQuickTimeVisualContext::supportsAcceleratedRendering() const
{
return isReadyForRendering();
}
void MediaPlayerPrivateQuickTimeVisualContext::acceleratedRenderingStateChanged()
{
// Set up or change the rendering path if necessary.
setUpVideoRendering();
}
void MediaPlayerPrivateQuickTimeVisualContext::setPrivateBrowsingMode(bool privateBrowsing)
{
m_privateBrowsing = privateBrowsing;
if (m_movie)
m_movie->setPrivateBrowsingMode(m_privateBrowsing);
}
#endif
}
#endif
| [
"ariya.hidayat@gmail.com"
] | ariya.hidayat@gmail.com |
d98efbec5296d10dab3bd9501b7c859fd5c9949a | 89d1563ba49502f20d1b0a2e531b9b93ba672b3d | /Network/X/Src/InputSystem.cpp | 3f8ff3be7592b14a40a7928deeedad374f3c8852 | [] | no_license | TyLauriente/Networking | 55f3f3392360882f40f06fbc60e325b3299b6bd1 | 83d88a29dd9f9cfe14ce7c9d377e84cbb5f6e16f | refs/heads/master | 2020-07-30T02:01:26.869261 | 2018-12-15T22:14:07 | 2018-12-15T22:14:07 | 210,048,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,295 | cpp | //====================================================================================================
// Filename: InputSystem.cpp
// Created by: Peter Chan
//====================================================================================================
#include "Precompiled.h"
#include "InputSystem.h"
using namespace X;
namespace
{
InputSystem* sInputSystem = nullptr;
WindowMessageHandler sPreviousWndProc = 0;
void ClipToWindow(HWND window)
{
RECT rect;
GetClientRect(window, &rect);
POINT ul;
ul.x = rect.left;
ul.y = rect.top;
POINT lr;
lr.x = rect.right;
lr.y = rect.bottom;
MapWindowPoints(window, nullptr, &ul, 1);
MapWindowPoints(window, nullptr, &lr, 1);
rect.left = ul.x;
rect.top = ul.y;
rect.right = lr.x;
rect.bottom = lr.y;
ClipCursor(&rect);
}
}
BOOL CALLBACK X::EnumGamePadCallback(const DIDEVICEINSTANCE* pDIDeviceInstance, VOID* pContext)
{
// Obtain an interface to the enumerated joystick
InputSystem* inputSystem = static_cast<InputSystem*>(pContext);
IDirectInput8* pDI = inputSystem->mDirectInput;
IDirectInputDevice8** gamePad = &(inputSystem->mGamePadDevice);
if (FAILED(pDI->CreateDevice(pDIDeviceInstance->guidInstance, gamePad, nullptr)))
{
XLOG("[InputSystem] Failed to create game pad device.");
}
return DIENUM_STOP;
}
LRESULT CALLBACK X::InputSystemMessageHandler(HWND window, UINT message, WPARAM wParam, LPARAM lParam)
{
if (sInputSystem == nullptr)
{
return sPreviousWndProc(window, message, wParam, lParam);
}
switch (message)
{
case WM_ACTIVATEAPP:
{
if (wParam == TRUE)
{
SetCapture(window);
}
else
{
sInputSystem->mMouseLeftEdge = false;
sInputSystem->mMouseRightEdge = false;
sInputSystem->mMouseTopEdge = false;
sInputSystem->mMouseBottomEdge = false;
ReleaseCapture();
}
break;
}
case WM_LBUTTONDOWN:
{
sInputSystem->mCurrMouseButtons[0] = true;
break;
}
case WM_LBUTTONUP:
{
sInputSystem->mCurrMouseButtons[0] = false;
break;
}
case WM_RBUTTONDOWN:
{
sInputSystem->mCurrMouseButtons[1] = true;
break;
}
case WM_RBUTTONUP:
{
sInputSystem->mCurrMouseButtons[1] = false;
break;
}
case WM_MBUTTONDOWN:
{
sInputSystem->mCurrMouseButtons[2] = true;
break;
}
case WM_MBUTTONUP:
{
sInputSystem->mCurrMouseButtons[2] = false;
break;
}
case WM_MOUSEWHEEL:
{
sInputSystem->mMouseWheel += GET_WHEEL_DELTA_WPARAM(wParam);
break;
}
case WM_MOUSEMOVE:
{
int mouseX = (signed short)(lParam);
int mouseY = (signed short)(lParam >> 16);
sInputSystem->mCurrMouseX = mouseX;
sInputSystem->mCurrMouseY = mouseY;
if (sInputSystem->mPrevMouseX == -1)
{
sInputSystem->mPrevMouseX = mouseX;
sInputSystem->mPrevMouseY = mouseY;
}
RECT rect;
GetClientRect(window, &rect);
sInputSystem->mMouseLeftEdge = mouseX <= rect.left;
sInputSystem->mMouseRightEdge = mouseX + 1 >= rect.right;
sInputSystem->mMouseTopEdge = mouseY <= rect.top;
sInputSystem->mMouseBottomEdge = mouseY + 1 >= rect.bottom;
break;
}
case WM_KEYDOWN:
{
if (wParam < 256)
{
sInputSystem->mCurrKeys[wParam] = true;
}
break;
}
case WM_KEYUP:
{
if (wParam < 256)
{
sInputSystem->mCurrKeys[wParam] = false;
}
break;
}
}
return sPreviousWndProc(window, message, wParam, lParam);
}
void InputSystem::StaticInitialize(HWND window)
{
XASSERT(sInputSystem == nullptr, "[InputSystem] System already initialized!");
sInputSystem = new InputSystem();
sInputSystem->Initialize(window);
}
void InputSystem::StaticTerminate()
{
if (sInputSystem != nullptr)
{
sInputSystem->Terminate();
SafeDelete(sInputSystem);
}
}
InputSystem* InputSystem::Get()
{
XASSERT(sInputSystem != nullptr, "[InputSystem] No system registered.");
return sInputSystem;
}
InputSystem::InputSystem()
: mWindow(0)
, mDirectInput(nullptr)
, mGamePadDevice(nullptr)
, mClipMouseToWindow(false)
, mCurrMouseX(-1)
, mCurrMouseY(-1)
, mPrevMouseX(-1)
, mPrevMouseY(-1)
, mMouseMoveX(0)
, mMouseMoveY(0)
, mMouseLeftEdge(false)
, mMouseRightEdge(false)
, mMouseTopEdge(false)
, mMouseBottomEdge(false)
, mInitialized(false)
{
ZeroMemory(&mCurrKeys, sizeof(mCurrKeys));
ZeroMemory(&mPrevKeys, sizeof(mPrevKeys));
ZeroMemory(&mPressedKeys, sizeof(mPressedKeys));
ZeroMemory(&mCurrMouseButtons, sizeof(mCurrMouseButtons));
ZeroMemory(&mPrevMouseButtons, sizeof(mPrevMouseButtons));
ZeroMemory(&mPressedMouseButtons, sizeof(mPressedMouseButtons));
ZeroMemory(&mCurrGamePadState, sizeof(DIJOYSTATE));
ZeroMemory(&mPrevGamePadState, sizeof(DIJOYSTATE));
}
//----------------------------------------------------------------------------------------------------
InputSystem::~InputSystem()
{
XASSERT(!mInitialized, "[InputSystem] Terminate() must be called to clean up!");
}
//----------------------------------------------------------------------------------------------------
void InputSystem::Initialize(HWND window)
{
// Check if we have already initialized the system
if (mInitialized)
{
XLOG("[InputSystem] System already initialized.");
return;
}
XLOG("[InputSystem] Initializing...");
// Hook application to window's procedure
mWindow = window;
sPreviousWndProc = (WindowMessageHandler)GetWindowLongPtrA(window, GWLP_WNDPROC);
SetWindowLongPtrA(window, GWLP_WNDPROC, (LONG_PTR)InputSystemMessageHandler);
// Obtain an interface to DirectInput
HRESULT hr = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&mDirectInput, nullptr);
XASSERT(SUCCEEDED(hr), "[InputSystem] Failed to create DirectInput object.");
//----------------------------------------------------------------------------------------------------
// Enumerate for game pad device
if (FAILED(mDirectInput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumGamePadCallback, this, DIEDFL_ATTACHEDONLY)))
{
XLOG("[InputSystem] Failed to enumerate for game pad devices.");
}
// Check if we have a game pad detected
if (mGamePadDevice != nullptr)
{
// Set the game pad data format
hr = mGamePadDevice->SetDataFormat(&c_dfDIJoystick);
XASSERT(SUCCEEDED(hr), "[InputSystem] Failed to set game pad data format.");
// Set the game pad cooperative level
hr = mGamePadDevice->SetCooperativeLevel(window, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
XASSERT(SUCCEEDED(hr), "[InputSystem] Failed to set game pad cooperative level.");
// Acquire the game pad device
hr = mGamePadDevice->Acquire();
XASSERT(SUCCEEDED(hr), "[InputSystem] Failed to acquire game pad device.");
}
else
{
XLOG("[InputSystem] No game pad attached.");
}
// Set flag
mInitialized = true;
XLOG("[InputSystem] System initialized.");
}
//----------------------------------------------------------------------------------------------------
void InputSystem::Terminate()
{
// Check if we have already terminated the system
if (!mInitialized)
{
XLOG("[InputSystem] System already terminated.");
return;
}
XLOG("[InputSystem] Terminating...");
// Release devices
if (mGamePadDevice != nullptr)
{
mGamePadDevice->Unacquire();
mGamePadDevice->Release();
mGamePadDevice = nullptr;
}
SafeRelease(mDirectInput);
// Restore original window's procedure
SetWindowLongPtrA(mWindow, GWLP_WNDPROC, (LONG_PTR)sPreviousWndProc);
mWindow = nullptr;
// Set flag
mInitialized = false;
XLOG("[InputSystem] System terminated.");
}
//----------------------------------------------------------------------------------------------------
void InputSystem::Update()
{
XASSERT(mInitialized, "[InputSystem] System not initialized.");
// Store the previous keyboard state
for (int i = 0; i < 512; ++i)
{
mPressedKeys[i] = !mPrevKeys[i] && mCurrKeys[i];
}
memcpy(mPrevKeys, mCurrKeys, sizeof(mCurrKeys));
// Update mouse movement
mMouseMoveX = mCurrMouseX - mPrevMouseX;
mMouseMoveY = mCurrMouseY - mPrevMouseY;
mPrevMouseX = mCurrMouseX;
mPrevMouseY = mCurrMouseY;
// Store the previous mouse state
for (int i = 0; i < 3; ++i)
{
mPressedMouseButtons[i] = !mPrevMouseButtons[i] && mCurrMouseButtons[i];
}
memcpy(mPrevMouseButtons, mCurrMouseButtons, sizeof(mCurrMouseButtons));
// Update game pad
if (mGamePadDevice != nullptr)
{
UpdateGamePad();
}
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsKeyDown(uint32_t key) const
{
return mCurrKeys[key];
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsKeyPressed(uint32_t key) const
{
return mPressedKeys[key];
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsMouseDown(uint32_t button) const
{
return mCurrMouseButtons[button];
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsMousePressed(uint32_t button) const
{
return mPressedMouseButtons[button];
}
//----------------------------------------------------------------------------------------------------
int InputSystem::GetMouseMoveX() const
{
return mMouseMoveX;
}
//----------------------------------------------------------------------------------------------------
int InputSystem::GetMouseMoveY() const
{
return mMouseMoveY;
}
//----------------------------------------------------------------------------------------------------
int InputSystem::GetMouseMoveZ() const
{
return mMouseWheel;
}
//----------------------------------------------------------------------------------------------------
int InputSystem::GetMouseScreenX() const
{
return mCurrMouseX;
}
//----------------------------------------------------------------------------------------------------
int InputSystem::GetMouseScreenY() const
{
return mCurrMouseY;
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsMouseLeftEdge() const
{
return mMouseLeftEdge;
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsMouseRightEdge() const
{
return mMouseRightEdge;
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsMouseTopEdge() const
{
return mMouseTopEdge;
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsMouseBottomEdge() const
{
return mMouseBottomEdge;
}
//----------------------------------------------------------------------------------------------------
void InputSystem::ShowSystemCursor(bool show)
{
ShowCursor(show);
}
//----------------------------------------------------------------------------------------------------
void InputSystem::SetMouseClipToWindow(bool clip)
{
mClipMouseToWindow = clip;
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsMouseClipToWindow() const
{
return mClipMouseToWindow;
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsGamePadButtonDown(uint32_t button) const
{
return (mCurrGamePadState.rgbButtons[button] & 0x80) != 0;
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsGamePadButtonPressed(uint32_t button) const
{
const bool currState = (mCurrGamePadState.rgbButtons[button] & 0x80) != 0;
const bool prevState = (mPrevGamePadState.rgbButtons[button] & 0x80) != 0;
return !prevState && currState;
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsDPadUp() const
{
const bool hasGamePad = (mGamePadDevice != nullptr);
return hasGamePad && (mCurrGamePadState.rgdwPOV[0] == 0);
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsDPadDown() const
{
return (mCurrGamePadState.rgdwPOV[0] == 18000);
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsDPadLeft() const
{
return (mCurrGamePadState.rgdwPOV[0] == 27000);
}
//----------------------------------------------------------------------------------------------------
bool InputSystem::IsDPadRight() const
{
return (mCurrGamePadState.rgdwPOV[0] == 9000);
}
//----------------------------------------------------------------------------------------------------
float InputSystem::GetLeftAnalogX() const
{
return (mCurrGamePadState.lX / 32767.5f) - 1.0f;
}
//----------------------------------------------------------------------------------------------------
float InputSystem::GetLeftAnalogY() const
{
return -(mCurrGamePadState.lY / 32767.5f) + 1.0f;
}
//----------------------------------------------------------------------------------------------------
float InputSystem::GetRightAnalogX() const
{
return (mCurrGamePadState.lZ / 32767.5f) - 1.0f;
}
//----------------------------------------------------------------------------------------------------
float InputSystem::GetRightAnalogY() const
{
return -(mCurrGamePadState.lRz / 32767.5f) + 1.0f;
}
//----------------------------------------------------------------------------------------------------
void InputSystem::UpdateGamePad()
{
// Store the previous game pad state
memcpy(&mPrevGamePadState, &mCurrGamePadState, sizeof(DIJOYSTATE));
// Poll the game pad device
static bool sWriteToLog = true;
HRESULT hr = mGamePadDevice->Poll();
if (FAILED(hr))
{
// Check if the device is lost
if (DIERR_INPUTLOST == hr || DIERR_NOTACQUIRED == hr)
{
if (sWriteToLog)
{
XLOG("[InputSystem] Game pad device is lost.");
sWriteToLog = false;
}
// Try to acquire game pad device again
mGamePadDevice->Acquire();
}
else
{
XLOG("[InputSystem] Failed to get game pad state.");
return;
}
}
else
{
// Reset flag
sWriteToLog = true;
}
// Get game pad state
hr = mGamePadDevice->GetDeviceState(sizeof(DIJOYSTATE), (void*)&mCurrGamePadState);
if (FAILED(hr))
{
// Check if the device is lost
if (DIERR_INPUTLOST == hr || DIERR_NOTACQUIRED == hr)
{
if (sWriteToLog)
{
XLOG("[InputSystem] Game pad device is lost.");
sWriteToLog = false;
}
// Try to acquire game pad device again
mGamePadDevice->Acquire();
}
else
{
XLOG("[InputSystem] Failed to get game pad state.");
return;
}
}
else
{
// Reset flag
sWriteToLog = true;
}
} | [
"tlauriente@gmail.com"
] | tlauriente@gmail.com |
d274282d4c07683cddc7ebd32f133de1f7deab01 | d2219fea4d37b8e608e52b9b9a7518d6b213bbbd | /Database/Strategy.cpp | dae67a30aecd0ea78ce764dd75306c4d357ee2e2 | [
"BSD-3-Clause"
] | permissive | qijiezhao/gStore | a42403cd4a4f3f18489a466697f52b0e71833ee4 | e33617ab9b096be4fecdd41710bde46a643c0a7a | refs/heads/master | 2021-01-11T08:15:31.247834 | 2016-09-18T12:23:50 | 2016-09-18T12:23:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,218 | cpp | /*=============================================================================
# Filename: Strategy.cpp
# Author: Bookug Lobert
# Mail: zengli-bookug@pku.edu.cn
# Last Modified: 2016-05-07 16:31
# Description: implement functions in Strategy.h
=============================================================================*/
#include "Strategy.h"
using namespace std;
Strategy::Strategy()
{
this->method = 0;
this->kvstore = NULL;
this->vstree = NULL;
//this->prepare_handler();
}
Strategy::Strategy(KVstore* _kvstore, VSTree* _vstree)
{
this->method = 0;
this->kvstore = _kvstore;
this->vstree = _vstree;
//this->prepare_handler();
}
Strategy::~Strategy()
{
//delete[] this->dispatch;
}
//void
//Strategy::prepare_handler()
//{
//this->dispatch = new QueryHandler[Strategy::QUERY_HANDLER_NUM];
//this->dispatch[0] = Strategy::handler0;
//}
//NOTICE: 2-triple case ?s1 p1 c0 ?s2 p2 c0 is viewed as an unconnected graph
//however, this can be dealed due to several basicquery and linking
bool
Strategy::handle(SPARQLquery& _query)
{
#ifdef MULTI_INDEX
Util::logging("IN GeneralEvaluation::handle");
vector<BasicQuery*>& queryList = _query.getBasicQueryVec();
// enumerate each BasicQuery and retrieve their variables' mapping entity in the VSTree.
vector<BasicQuery*>::iterator iter = queryList.begin();
for (; iter != queryList.end(); iter++)
{
this->method = 0;
vector<int*>& result_list = (*iter)->getResultList();
//int select_var_num = (*iter)->getSelectVarNum();
int varNum = (*iter)->getVarNum(); //the num of vars needing to be joined
int total_num = (*iter)->getTotalVarNum();
int pre_varNum = (*iter)->getPreVarNum();
if ((*iter)->getTripleNum() == 1 && pre_varNum == 1)
{
Triple triple = (*iter)->getTriple(0);
int* id_list = NULL;
int id_list_len = 0;
result_list.clear();
if (total_num == 2)
{
//TODO:consider special case, select ?s (?p) ?o where { ?s ?p ?o . }
//filter and join is too costly, should enum all predicates and use p2so
//maybe the selected vars are ?s (?p) or ?o (?p)
cerr << "not supported now!" << endl;
}
else if (total_num == 1)
{
//TODO:if just select s/o, use o2s/s2o
//if only p is selected, use s2p or o2p
//only if both s/o and p are selected, use s2po or o2ps
if (triple.subject[0] != '?') //constant
{
int sid = (this->kvstore)->getIDByEntity(triple.subject);
this->kvstore->getpreIDobjIDlistBysubID(sid, id_list, id_list_len);
}
else if (triple.object[0] != '?') //constant
{
int oid = (this->kvstore)->getIDByEntity(triple.object);
if (oid == -1)
{
oid = (this->kvstore)->getIDByLiteral(triple.object);
}
this->kvstore->getpreIDsubIDlistByobjID(oid, id_list, id_list_len);
}
//always place s/o before p in result list
for (int i = 0; i < id_list_len; i += 2)
{
int* record = new int[2]; //2 vars selected
record[1] = id_list[i]; //for the pre var
record[0] = id_list[i + 1]; //for the s/o var
result_list.push_back(record);
}
}
else if (total_num == 0) //only ?p
{
//just use so2p
int sid = (this->kvstore)->getIDByEntity(triple.subject);
int oid = (this->kvstore)->getIDByEntity(triple.object);
if (oid == -1)
{
oid = (this->kvstore)->getIDByLiteral(triple.object);
}
this->kvstore->getpreIDlistBysubIDobjID(sid, oid, id_list, id_list_len);
//copy to result list
for (int i = 0; i < id_list_len; ++i)
{
int* record = new int[1];
record[0] = id_list[i];
result_list.push_back(record);
}
}
delete[] id_list;
continue;
}
if (pre_varNum == 0 && (*iter)->getTripleNum() == 1) //only one triple and no predicates
{
//only one variable and one triple: ?s pre obj or sub pre ?o
if (total_num == 1)
{
this->method = 1;
}
//only two vars: ?s pre ?o
else if (total_num == 2)
{
if (varNum == 1) //the selected id should be 0
{
this->method = 2;
}
else //==2
{
this->method = 3;
}
}
//cerr << "this BasicQuery use query strategy 2" << endl;
//cerr<<"Final result size: "<<(*iter)->getResultList().size()<<endl;
//continue;
}
//QueryHandler dispatch;
//dispatch[0] = handler0;
switch (this->method)
{
case 0:
this->handler0(*iter, result_list);
break;
case 1:
this->handler1(*iter, result_list);
break;
case 2:
this->handler2(*iter, result_list);
break;
case 3:
this->handler3(*iter, result_list);
break;
default:
cerr << "not support this method" << endl;
}
cerr << "Final result size: " << (*iter)->getResultList().size() << endl;
//BETTER: use function pointer array in C++ class
}
#else
cerr << "this BasicQuery use original query strategy" << endl;
long tv_handle = Util::get_cur_time();
(this->vstree)->retrieve(_query);
long tv_retrieve = Util::get_cur_time();
cout << "after Retrieve, used " << (tv_retrieve - tv_handle) << "ms." << endl;
this->join = new Join(kvstore);
this->join->join_sparql(_query);
delete this->join;
long tv_join = Util::get_cur_time();
cout << "after Join, used " << (tv_join - tv_retrieve) << "ms." << endl;
#endif
Util::logging("OUT Strategy::handle");
return true;
}
bool
Strategy::handle(SPARQLquery& _query, int myRank, string &internal_tag_str)
{
#ifdef MULTI_INDEX
Util::logging("IN GeneralEvaluation::handle");
vector<BasicQuery*>& queryList = _query.getBasicQueryVec();
// enumerate each BasicQuery and retrieve their variables' mapping entity in the VSTree.
vector<BasicQuery*>::iterator iter=queryList.begin();
for(; iter != queryList.end(); iter++)
{
this->method = 0;
vector<int*>& result_list = (*iter)->getResultList();
int select_var_num = (*iter)->getSelectVarNum();
int varNum = (*iter)->getVarNum(); //the num of vars needing to be joined
int total_num = (*iter)->getTotalVarNum();
int pre_varNum = (*iter)->getPreVarNum();
if((*iter)->getTripleNum() == 1 && pre_varNum == 1)
{
Triple triple = (*iter)->getTriple(0);
int* id_list = NULL;
int id_list_len = 0;
result_list.clear();
if(total_num == 2)
{
//TODO:consider special case, select ?s (?p) ?o where { ?s ?p ?o . }
//filter and join is too costly, should enum all predicates and use p2so
//maybe the selected vars are ?s (?p) or ?o (?p)
cerr << "not supported now!" << endl;
}
else if(total_num == 1)
{
//TODO:if just select s/o, use o2s/s2o
//if only p is selected, use s2p or o2p
//only if both s/o and p are selected, use s2po or o2ps
if(triple.subject[0] != '?') //constant
{
int sid = (this->kvstore)->getIDByEntity(triple.subject);
this->kvstore->getpreIDobjIDlistBysubID(sid, id_list, id_list_len);
}
else if(triple.object[0] != '?') //constant
{
int oid = (this->kvstore)->getIDByEntity(triple.object);
if(oid == -1)
{
oid = (this->kvstore)->getIDByLiteral(triple.object);
}
this->kvstore->getpreIDsubIDlistByobjID(oid, id_list, id_list_len);
}
//always place s/o before p in result list
for(int i = 0; i < id_list_len; i += 2)
{
int* record = new int[2]; //2 vars selected
record[1] = id_list[i]; //for the pre var
record[0] = id_list[i+1]; //for the s/o var
result_list.push_back(record);
}
}
else if(total_num == 0) //only ?p
{
//just use so2p
int sid = (this->kvstore)->getIDByEntity(triple.subject);
int oid = (this->kvstore)->getIDByEntity(triple.object);
if(oid == -1)
{
oid = (this->kvstore)->getIDByLiteral(triple.object);
}
this->kvstore->getpreIDlistBysubIDobjID(sid, oid, id_list, id_list_len);
//copy to result list
for(int i = 0; i < id_list_len; ++i)
{
int* record = new int[1];
record[0] = id_list[i];
result_list.push_back(record);
}
}
delete[] id_list;
continue;
}
if(pre_varNum == 0 && (*iter)->getTripleNum() == 1) //only one triple and no predicates
{
//only one variable and one triple: ?s pre obj or sub pre ?o
if(total_num == 1)
{
this->method = 1;
}
//only two vars: ?s pre ?o
else if(total_num == 2)
{
if(varNum == 1) //the selected id should be 0
{
this->method = 2;
}
else //==2
{
this->method = 3;
}
}
//cerr << "this BasicQuery use query strategy 2" << endl;
//cerr<<"Final result size: "<<(*iter)->getResultList().size()<<endl;
//continue;
}
//QueryHandler dispatch;
//dispatch[0] = handler0;
switch(this->method)
{
case 0:
this->handler0_0(*iter, result_list, internal_tag_str);
break;
case 1:
this->handler1(*iter, result_list);
break;
case 2:
this->handler2(*iter, result_list);
break;
case 3:
this->handler3(*iter, result_list);
break;
default:
cerr << "not support this method" << endl;
}
//cerr<<"Final result size: "<<(*iter)->getResultList().size()<<endl;
//BETTER: use function pointer array in C++ class
}
#else
cerr << "this BasicQuery use original query strategy" << endl;
long tv_handle = Util::get_cur_time();
(this->vstree)->retrieve(_query);
long tv_retrieve = Util::get_cur_time();
cout << "after Retrieve, used " << (tv_retrieve - tv_handle) << "ms." << endl;
this->join = new Join(kvstore);
this->join->join_sparql(_query);
delete this->join;
long tv_join = Util::get_cur_time();
cout << "after Join, used " << (tv_join - tv_retrieve) << "ms." << endl;
#endif
Util::logging("OUT Strategy::handle");
return true;
}
void
Strategy::handler0_0(BasicQuery* _bq, vector<int*>& _result_list, string &internal_tag_str)
{
int star_flag = 0;
if(star_flag == 0){
_bq->setRetrievalTag();
}
long before_filter = Util::get_cur_time();
long tv_handle = Util::get_cur_time();
int varNum = _bq->getVarNum(); //the num of vars needing to be joined
for(int i = 0; i < varNum; ++i)
{
if(_bq->if_need_retrieve(i) == false)
continue;
bool flag = _bq->isLiteralVariable(i);
const EntityBitSet& entityBitSet = _bq->getVarBitSet(i);
IDList* idListPtr = &( _bq->getCandidateList(i) );
this->vstree->retrieveEntity(entityBitSet, idListPtr);
if(!flag)
{
_bq->setReady(i);
}
//the basic query should end if one non-literal var has no candidates
if(idListPtr->size() == 0 && !flag)
{
//break;
}
}
long tv_retrieve = Util::get_cur_time();
//printf("join_pe !!!! \n");
Join *join = new Join(kvstore);
if(star_flag == 1){
join->join_basic(_bq);
}else{
join->join_pe(_bq, internal_tag_str);
}
delete join;
long tv_join = Util::get_cur_time();
//cout << "after Join, used " << (tv_join - tv_retrieve) << "ms." << endl;
}
void
Strategy::handler0(BasicQuery* _bq, vector<int*>& _result_list)
{
//long before_filter = Util::get_cur_time();
cerr << "this BasicQuery use query strategy 0" << endl;
//BETTER:not all vars in join filtered by vstree
//(A)-B-c: B should by vstree, then by c, but A should be generated in join(first set A as not)
//if A not in join, just filter B by pre
//divided into star graphs, join core vertices, generate satellites
//join should also start from a core vertex(neighbor can be constants or vars) if available
//
//QUERY: is there any case that a node should be retrieved by other index?(instead of vstree or generate whne join)
//
//we had better treat 1-triple case(no ?p) as special, and then in other cases, core vertex exist(if connected)
//However, if containing ?p and 1-triple, we should treat it also as a special case, or select a variable as core vertex
//and retrieved (for example, ?s ?p o or s ?p ?o, generally no core vertex in these cases)
long tv_handle = Util::get_cur_time();
int varNum = _bq->getVarNum(); //the num of vars needing to be joined
for (int i = 0; i < varNum; ++i)
{
if (_bq->if_need_retrieve(i) == false)
continue;
bool flag = _bq->isLiteralVariable(i);
const EntityBitSet& entityBitSet = _bq->getVarBitSet(i);
IDList* idListPtr = &(_bq->getCandidateList(i));
this->vstree->retrieveEntity(entityBitSet, idListPtr);
if (!flag)
{
_bq->setReady(i);
}
//the basic query should end if one non-literal var has no candidates
if (idListPtr->size() == 0 && !flag)
{
break;
}
}
//if(_bq->isReady(0))
//cout<<"error: var 0 is ready?"<<endl;
//TODO:end directly if one is empty!
long tv_retrieve = Util::get_cur_time();
cout << "after Retrieve, used " << (tv_retrieve - tv_handle) << "ms." << endl;
Join *join = new Join(kvstore);
join->join_basic(_bq);
delete join;
long tv_join = Util::get_cur_time();
cout << "after Join, used " << (tv_join - tv_retrieve) << "ms." << endl;
}
void
Strategy::handler1(BasicQuery* _bq, vector<int*>& _result_list)
{
long before_filter = Util::get_cur_time();
cerr << "this BasicQuery use query strategy 1" << endl;
//int neighbor_id = (*_bq->getEdgeNeighborID(0, 0); //constant, -1
char edge_type = _bq->getEdgeType(0, 0);
int triple_id = _bq->getEdgeID(0, 0);
Triple triple = _bq->getTriple(triple_id);
int pre_id = _bq->getEdgePreID(0, 0);
int* id_list = NULL;
int id_list_len = 0;
if (edge_type == Util::EDGE_OUT)
{
//cerr<<"edge out!!!"<<endl;
int nid = (this->kvstore)->getIDByEntity(triple.object);
if (nid == -1)
{
nid = (this->kvstore)->getIDByLiteral(triple.object);
}
this->kvstore->getsubIDlistByobjIDpreID(nid, pre_id, id_list, id_list_len);
}
else
{
//cerr<<"edge in!!!"<<endl;
this->kvstore->getobjIDlistBysubIDpreID(this->kvstore->getIDByEntity(triple.subject), pre_id, id_list, id_list_len);
}
long after_filter = Util::get_cur_time();
cerr << "after filter, used " << (after_filter - before_filter) << "ms" << endl;
_result_list.clear();
//cerr<<"now to copy result to list"<<endl;
for (int i = 0; i < id_list_len; ++i)
{
int* record = new int[1]; //only this var is selected
record[0] = id_list[i];
//cerr<<this->kvstore->getEntityByID(record[0])<<endl;
_result_list.push_back(record);
}
long after_copy = Util::get_cur_time();
cerr << "after copy to result list: used " << (after_copy - after_filter) << " ms" << endl;
delete[] id_list;
cerr << "Final result size: " << _result_list.size() << endl;
}
void
Strategy::handler2(BasicQuery* _bq, vector<int*>& _result_list)
{
long before_filter = Util::get_cur_time();
cerr << "this BasicQuery use query strategy 2" << endl;
int triple_id = _bq->getEdgeID(0, 0);
Triple triple = _bq->getTriple(triple_id);
int pre_id = _bq->getEdgePreID(0, 0);
int var1_id = _bq->getIDByVarName(triple.subject);
int var2_id = _bq->getIDByVarName(triple.object);
int* id_list = NULL;
int id_list_len = 0;
if (var1_id == 0) //subject var selected
{
//use p2s directly
this->kvstore->getsubIDlistBypreID(pre_id, id_list, id_list_len);
}
else if (var2_id == 0) //object var selected
{
//use p2o directly
this->kvstore->getobjIDlistBypreID(pre_id, id_list, id_list_len);
}
else
{
cerr << "ERROR in Database::handle(): no selected var!" << endl;
}
long after_filter = Util::get_cur_time();
cerr << "after filter, used " << (after_filter - before_filter) << "ms" << endl;
_result_list.clear();
for (int i = 0; i < id_list_len; ++i)
{
int* record = new int[1]; //only one var
record[0] = id_list[i];
_result_list.push_back(record);
}
long after_copy = Util::get_cur_time();
cerr << "after copy to result list: used " << (after_copy - after_filter) << " ms" << endl;
delete[] id_list;
cerr << "Final result size: " << _result_list.size() << endl;
}
void
Strategy::handler3(BasicQuery* _bq, vector<int*>& _result_list)
{
long before_filter = Util::get_cur_time();
cerr << "this BasicQuery use query strategy 3" << endl;
int triple_id = _bq->getEdgeID(0, 0);
Triple triple = _bq->getTriple(triple_id);
int pre_id = _bq->getEdgePreID(0, 0);
int* id_list = NULL;
int id_list_len = 0;
this->kvstore->getsubIDobjIDlistBypreID(pre_id, id_list, id_list_len);
int var1_id = _bq->getIDByVarName(triple.subject);
int var2_id = _bq->getIDByVarName(triple.object);
long after_filter = Util::get_cur_time();
cerr << "after filter, used " << (after_filter - before_filter) << "ms" << endl;
_result_list.clear();
for (int i = 0; i < id_list_len; i += 2)
{
int* record = new int[2]; //2 vars and selected
record[var1_id] = id_list[i];
record[var2_id] = id_list[i + 1];
_result_list.push_back(record);
}
long after_copy = Util::get_cur_time();
cerr << "after copy to result list: used " << (after_copy - after_filter) << " ms" << endl;
delete[] id_list;
cerr << "Final result size: " << _result_list.size() << endl;
} | [
"zengli-bookug@pku.edu.cn"
] | zengli-bookug@pku.edu.cn |
aadfdc0c72a4c93cb044f8db4540856e3cd0f765 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/admin/wmi/wbem/providers/nteventprovider/dll/ntevtprov.cpp | 10a6fd17b234c4a7680758e7e1f710e907ab1b1d | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,622 | cpp | //***************************************************************************
//
// NTEVTPROV.CPP
//
// Module: WBEM NT EVENT PROVIDER
//
// Purpose: Contains the WBEM interface for event provider classes
//
// Copyright (c) 1996-2001 Microsoft Corporation, All Rights Reserved
//
//***************************************************************************
#include "precomp.h"
#include "ql.h"
#include "analyser.h"
BOOL ObtainedSerialAccess(CMutex* pLock)
{
BOOL bResult = FALSE;
if (pLock != NULL)
{
if (pLock->Lock())
{
bResult = TRUE;
}
}
return bResult;
}
void ReleaseSerialAccess(CMutex* pLock)
{
if (pLock != NULL)
{
pLock->Unlock();
}
}
void CNTEventProvider::AllocateGlobalSIDs()
{
SID_IDENTIFIER_AUTHORITY t_WorldAuthoritySid = SECURITY_WORLD_SID_AUTHORITY;
if (!AllocateAndInitializeSid(
&t_WorldAuthoritySid,
1,
SECURITY_WORLD_RID,
0,
0, 0, 0, 0, 0, 0,
&s_WorldSid))
{
s_WorldSid = NULL;
}
SID_IDENTIFIER_AUTHORITY t_NTAuthoritySid = SECURITY_NT_AUTHORITY;
if (!AllocateAndInitializeSid(
&t_NTAuthoritySid,
1,
SECURITY_ANONYMOUS_LOGON_RID,
0, 0, 0, 0, 0, 0, 0,
&s_AnonymousLogonSid))
{
s_AnonymousLogonSid = NULL;
}
if (!AllocateAndInitializeSid(
&t_NTAuthoritySid,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&s_AliasAdminsSid))
{
s_AliasAdminsSid = NULL;
}
if (!AllocateAndInitializeSid(
&t_NTAuthoritySid,
1,
SECURITY_LOCAL_SYSTEM_RID,
0, 0, 0, 0, 0, 0, 0,
&s_LocalSystemSid
))
{
s_LocalSystemSid = NULL;
}
if (!AllocateAndInitializeSid(
&t_NTAuthoritySid,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_GUESTS,
0,0,0,0,0,0,
&s_AliasGuestsSid
))
{
s_AliasGuestsSid = NULL;
}
if (!AllocateAndInitializeSid(
&t_NTAuthoritySid,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_SYSTEM_OPS,
0,0,0,0,0,0,
&s_AliasSystemOpsSid
))
{
s_AliasSystemOpsSid = NULL;
}
if (!AllocateAndInitializeSid(
&t_NTAuthoritySid,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_BACKUP_OPS,
0,0,0,0,0,0,
&s_AliasBackupOpsSid
))
{
s_AliasBackupOpsSid = NULL;
}
if (!AllocateAndInitializeSid(
&t_NTAuthoritySid,
1,
SECURITY_LOCAL_SERVICE_RID,
0,
0, 0, 0, 0, 0, 0,
&s_LocalServiceSid
))
{
s_LocalServiceSid = NULL;
}
if (!AllocateAndInitializeSid(
&t_NTAuthoritySid,
1,
SECURITY_NETWORK_SERVICE_RID,
0,
0, 0, 0, 0, 0, 0,
&s_NetworkServiceSid
))
{
s_NetworkServiceSid = NULL;
}
}
void CNTEventProvider::FreeGlobalSIDs()
{
if (s_NetworkServiceSid)
{
FreeSid(s_NetworkServiceSid);
s_NetworkServiceSid = NULL;
}
if (s_LocalServiceSid)
{
FreeSid(s_LocalServiceSid);
s_LocalServiceSid = NULL;
}
if (s_AliasBackupOpsSid)
{
FreeSid(s_AliasBackupOpsSid);
s_AliasBackupOpsSid = NULL;
}
if (s_AliasSystemOpsSid)
{
FreeSid(s_AliasSystemOpsSid);
s_AliasSystemOpsSid = NULL;
}
if (s_AliasGuestsSid)
{
FreeSid(s_AliasGuestsSid);
s_AliasGuestsSid = NULL;
}
if (s_LocalSystemSid)
{
FreeSid(s_LocalSystemSid);
s_LocalSystemSid = NULL;
}
if (s_AliasAdminsSid)
{
FreeSid(s_AliasAdminsSid);
s_AliasAdminsSid = NULL;
}
if (s_AnonymousLogonSid)
{
FreeSid(s_AnonymousLogonSid);
s_AnonymousLogonSid = NULL;
}
if (s_WorldSid)
{
FreeSid(s_WorldSid);
s_WorldSid = NULL;
}
}
BOOL CNTEventProvider::GlobalSIDsOK()
{
return (s_NetworkServiceSid
&& s_LocalServiceSid
&& s_AliasBackupOpsSid
&& s_AliasSystemOpsSid
&& s_AliasGuestsSid
&& s_LocalSystemSid
&& s_AliasAdminsSid
&& s_AnonymousLogonSid
&& s_WorldSid);
}
STDMETHODIMP CNTEventProvider::AccessCheck (
LPCWSTR wszQueryLanguage,
LPCWSTR wszQuery,
LONG lSidLength,
const BYTE __RPC_FAR *pSid
)
{
HRESULT t_Status = WBEM_E_ACCESS_DENIED;
SetStructuredExceptionHandler seh;
try
{
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Entering CNTEventProvider::AccessCheck\r\n");
)
if (lSidLength > 0)
{
if (pSid != NULL)
{
// permanent consumer: hope core did its job
return WBEM_S_SUBJECT_TO_SDS;
}
else
{
return WBEM_E_ACCESS_DENIED;
}
}
if (FAILED(CImpNTEvtProv::GetImpersonation()))
{
return WBEM_E_ACCESS_DENIED;
}
QL_LEVEL_1_RPN_EXPRESSION* pExpr;
CTextLexSource Source(wszQuery);
QL1_Parser Parser(&Source);
if(Parser.Parse(&pExpr) == 0)
{
// Analyze this
QL_LEVEL_1_RPN_EXPRESSION* pNewExpr;
CPropertyName MyProp;
MyProp.AddElement(TARGET_PROP);
MyProp.AddElement(LOGFILE_PROP);
if(SUCCEEDED(CQueryAnalyser::GetNecessaryQueryForProperty(pExpr, MyProp, pNewExpr)))
{
CStringArray t_wsVals;
HRESULT t_hres = CQueryAnalyser::GetValuesForProp(pNewExpr, MyProp, t_wsVals);
if(SUCCEEDED(t_hres))
{
//grant access and set false if a failure occurs...
t_Status = S_OK;
// awsVals contains the list of files
for (int x = 0; x < t_wsVals.GetSize(); x++)
{
DWORD t_dwReason = 0;
HANDLE t_hEvtlog = CEventLogFile::OpenLocalEventLog(t_wsVals[x], &t_dwReason);
if (t_hEvtlog == NULL)
{
if (t_dwReason != ERROR_FILE_NOT_FOUND)
{
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Entering CNTEventProvider::AccessCheck - Failed to verify logfile access\r\n");
)
t_Status = WBEM_E_ACCESS_DENIED;
break;
}
else
{
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Entering CNTEventProvider::AccessCheck - Logfile not found assuming access allowed for log\r\n");
)
}
}
else
{
CloseEventLog(t_hEvtlog);
}
}
}
else if(t_hres == WBEMESS_E_REGISTRATION_TOO_BROAD)
{
// user asked for all, check all logs....
HKEY hkResult = NULL;
LONG t_lErr = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
EVENTLOG_BASE, 0,
KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS,
&hkResult);
if (t_lErr == ERROR_SUCCESS)
{
DWORD iValue = 0;
WCHAR t_logname[MAX_PATH+1];
DWORD t_lognameSize = MAX_PATH;
//grant access and set false if a failure occurs...
t_Status = S_OK;
// read all entries under this key to find all logfiles...
while ((t_lErr = RegEnumKey(hkResult, iValue, t_logname, t_lognameSize)) != ERROR_NO_MORE_ITEMS)
{
// if error during read
if (t_lErr != ERROR_SUCCESS)
{
// indicate error
t_Status = WBEM_E_ACCESS_DENIED;
break;
}
//open logfile
DWORD t_dwReason = 0;
HANDLE t_hEvtlog = CEventLogFile::OpenLocalEventLog(t_logname, &t_dwReason);
if (t_hEvtlog == NULL)
{
if (t_dwReason != ERROR_FILE_NOT_FOUND)
{
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Entering CNTEventProvider::AccessCheck - Failed to verify logfile access\r\n");
)
t_Status = WBEM_E_ACCESS_DENIED;
break;
}
else
{
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Entering CNTEventProvider::AccessCheck - Logfile not found assuming access allowed for log\r\n");
)
}
}
else
{
CloseEventLog(t_hEvtlog);
}
// read next parameter
iValue++;
} // end while
RegCloseKey(hkResult);
}
}
t_wsVals.RemoveAll();
delete pNewExpr;
}
delete pExpr;
}
WbemCoRevertToSelf();
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Leaving CNTEventProvider::AccessCheck\r\n");
)
}
catch(Structured_Exception e_SE)
{
WbemCoRevertToSelf();
t_Status = WBEM_E_UNEXPECTED;
}
catch(Heap_Exception e_HE)
{
WbemCoRevertToSelf();
t_Status = WBEM_E_OUT_OF_MEMORY;
}
catch(...)
{
WbemCoRevertToSelf();
t_Status = WBEM_E_UNEXPECTED;
}
return t_Status;
}
STDMETHODIMP CNTEventProvider::Initialize (
LPWSTR pszUser,
LONG lFlags,
LPWSTR pszNamespace,
LPWSTR pszLocale,
IWbemServices *pCIMOM, // For anybody
IWbemContext *pCtx,
IWbemProviderInitSink *pInitSink // For init signals
)
{
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Entering CNTEventProvider::Initialize\r\n");
)
HRESULT t_Status = WBEM_NO_ERROR;
SetStructuredExceptionHandler seh;
try
{
if (GlobalSIDsOK())
{
m_pNamespace = pCIMOM;
m_pNamespace->AddRef();
m_Mgr->SetFirstSinceLogon(pCIMOM, pCtx);
pInitSink->SetStatus ( WBEM_S_INITIALIZED , 0 );
}
else
{
pInitSink->SetStatus ( WBEM_E_UNEXPECTED , 0 );
}
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Leaving CNTEventProvider::Initialize with SUCCEEDED\r\n");
)
}
catch(Structured_Exception e_SE)
{
t_Status = WBEM_E_UNEXPECTED;
}
catch(Heap_Exception e_HE)
{
t_Status = WBEM_E_OUT_OF_MEMORY;
}
catch(...)
{
t_Status = WBEM_E_UNEXPECTED;
}
return t_Status;
}
STDMETHODIMP CNTEventProvider::ProvideEvents(IWbemObjectSink* pSink, LONG lFlags)
{
HRESULT t_Status = WBEM_NO_ERROR;
SetStructuredExceptionHandler seh;
try
{
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Entering CNTEventProvider::ProvideEvents\r\n");
)
m_pEventSink = pSink;
m_pEventSink->AddRef();
if (!m_Mgr->Register(this))
{
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Leaving CNTEventProvider::ProvideEvents with FAILED\r\n");
)
return WBEM_E_FAILED;
}
DebugOut(
CNTEventProvider::g_NTEvtDebugLog->WriteFileAndLine(_T(__FILE__),__LINE__,
L"Leaving CNTEventProvider::ProvideEvents with SUCCEEDED\r\n");
)
}
catch(Structured_Exception e_SE)
{
t_Status = WBEM_E_UNEXPECTED;
}
catch(Heap_Exception e_HE)
{
t_Status = WBEM_E_OUT_OF_MEMORY;
}
catch(...)
{
t_Status = WBEM_E_UNEXPECTED;
}
return t_Status;
}
CNTEventProvider::~CNTEventProvider()
{
if (m_pNamespace != NULL)
{
m_pNamespace->Release();
}
if (m_pEventSink != NULL)
{
m_pEventSink->Release();
}
}
CNTEventProvider::CNTEventProvider(CEventProviderManager* mgr) : m_pNamespace(NULL), m_pEventSink(NULL)
{
m_Mgr = mgr;
m_ref = 0;
}
IWbemServices* CNTEventProvider::GetNamespace()
{
m_pNamespace->AddRef();
return m_pNamespace;
}
IWbemObjectSink* CNTEventProvider::GetEventSink()
{
m_pEventSink->AddRef();
return m_pEventSink;
}
void CNTEventProvider::ReleaseAll()
{
//release dependencies
m_pNamespace->Release();
m_pEventSink->Release();
Release();
}
void CNTEventProvider::AddRefAll()
{
//addref dependencies
m_pNamespace->AddRef();
m_pEventSink->AddRef();
AddRef();
}
STDMETHODIMP_( ULONG ) CNTEventProvider::AddRef()
{
SetStructuredExceptionHandler seh;
try
{
InterlockedIncrement(&(CNTEventProviderClassFactory::objectsInProgress));
return InterlockedIncrement ( &m_ref ) ;
}
catch(Structured_Exception e_SE)
{
return 0;
}
catch(Heap_Exception e_HE)
{
return 0;
}
catch(...)
{
return 0;
}
}
STDMETHODIMP_(ULONG) CNTEventProvider::Release()
{
SetStructuredExceptionHandler seh;
try
{
long ret;
if ( 0 == (ret = InterlockedDecrement(&m_ref)) )
{
delete this;
}
else if ( 1 == ret )
{
m_Mgr->UnRegister(this);
}
InterlockedDecrement(&(CNTEventProviderClassFactory::objectsInProgress));
return ret;
}
catch(Structured_Exception e_SE)
{
return 0;
}
catch(Heap_Exception e_HE)
{
return 0;
}
catch(...)
{
return 0;
}
}
STDMETHODIMP CNTEventProvider::QueryInterface(REFIID riid, PVOID* ppv)
{
SetStructuredExceptionHandler seh;
try
{
*ppv = NULL;
if (IID_IUnknown == riid)
{
*ppv=(IWbemEventProvider*)this;
}
else if (IID_IWbemEventProvider == riid)
{
*ppv=(IWbemEventProvider*)this;
}
else if (IID_IWbemProviderInit == riid)
{
*ppv= (IWbemProviderInit*)this;
}
else if (IID_IWbemEventProviderSecurity == riid)
{
*ppv= (IWbemEventProviderSecurity*)this;
}
if (NULL==*ppv)
{
return E_NOINTERFACE;
}
//AddRef any interface we'll return.
((LPUNKNOWN)*ppv)->AddRef();
return NOERROR;
}
catch(Structured_Exception e_SE)
{
return E_UNEXPECTED;
}
catch(Heap_Exception e_HE)
{
return E_OUTOFMEMORY;
}
catch(...)
{
return E_UNEXPECTED;
}
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
57e4809d112a30b48080cf1543f4b6b93faaf56b | f8cdee63b259f1a2b9dfd40060bcd6436052314d | /aika.h | c927dc13d5ea7a3641064242168e9ab59cfeab09 | [] | no_license | Jani-siv/Mystery-Cube-Quest | 01baa7157925baaa8ebd18b75d0d93ce82f21400 | 4aca0135812dfd9bbfb2facd8826b855e8c64b5e | refs/heads/main | 2023-02-03T18:46:44.700479 | 2020-12-12T11:22:58 | 2020-12-12T11:22:58 | 311,934,519 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,616 | h | #ifndef AIKA_H
#define AIKA_H
#include "lcd.h"
#include "debug.h"
class aika
{
public:
bool yleinenAika = false; //aika keskeytyksen alustus
unsigned long int keskeytysMillis = 0;
void alustaAika(int maara);
int vahennaAika(int maara);
void paivitaAika(int maara);
//void yleinenAika(); //vähentää pääkellosta 1 sekunnin
int tarkistaAika();
void yleinenAikaFunktio(LCD* objekti);
debug var;
debug *variable = &var;//aika keskeytys
int kymmin = 10; //pääkellon minuutit ja sekunnit
int minuutit = 0;
int kymsek = 0;
int sekunnit = 0;
int aikaMin = 10; //keskeytyksen aika minuuttia
int aikaSec = 5; //keskeytyksen aika sekunttia
unsigned long int millisFunktiossa = 0;
};
#endif
| [
"info@kengityspaja.fi"
] | info@kengityspaja.fi |
cd76d22b15d24212e2d711c8b01bf8eda6e139ed | 5456502f97627278cbd6e16d002d50f1de3da7bb | /ash/shared/immersive_fullscreen_controller_delegate.h | 0af55cb7ffc2660c76cee4b206b5f3234095e4d4 | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,654 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_SHARED_IMMERSIVE_FULLSCREEN_CONTROLLER_DELEGATE_H_
#define ASH_SHARED_IMMERSIVE_FULLSCREEN_CONTROLLER_DELEGATE_H_
#include <vector>
#include "ash/ash_export.h"
namespace gfx {
class Rect;
}
namespace ash {
class ASH_EXPORT ImmersiveFullscreenControllerDelegate {
public:
// Called when a reveal of the top-of-window views starts.
virtual void OnImmersiveRevealStarted() = 0;
// Called when the top-of-window views have finished closing. This call
// implies a visible fraction of 0. SetVisibleFraction(0) may not be called
// prior to OnImmersiveRevealEnded().
virtual void OnImmersiveRevealEnded() = 0;
// Called as a result of disabling immersive fullscreen via SetEnabled().
virtual void OnImmersiveFullscreenExited() = 0;
// Called to update the fraction of the top-of-window views height which is
// visible.
virtual void SetVisibleFraction(double visible_fraction) = 0;
// Returns a list of rects whose union makes up the top-of-window views.
// The returned list is used for hittesting when the top-of-window views
// are revealed. GetVisibleBoundsInScreen() must return a valid value when
// not in immersive fullscreen for the sake of SetupForTest().
virtual std::vector<gfx::Rect> GetVisibleBoundsInScreen() const = 0;
protected:
virtual ~ImmersiveFullscreenControllerDelegate() {}
};
} // namespace ash
#endif // ASH_SHARED_IMMERSIVE_FULLSCREEN_CONTROLLER_DELEGATE_H_
| [
"lixiaodonglove7@aliyun.com"
] | lixiaodonglove7@aliyun.com |
cf9dc3b898d492358b10c4c99be35e77fa7c633d | f04bb40794f407e077cf47aab643e8536a7384ec | /Video/cutImageTest/cutImageTest.cpp | eb550a8e40a59500d8818ec7b5451458f1a0e95d | [] | no_license | elfmedy/2013 | 50f98ca39ff723b869631912df4b2e0c64f52c26 | fdc3bac5b17871baa22b1d044afd0a5a0e1fcbdc | refs/heads/master | 2020-05-19T07:49:06.318059 | 2014-01-03T17:58:53 | 2014-01-03T17:58:53 | 10,138,872 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 223 | cpp | // cutImageTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "cutImage.h"
int _tmain(int argc, _TCHAR* argv[])
{
CutImage(10, 10, 100, 200, "in\\2.jpg", "out\\s2.jpg");
return 0;
}
| [
"flyoverthecity@gmail.com"
] | flyoverthecity@gmail.com |
0f40bf1b3e0df596c14ca17287fa9ef43491e3a5 | 94db0bd95a58fabfd47517ed7d7d819a542693cd | /client/ClientRes/IOSAPI/Classes/Native/AssemblyU2DCSharp_EditerType4017711417.h | 88b3e8e66e62437373bbd7db4f769974b7b17005 | [] | no_license | Avatarchik/card | 9fc6efa058085bd25f2b8831267816aa12b24350 | d18dbc9c7da5cf32c963458ac13731ecfbf252fa | refs/heads/master | 2020-06-07T07:01:00.444233 | 2017-12-11T10:52:17 | 2017-12-11T10:52:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Enum2459695545.h"
#include "AssemblyU2DCSharp_EditerType4017711417.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// EditerType
struct EditerType_t4017711417
{
public:
// System.Int32 EditerType::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(EditerType_t4017711417, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"1"
] | 1 |
09744c7580262cd7c57ca7a1947365315e5215b0 | ab5bd6ed10341b5c4d63fd04c4f6f809562c3485 | /tensorflow/lite/delegates/gpu/cl/kernels/conv_buffer_1x1.h | 89f0cae4ea44c9d9cc441799637fc84d3a313216 | [
"Apache-2.0"
] | permissive | Arashtbr/tensorflow | 925aef7fa7ffe99d0321fc8af13804b6dfe41b7a | 4f301f599748928f6a3471d466731cfe5b536670 | refs/heads/master | 2023-01-14T01:40:57.436443 | 2020-11-21T00:05:08 | 2020-11-21T00:12:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,406 | h | /* Copyright 2019 The TensorFlow 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.
==============================================================================*/
#ifndef TENSORFLOW_LITE_DELEGATES_GPU_CL_KERNELS_CONV_BUFFER_1X1_H_
#define TENSORFLOW_LITE_DELEGATES_GPU_CL_KERNELS_CONV_BUFFER_1X1_H_
#include "tensorflow/lite/delegates/gpu/cl/buffer.h"
#include "tensorflow/lite/delegates/gpu/cl/cl_kernel.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/gpu_operation.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/util.h"
#include "tensorflow/lite/delegates/gpu/cl/linear_storage.h"
#include "tensorflow/lite/delegates/gpu/cl/tensor.h"
#include "tensorflow/lite/delegates/gpu/cl/util.h"
#include "tensorflow/lite/delegates/gpu/common/data_type.h"
#include "tensorflow/lite/delegates/gpu/common/operations.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/task/weights_layout.h"
#include "tensorflow/lite/delegates/gpu/common/tensor.h"
#include "tensorflow/lite/delegates/gpu/common/types.h"
#include "tensorflow/lite/delegates/gpu/common/winograd_util.h"
namespace tflite {
namespace gpu {
namespace cl {
class ConvBuffer1x1 : public GPUOperation {
public:
ConvBuffer1x1() = default;
// Move only
ConvBuffer1x1(ConvBuffer1x1&& operation);
ConvBuffer1x1& operator=(ConvBuffer1x1&& operation);
ConvBuffer1x1(const ConvBuffer1x1&) = delete;
ConvBuffer1x1& operator=(const ConvBuffer1x1&) = delete;
void GetPossibleKernelWorkGroups(
TuningType tuning_type, const GpuInfo& gpu_info,
const KernelInfo& kernel_info,
std::vector<int3>* work_groups) const override;
int3 GetGridSize() const override;
WeightsDescription GetWeightsDescription() const {
WeightsDescription desc;
desc.layout = WeightsLayout::kOHWIOGroupI4O4;
desc.output_group_size = conv_params_.block_size.z;
return desc;
}
struct ConvParams {
int3 block_size = int3(1, 1, 1);
int element_size = 4; // can be 4, 8 or 16
// By default in 2d convolution we have the same weights for WH dims, but in
// some cases we need separate weights for H dimension and convolution
// kernel requires very small modifications to support it.
bool different_weights_for_height = false;
};
private:
ConvBuffer1x1(const OperationDef& definition, const ConvParams& conv_params);
friend ConvBuffer1x1 CreateConvBuffer1x1(const GpuInfo& gpu_info,
const OperationDef& definition,
const Convolution2DAttributes& attr,
const BHWC* shape);
friend ConvBuffer1x1 CreateConvBuffer1x1(const GpuInfo& gpu_info,
const OperationDef& definition,
const FullyConnectedAttributes& attr,
const BHWC* shape);
friend ConvBuffer1x1 CreateConvBuffer1x1Wino4x4To6x6(
const GpuInfo& gpu_info, const OperationDef& definition,
const Convolution2DAttributes& attr, const BHWC* shape);
friend ConvBuffer1x1 CreateConvBuffer1x1DynamicWeights(
const GpuInfo& gpu_info, const OperationDef& definition,
const Convolution2DAttributes& attr, const BHWC& weights_shape,
const BHWC* dst_shape);
template <DataType T>
void UploadData(const tflite::gpu::Tensor<OHWI, T>& weights,
const tflite::gpu::Tensor<Linear, T>& biases);
template <DataType T>
void UploadDataForWinograd4x4To6x6(
const tflite::gpu::Tensor<OHWI, T>& weights);
template <DataType T>
void UploadWeights(const tflite::gpu::Tensor<OHWI, T>& weights);
template <DataType T>
void UploadBiases(const tflite::gpu::Tensor<Linear, T>& biases);
std::string GenerateConvBuffer1x1(
const OperationDef& op_def, const ConvBuffer1x1::ConvParams& conv_params,
Arguments* args);
ConvParams conv_params_;
};
template <DataType T>
void ConvBuffer1x1::UploadData(const tflite::gpu::Tensor<OHWI, T>& weights,
const tflite::gpu::Tensor<Linear, T>& biases) {
UploadWeights(weights);
UploadBiases(biases);
}
template <DataType T>
void ConvBuffer1x1::UploadDataForWinograd4x4To6x6(
const tflite::gpu::Tensor<OHWI, T>& weights) {
tflite::gpu::Tensor<OHWI, T> wino_weights;
RearrangeWeightsToWinograd4x4To6x6Weights(weights, &wino_weights);
UploadWeights(wino_weights);
tflite::gpu::Tensor<Linear, DataType::FLOAT32> bias;
bias.shape = Linear(weights.shape.o);
bias.data.resize(weights.shape.o, 0.0f);
UploadBiases(bias);
}
template <DataType T>
void ConvBuffer1x1::UploadWeights(const tflite::gpu::Tensor<OHWI, T>& weights) {
const int dst_depth = DivideRoundUp(weights.shape.o, 4);
const int src_depth = DivideRoundUp(weights.shape.i, 4);
const bool f32_weights = definition_.precision == CalculationsPrecision::F32;
const int float4_size = f32_weights ? sizeof(float4) : sizeof(half4);
const int dst_depth_aligned = AlignByN(dst_depth, conv_params_.block_size.z);
const int elements_count =
weights.shape.h * weights.shape.w * src_depth * dst_depth_aligned * 4;
BufferDescriptor desc;
desc.element_type = f32_weights ? DataType::FLOAT32 : DataType::FLOAT16;
desc.element_size = 16;
desc.memory_type = MemoryType::GLOBAL;
desc.size = float4_size * elements_count;
desc.data.resize(desc.size);
if (f32_weights) {
float4* ptr = reinterpret_cast<float4*>(desc.data.data());
RearrangeWeightsToOHWIOGroupI4O4(weights, conv_params_.block_size.z,
absl::MakeSpan(ptr, elements_count));
} else {
half4* ptr = reinterpret_cast<half4*>(desc.data.data());
RearrangeWeightsToOHWIOGroupI4O4(weights, conv_params_.block_size.z,
absl::MakeSpan(ptr, elements_count));
}
args_.AddObject("weights",
absl::make_unique<BufferDescriptor>(std::move(desc)));
}
template <DataType T>
void ConvBuffer1x1::UploadBiases(const tflite::gpu::Tensor<Linear, T>& biases) {
TensorLinearDescriptor desc;
desc.storage_type = LinearStorageType::BUFFER;
desc.element_type = definition_.GetDataType();
int depth = AlignByN(biases.shape.v, 4 * conv_params_.block_size.z) / 4;
desc.UploadLinearData(biases, depth);
args_.AddObject("biases",
absl::make_unique<TensorLinearDescriptor>(std::move(desc)));
}
bool IsConvBuffer1x1Supported(const OperationDef& definition,
const Convolution2DAttributes& attr);
bool IsConvBuffer1x1Supported(const OperationDef& definition,
const BHWC& weights_shape,
const Convolution2DAttributes& attr);
ConvBuffer1x1 CreateConvBuffer1x1(const GpuInfo& gpu_info,
const OperationDef& definition,
const Convolution2DAttributes& attr,
const BHWC* shape = nullptr);
ConvBuffer1x1 CreateConvBuffer1x1(const GpuInfo& gpu_info,
const OperationDef& definition,
const FullyConnectedAttributes& attr,
const BHWC* shape = nullptr);
ConvBuffer1x1 CreateConvBuffer1x1DynamicWeights(
const GpuInfo& gpu_info, const OperationDef& definition,
const Convolution2DAttributes& attr, const BHWC& weights_shape,
const BHWC* dst_shape = nullptr);
ConvBuffer1x1 CreateConvBuffer1x1Wino4x4To6x6(
const GpuInfo& gpu_info, const OperationDef& definition,
const Convolution2DAttributes& attr, const BHWC* shape = nullptr);
} // namespace cl
} // namespace gpu
} // namespace tflite
#endif // TENSORFLOW_LITE_DELEGATES_GPU_CL_KERNELS_CONV_BUFFER_1X1_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
a284ec2c62b6abeabb0b3e63b10ebfe1a5e0d8ac | 24c1eae6026f1378172ee3ef4fd47ab39f6d7290 | /adddialog.cpp | 9e52d36910f0e0bd7a96b4f3aefa4b42954e3df9 | [] | no_license | upcomingGit/PasswordManager | 5fac90e36b75ded7a913d6eb0a1defb0df3db168 | 9c779285aa78bf901478d90530a8d8201b95ff54 | refs/heads/master | 2021-01-10T02:06:22.490500 | 2016-03-08T04:05:37 | 2016-03-08T04:05:37 | 53,294,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | cpp | #include "adddialog.h"
#include <QGridLayout>
AddDialog::AddDialog(QWidget *parent) : QDialog(parent)
{
nameLabel = new QLabel("Username");
passLabel = new QLabel("Password");
desLabel = new QLabel("Description");
add = new QPushButton("Add");
close = new QPushButton("Close");
username = new QLineEdit;
password = new QLineEdit;
description = new QLineEdit;
setWindowTitle("Add a password entry");
QGridLayout *gLayout = new QGridLayout;
gLayout->setColumnStretch(1, 2);
gLayout->addWidget(desLabel, 0, 0);
gLayout->addWidget(description, 0, 1);
gLayout->addWidget(nameLabel, 1, 0);
gLayout->addWidget(username, 1, 1);
gLayout->addWidget(passLabel, 2, 0);
gLayout->addWidget(password, 2, 1);
QHBoxLayout *boxLayout = new QHBoxLayout;
boxLayout->addWidget(add);
boxLayout->addWidget(close);
gLayout->addLayout(boxLayout, 3, 1);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(gLayout);
setLayout(mainLayout);
connect(add, SIGNAL(clicked()), this, SLOT(accept()));
connect(close, SIGNAL(clicked()), this, SLOT(reject()));
}
| [
"ankur1992@gmail.com"
] | ankur1992@gmail.com |
8830c64d213dd33a05b07c291928658dc3a5cf1e | 379d37c01fc6e8ae01be14dae5bb17a2f6d0b8a7 | /ZRXSDK2018/utils/amodeler/inc/morphmap.h | 4050f60c6cfa5aa4b8bb0083e665891211ebd845 | [] | no_license | xiongzhihui/QuickDim | 80c54b5031b7676c8ac6ff2b326cf171fa6736dc | 1429b06b4456372c2976ec53c2f91fd8c4e0bae1 | refs/heads/master | 2020-03-28T12:08:21.284473 | 2018-09-11T06:39:20 | 2018-09-11T06:39:20 | 148,272,259 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,692 | h | #ifndef AECMODELER_INC_MORPHMAP_H
#define AECMODELER_INC_MORPHMAP_H
#include "global.h"
#include <vector>
AECMODELER_NAMESPACE_BEGIN
class DllImpExp MorphingMap
{
public:
MorphingMap() {}
MorphingMap(const MorphingMap&);
~MorphingMap();
MorphingMap& operator =(const MorphingMap&);
void add (int from, int to, int vis = 0);
void addAt(int index, int from, int to, int vis = 0);
void del (int index);
void get (int index, int& fromIndex, int& toIndex, int& visibility) const;
int length() const { return 0; }
bool isNull() const { return true; }
bool isIdentity() const;
void setToExplicitIdentityMap(int numEdges); // Mapping 0-->0, 1-->1, 2-->2, 3-->3, etc.
//void createFromTwoPointLoops(const std::vector<Point2d>&, const std::vector<Point2d>&);
void init(); // Empties the map
void print() const;
// Converts mapping m --> n (m > n) to:
// a --> 1
// n --> n
// b --> 1
//
// and mapping m --> n (m < n) to:
// 1 --> a
// m --> m
// 1 --> b
//
// where a = abs(m-n+1)/2 and b = abs(m-n) - a
//
void normalize(int numEdges0, int numEdges1);
void remapIndices(const std::vector<int>& fromIndexMap, const std::vector<int>& toIndexMap);
static const MorphingMap kNull;
enum { kCrossEdgeIsApprox = 1, kBaseEdgeIsApprox = 2 };
private:
class MorphingMapElem
{
public:
MorphingMapElem(int i, int j, int vis = 0) : fromIndex(i), toIndex(j), visibility(vis) {}
int fromIndex;
int toIndex;
int visibility;
};
//std::vector<MorphingMapElem*> mArray;
};
AECMODELER_NAMESPACE_END
#endif
| [
"38715689+xiongzhihui@users.noreply.github.com"
] | 38715689+xiongzhihui@users.noreply.github.com |
446ad44a598270ba5a31427a25bec4f974bf8205 | 9184c4403f1ff36ba7318fa5c08302db0dd37504 | /include/apollo/gc.hpp | c8ff09fce3ca2694e4ad7b75d0c108e62a2a5701 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | Oberon00/apollo | 5c0c13799153deddf68aafccb2767788a4082d4f | 5940d07f277951a7faad5c53eb9e5f44f12c7de7 | refs/heads/master | 2021-01-15T18:14:25.353251 | 2015-09-17T14:31:13 | 2015-09-17T14:31:13 | 25,267,679 | 34 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 2,089 | hpp | // Part of the apollo library -- Copyright (c) Christian Neumüller 2015
// This file is subject to the terms of the BSD 2-Clause License.
// See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause
#ifndef APOLLO_GC_HPP_INCLUDED
#define APOLLO_GC_HPP_INCLUDED APOLLO_GC_HPP_INCLUDED
#include <apollo/detail/meta_util.hpp>
#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <apollo/lua_include.hpp>
#include <type_traits>
namespace apollo {
template <typename T>
int gc_object(lua_State* L) BOOST_NOEXCEPT
{
BOOST_ASSERT(lua_type(L, 1) == LUA_TUSERDATA);
static_cast<T*>(lua_touserdata(L, 1))->~T();
return 0;
}
template <typename T, typename... Args>
inline typename detail::remove_qualifiers<T>::type*
emplace_bare_udata(lua_State* L, Args&&... ctor_args)
{
using obj_t = typename detail::remove_qualifiers<T>::type;
void* uf = lua_newuserdata(L, sizeof(obj_t));
try {
return new(uf) obj_t(std::forward<Args>(ctor_args)...);
} catch (...) {
lua_pop(L, 1);
throw;
}
}
template <typename T>
inline typename detail::remove_qualifiers<T>::type*
push_bare_udata(lua_State* L, T&& o)
{
return emplace_bare_udata<T>(L, std::forward<T>(o));
}
// Note: __gc will not unset metatable.
// Use for objects that cannot be retrieved from untrusted Lua code only.
template <typename T>
typename detail::remove_qualifiers<T>::type*
push_gc_object(lua_State* L, T&& o)
{
using obj_t = typename detail::remove_qualifiers<T>::type;
void* uf = push_bare_udata(L, std::forward<T>(o));
#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable:4127) // Conditional expression is constant.
#endif
if (!std::is_trivially_destructible<obj_t>::value) {
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
lua_createtable(L, 0, 1); // 0 sequence entries, 1 dictionary entry
lua_pushcfunction(L, &gc_object<obj_t>);
lua_setfield(L, -2, "__gc");
lua_setmetatable(L, -2);
}
return static_cast<obj_t*>(uf);
}
} // namespace apollo
#endif // APOLLO_GC_HPP_INCLUDED
| [
"cn00@gmx.at"
] | cn00@gmx.at |
9cb4f059ed372a0a4f3041cea31f267f1da36885 | a4bb94cfe9c0bee937a6ec584e10f6fe126372ff | /Drivers/Video/Console/Console.cpp | 61c3ebf8a02b2cd6a3ad948192fecf6816fce2aa | [] | no_license | MatiasNAmendola/magneto | 564d0bdb3534d4b7118e74cc8b50601afaad10a0 | 33bc34a49a34923908883775f94eb266be5af0f9 | refs/heads/master | 2020-04-05T23:36:22.535156 | 2009-07-04T09:14:01 | 2009-07-04T09:14:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,172 | cpp | /*
* Module Name: Console
* File: Silver\Console\Console.cpp
*
*/
#include "Drivers\Video\Console\Console.h"
#if !defined ( __CONSOLE_CPP_ )
#define __CONSOLE_CPP_
char Console::is_console;
unsigned int Console::last_result;
unsigned char * Console::vid_mem;
unsigned int Console::curr_x, Console::curr_y, Console::c_maxx, Console::c_maxy, Console::textattrib, Console::fgcolor, Console::bgcolor;
const char * CONSOLE_ID = "CONSOLE";
Console console;
unsigned char _40x25_text[] =
{
/* MISC */
0x67,
/* SEQ */
0x03, 0x08, 0x03, 0x00, 0x02,
/* CRTC */
0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0xA0,
0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char _40x50_text[] =
{
/* MISC */
0x67,
/* SEQ */
0x03, 0x08, 0x03, 0x00, 0x02,
/* CRTC */
0x2D, 0x27, 0x28, 0x90, 0x2B, 0xA0, 0xBF, 0x1F,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x04, 0x60,
0x9C, 0x8E, 0x8F, 0x14, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char _80x25_text[] =
{
/* MISC */
0x67,
/* SEQ */
0x03, 0x00, 0x03, 0x00, 0x02,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x50,
0x9C, 0x0E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00
};
unsigned char _80x50_text[] =
{
/* MISC */
0x67,
/* SEQ */
0x03, 0x00, 0x03, 0x00, 0x02,
/* CRTC */
0x5F, 0x4F, 0x50, 0x82, 0x55, 0x81, 0xBF, 0x1F,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x01, 0x40,
0x9C, 0x8E, 0x8F, 0x28, 0x1F, 0x96, 0xB9, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char _90x30_text[] =
{
/* MISC */
0xE7,
/* SEQ */
0x03, 0x01, 0x03, 0x00, 0x02,
/* CRTC */
0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E,
0x00, 0x4F, 0x0D, 0x0E, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x2D, 0x10, 0xE8, 0x05, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char _90x60_text[] =
{
/* MISC */
0xE7,
/* SEQ */
0x03, 0x01, 0x03, 0x00, 0x02,
/* CRTC */
0x6B, 0x59, 0x5A, 0x82, 0x60, 0x8D, 0x0B, 0x3E,
0x00, 0x47, 0x06, 0x07, 0x00, 0x00, 0x00, 0x00,
0xEA, 0x0C, 0xDF, 0x2D, 0x08, 0xE8, 0x05, 0xA3,
0xFF,
/* GC */
0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x0E, 0x00,
0xFF,
/* AC */
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x14, 0x07,
0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
0x0C, 0x00, 0x0F, 0x08, 0x00,
};
unsigned char g_8x8_font[2048] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x7E, 0x81, 0xA5, 0x81, 0xBD, 0x99, 0x81, 0x7E,
0x7E, 0xFF, 0xDB, 0xFF, 0xC3, 0xE7, 0xFF, 0x7E,
0x6C, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00,
0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00,
0x38, 0x7C, 0x38, 0xFE, 0xFE, 0x92, 0x10, 0x7C,
0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x7C,
0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00,
0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF,
0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00,
0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF,
0x0F, 0x07, 0x0F, 0x7D, 0xCC, 0xCC, 0xCC, 0x78,
0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18,
0x3F, 0x33, 0x3F, 0x30, 0x30, 0x70, 0xF0, 0xE0,
0x7F, 0x63, 0x7F, 0x63, 0x63, 0x67, 0xE6, 0xC0,
0x99, 0x5A, 0x3C, 0xE7, 0xE7, 0x3C, 0x5A, 0x99,
0x80, 0xE0, 0xF8, 0xFE, 0xF8, 0xE0, 0x80, 0x00,
0x02, 0x0E, 0x3E, 0xFE, 0x3E, 0x0E, 0x02, 0x00,
0x18, 0x3C, 0x7E, 0x18, 0x18, 0x7E, 0x3C, 0x18,
0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00,
0x7F, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x00,
0x3E, 0x63, 0x38, 0x6C, 0x6C, 0x38, 0x86, 0xFC,
0x00, 0x00, 0x00, 0x00, 0x7E, 0x7E, 0x7E, 0x00,
0x18, 0x3C, 0x7E, 0x18, 0x7E, 0x3C, 0x18, 0xFF,
0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x00,
0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00,
0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00,
0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00,
0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00,
0x00, 0x24, 0x66, 0xFF, 0x66, 0x24, 0x00, 0x00,
0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0xFF, 0xFF, 0x7E, 0x3C, 0x18, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00,
0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00,
0x6C, 0x6C, 0xFE, 0x6C, 0xFE, 0x6C, 0x6C, 0x00,
0x18, 0x7E, 0xC0, 0x7C, 0x06, 0xFC, 0x18, 0x00,
0x00, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xC6, 0x00,
0x38, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0x76, 0x00,
0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00,
0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00,
0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00,
0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30,
0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00,
0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00,
0x7C, 0xCE, 0xDE, 0xF6, 0xE6, 0xC6, 0x7C, 0x00,
0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0xFC, 0x00,
0x78, 0xCC, 0x0C, 0x38, 0x60, 0xCC, 0xFC, 0x00,
0x78, 0xCC, 0x0C, 0x38, 0x0C, 0xCC, 0x78, 0x00,
0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x1E, 0x00,
0xFC, 0xC0, 0xF8, 0x0C, 0x0C, 0xCC, 0x78, 0x00,
0x38, 0x60, 0xC0, 0xF8, 0xCC, 0xCC, 0x78, 0x00,
0xFC, 0xCC, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x00,
0x78, 0xCC, 0xCC, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x78, 0xCC, 0xCC, 0x7C, 0x0C, 0x18, 0x70, 0x00,
0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x00,
0x00, 0x18, 0x18, 0x00, 0x00, 0x18, 0x18, 0x30,
0x18, 0x30, 0x60, 0xC0, 0x60, 0x30, 0x18, 0x00,
0x00, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00, 0x00,
0x60, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x60, 0x00,
0x3C, 0x66, 0x0C, 0x18, 0x18, 0x00, 0x18, 0x00,
0x7C, 0xC6, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00,
0x30, 0x78, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x66, 0x66, 0xFC, 0x00,
0x3C, 0x66, 0xC0, 0xC0, 0xC0, 0x66, 0x3C, 0x00,
0xF8, 0x6C, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00,
0xFE, 0x62, 0x68, 0x78, 0x68, 0x62, 0xFE, 0x00,
0xFE, 0x62, 0x68, 0x78, 0x68, 0x60, 0xF0, 0x00,
0x3C, 0x66, 0xC0, 0xC0, 0xCE, 0x66, 0x3A, 0x00,
0xCC, 0xCC, 0xCC, 0xFC, 0xCC, 0xCC, 0xCC, 0x00,
0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0x1E, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78, 0x00,
0xE6, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0xE6, 0x00,
0xF0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00,
0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0x00,
0xC6, 0xE6, 0xF6, 0xDE, 0xCE, 0xC6, 0xC6, 0x00,
0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00,
0x7C, 0xC6, 0xC6, 0xC6, 0xD6, 0x7C, 0x0E, 0x00,
0xFC, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0xE6, 0x00,
0x7C, 0xC6, 0xE0, 0x78, 0x0E, 0xC6, 0x7C, 0x00,
0xFC, 0xB4, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xFC, 0x00,
0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00,
0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00,
0xC6, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0xC6, 0x00,
0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x30, 0x78, 0x00,
0xFE, 0xC6, 0x8C, 0x18, 0x32, 0x66, 0xFE, 0x00,
0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00,
0xC0, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x02, 0x00,
0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00,
0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF,
0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0xE0, 0x60, 0x60, 0x7C, 0x66, 0x66, 0xDC, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xC0, 0xCC, 0x78, 0x00,
0x1C, 0x0C, 0x0C, 0x7C, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0x38, 0x6C, 0x64, 0xF0, 0x60, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0xE0, 0x60, 0x6C, 0x76, 0x66, 0x66, 0xE6, 0x00,
0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x0C, 0x00, 0x1C, 0x0C, 0x0C, 0xCC, 0xCC, 0x78,
0xE0, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0xE6, 0x00,
0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00,
0x00, 0x00, 0xCC, 0xFE, 0xFE, 0xD6, 0xD6, 0x00,
0x00, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0xCC, 0x00,
0x00, 0x00, 0x78, 0xCC, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x00, 0xDC, 0x66, 0x66, 0x7C, 0x60, 0xF0,
0x00, 0x00, 0x76, 0xCC, 0xCC, 0x7C, 0x0C, 0x1E,
0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x7C, 0xC0, 0x70, 0x1C, 0xF8, 0x00,
0x10, 0x30, 0xFC, 0x30, 0x30, 0x34, 0x18, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x78, 0x30, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xD6, 0xFE, 0x6C, 0x00,
0x00, 0x00, 0xC6, 0x6C, 0x38, 0x6C, 0xC6, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0x00, 0x00, 0xFC, 0x98, 0x30, 0x64, 0xFC, 0x00,
0x1C, 0x30, 0x30, 0xE0, 0x30, 0x30, 0x1C, 0x00,
0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00,
0xE0, 0x30, 0x30, 0x1C, 0x30, 0x30, 0xE0, 0x00,
0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0x00,
0x7C, 0xC6, 0xC0, 0xC6, 0x7C, 0x0C, 0x06, 0x7C,
0x00, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x1C, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0x7E, 0x81, 0x3C, 0x06, 0x3E, 0x66, 0x3B, 0x00,
0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0xE0, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x30, 0x30, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC0, 0x78, 0x0C, 0x38,
0x7E, 0x81, 0x3C, 0x66, 0x7E, 0x60, 0x3C, 0x00,
0xCC, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0xE0, 0x00, 0x78, 0xCC, 0xFC, 0xC0, 0x78, 0x00,
0xCC, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x7C, 0x82, 0x38, 0x18, 0x18, 0x18, 0x3C, 0x00,
0xE0, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0xC6, 0x10, 0x7C, 0xC6, 0xFE, 0xC6, 0xC6, 0x00,
0x30, 0x30, 0x00, 0x78, 0xCC, 0xFC, 0xCC, 0x00,
0x1C, 0x00, 0xFC, 0x60, 0x78, 0x60, 0xFC, 0x00,
0x00, 0x00, 0x7F, 0x0C, 0x7F, 0xCC, 0x7F, 0x00,
0x3E, 0x6C, 0xCC, 0xFE, 0xCC, 0xCC, 0xCE, 0x00,
0x78, 0x84, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0xCC, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0xE0, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x78, 0x84, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xE0, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xCC, 0x00, 0xCC, 0xCC, 0x7C, 0x0C, 0xF8,
0xC3, 0x18, 0x3C, 0x66, 0x66, 0x3C, 0x18, 0x00,
0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00,
0x18, 0x18, 0x7E, 0xC0, 0xC0, 0x7E, 0x18, 0x18,
0x38, 0x6C, 0x64, 0xF0, 0x60, 0xE6, 0xFC, 0x00,
0xCC, 0xCC, 0x78, 0x30, 0xFC, 0x30, 0xFC, 0x30,
0xF8, 0xCC, 0xCC, 0xFA, 0xC6, 0xCF, 0xC6, 0xC3,
0x0E, 0x1B, 0x18, 0x3C, 0x18, 0x18, 0xD8, 0x70,
0x1C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0x76, 0x00,
0x38, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00,
0x00, 0x1C, 0x00, 0x78, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x1C, 0x00, 0xCC, 0xCC, 0xCC, 0x76, 0x00,
0x00, 0xF8, 0x00, 0xB8, 0xCC, 0xCC, 0xCC, 0x00,
0xFC, 0x00, 0xCC, 0xEC, 0xFC, 0xDC, 0xCC, 0x00,
0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00,
0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00,
0x18, 0x00, 0x18, 0x18, 0x30, 0x66, 0x3C, 0x00,
0x00, 0x00, 0x00, 0xFC, 0xC0, 0xC0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFC, 0x0C, 0x0C, 0x00, 0x00,
0xC6, 0xCC, 0xD8, 0x36, 0x6B, 0xC2, 0x84, 0x0F,
0xC3, 0xC6, 0xCC, 0xDB, 0x37, 0x6D, 0xCF, 0x03,
0x18, 0x00, 0x18, 0x18, 0x3C, 0x3C, 0x18, 0x00,
0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00,
0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00,
0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88,
0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA,
0xDB, 0xF6, 0xDB, 0x6F, 0xDB, 0x7E, 0xD7, 0xED,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36,
0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18,
0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36,
0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00,
0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36,
0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36,
0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36,
0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36,
0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00,
0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36,
0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0xC8, 0xDC, 0x76, 0x00,
0x00, 0x78, 0xCC, 0xF8, 0xCC, 0xF8, 0xC0, 0xC0,
0x00, 0xFC, 0xCC, 0xC0, 0xC0, 0xC0, 0xC0, 0x00,
0x00, 0x00, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x00,
0xFC, 0xCC, 0x60, 0x30, 0x60, 0xCC, 0xFC, 0x00,
0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0x70, 0x00,
0x00, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0xC0,
0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x00,
0xFC, 0x30, 0x78, 0xCC, 0xCC, 0x78, 0x30, 0xFC,
0x38, 0x6C, 0xC6, 0xFE, 0xC6, 0x6C, 0x38, 0x00,
0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x6C, 0xEE, 0x00,
0x1C, 0x30, 0x18, 0x7C, 0xCC, 0xCC, 0x78, 0x00,
0x00, 0x00, 0x7E, 0xDB, 0xDB, 0x7E, 0x00, 0x00,
0x06, 0x0C, 0x7E, 0xDB, 0xDB, 0x7E, 0x60, 0xC0,
0x38, 0x60, 0xC0, 0xF8, 0xC0, 0x60, 0x38, 0x00,
0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x00,
0x00, 0x7E, 0x00, 0x7E, 0x00, 0x7E, 0x00, 0x00,
0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x7E, 0x00,
0x60, 0x30, 0x18, 0x30, 0x60, 0x00, 0xFC, 0x00,
0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0xFC, 0x00,
0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0x70,
0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00,
0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00,
0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00,
0x0F, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x3C, 0x1C,
0x58, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00,
0x70, 0x98, 0x30, 0x60, 0xF8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x3C, 0x3C, 0x3C, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
unsigned char g_8x16_font[4096] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0x81, 0xA5, 0x81, 0x81, 0xBD, 0x99, 0x81, 0x81, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0xFF, 0xDB, 0xFF, 0xFF, 0xC3, 0xE7, 0xFF, 0xFF, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x6C, 0xFE, 0xFE, 0xFE, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x7C, 0xFE, 0x7C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0xE7, 0xE7, 0xE7, 0x99, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x7E, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xC3, 0xC3, 0xE7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x42, 0x42, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC3, 0x99, 0xBD, 0xBD, 0x99, 0xC3, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x1E, 0x0E, 0x1A, 0x32, 0x78, 0xCC, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3F, 0x33, 0x3F, 0x30, 0x30, 0x30, 0x30, 0x70, 0xF0, 0xE0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7F, 0x63, 0x7F, 0x63, 0x63, 0x63, 0x63, 0x67, 0xE7, 0xE6, 0xC0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x18, 0x18, 0xDB, 0x3C, 0xE7, 0x3C, 0xDB, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFE, 0xF8, 0xF0, 0xE0, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x02, 0x06, 0x0E, 0x1E, 0x3E, 0xFE, 0x3E, 0x1E, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7F, 0xDB, 0xDB, 0xDB, 0x7B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x00, 0x00, 0x00, 0x00,
0x00, 0x7C, 0xC6, 0x60, 0x38, 0x6C, 0xC6, 0xC6, 0x6C, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x0C, 0xFE, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x60, 0xFE, 0x60, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x6C, 0xFE, 0x6C, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x38, 0x7C, 0x7C, 0xFE, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFE, 0xFE, 0x7C, 0x7C, 0x38, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x66, 0x66, 0x66, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x6C, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x7C, 0xC6, 0xC2, 0xC0, 0x7C, 0x06, 0x86, 0xC6, 0x7C, 0x18, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xC2, 0xC6, 0x0C, 0x18, 0x30, 0x60, 0xC6, 0x86, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0x6C, 0x38, 0x76, 0xDC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x30, 0x30, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x18, 0x0C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0x80, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xCE, 0xD6, 0xD6, 0xE6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x38, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xC0, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0x06, 0x06, 0x3C, 0x06, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0C, 0x1C, 0x3C, 0x6C, 0xCC, 0xFE, 0x0C, 0x0C, 0x0C, 0x1E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xFC, 0x0E, 0x06, 0x06, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x60, 0xC0, 0xC0, 0xFC, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0x06, 0x06, 0x0C, 0x18, 0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x06, 0x06, 0x0C, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x0C, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xDE, 0xDE, 0xDE, 0xDC, 0xC0, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x66, 0x66, 0x66, 0x66, 0xFC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xF8, 0x6C, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x6C, 0xF8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0x66, 0x62, 0x68, 0x78, 0x68, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xDE, 0xC6, 0xC6, 0x66, 0x3A, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xCC, 0xCC, 0xCC, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE6, 0x66, 0x6C, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xF0, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x62, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xEE, 0xFE, 0xFE, 0xD6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xDE, 0x7C, 0x0C, 0x0E, 0x00, 0x00,
0x00, 0x00, 0xFC, 0x66, 0x66, 0x66, 0x7C, 0x6C, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7C, 0xC6, 0xC6, 0x60, 0x38, 0x0C, 0x06, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x7E, 0x7E, 0x5A, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x10, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x6C, 0x6C, 0x38, 0x38, 0x6C, 0x6C, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0x86, 0x0C, 0x18, 0x30, 0x60, 0xC2, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0xC0, 0xE0, 0x70, 0x38, 0x1C, 0x0E, 0x06, 0x02, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x10, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00,
0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x78, 0x6C, 0x66, 0x66, 0x66, 0x66, 0xDC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC0, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1C, 0x0C, 0x0C, 0x3C, 0x6C, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0xCC, 0x78, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x6C, 0x76, 0x66, 0x66, 0x66, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x06, 0x00, 0x0E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x66, 0x66, 0x3C, 0x00,
0x00, 0x00, 0xE0, 0x60, 0x60, 0x66, 0x6C, 0x78, 0x78, 0x6C, 0x66, 0xE6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xEC, 0xFE, 0xD6, 0xD6, 0xD6, 0xD6, 0xD6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xF0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x7C, 0x0C, 0x0C, 0x1E, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x76, 0x62, 0x60, 0x60, 0x60, 0xF0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0xC6, 0x60, 0x38, 0x0C, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x30, 0x30, 0xFC, 0x30, 0x30, 0x30, 0x30, 0x36, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xD6, 0xD6, 0xFE, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x6C, 0x38, 0x38, 0x38, 0x6C, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0xF8, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xCC, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0E, 0x18, 0x18, 0x18, 0x70, 0x18, 0x18, 0x18, 0x18, 0x0E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x70, 0x18, 0x18, 0x18, 0x0E, 0x18, 0x18, 0x18, 0x18, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3C, 0x66, 0xC2, 0xC0, 0xC0, 0xC0, 0xC2, 0x66, 0x3C, 0x0C, 0x06, 0x7C, 0x00, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0C, 0x18, 0x30, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xCC, 0xCC, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x38, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x3C, 0x66, 0x60, 0x60, 0x66, 0x3C, 0x0C, 0x06, 0x3C, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xFE, 0xC0, 0xC0, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x3C, 0x66, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC6, 0xC6, 0x10, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x38, 0x6C, 0x38, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x18, 0x30, 0x60, 0x00, 0xFE, 0x66, 0x60, 0x7C, 0x60, 0x60, 0x66, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x76, 0x36, 0x7E, 0xD8, 0xD8, 0x6E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x3E, 0x6C, 0xCC, 0xCC, 0xFE, 0xCC, 0xCC, 0xCC, 0xCC, 0xCE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x10, 0x38, 0x6C, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x30, 0x78, 0xCC, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x30, 0x18, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7E, 0x06, 0x0C, 0x78, 0x00,
0x00, 0xC6, 0xC6, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC6, 0xC6, 0x00, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x18, 0x3C, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3C, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x64, 0x60, 0xF0, 0x60, 0x60, 0x60, 0x60, 0xE6, 0xFC, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0xF8, 0xCC, 0xCC, 0xF8, 0xC4, 0xCC, 0xDE, 0xCC, 0xCC, 0xCC, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0E, 0x1B, 0x18, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0x70, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0x78, 0x0C, 0x7C, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0C, 0x18, 0x30, 0x00, 0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x30, 0x60, 0x00, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x76, 0xDC, 0x00, 0xDC, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0x00,
0x76, 0xDC, 0x00, 0xC6, 0xE6, 0xF6, 0xFE, 0xDE, 0xCE, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3C, 0x6C, 0x6C, 0x3E, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x30, 0x30, 0x00, 0x30, 0x30, 0x60, 0xC0, 0xC6, 0xC6, 0x7C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0x06, 0x06, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x60, 0xCE, 0x93, 0x06, 0x0C, 0x1F, 0x00, 0x00,
0x00, 0xC0, 0xC0, 0xC2, 0xC6, 0xCC, 0x18, 0x30, 0x66, 0xCE, 0x9A, 0x3F, 0x06, 0x0F, 0x00, 0x00,
0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x3C, 0x3C, 0x3C, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x66, 0xCC, 0x66, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xCC, 0x66, 0x33, 0x66, 0xCC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44, 0x11, 0x44,
0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA,
0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77, 0xDD, 0x77,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x06, 0xF6, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF6, 0x06, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0xF7, 0x00, 0xF7, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x18, 0x18, 0x18, 0x18, 0x1F, 0x18, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0xFF, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x18, 0x18, 0x18, 0x18, 0x18, 0xFF, 0x18, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0xD8, 0xD8, 0xD8, 0xDC, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0xC6, 0xFC, 0xC6, 0xC6, 0xFC, 0xC0, 0xC0, 0xC0, 0x00, 0x00,
0x00, 0x00, 0xFE, 0xC6, 0xC6, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0xFE, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xFE, 0xC6, 0x60, 0x30, 0x18, 0x30, 0x60, 0xC6, 0xFE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xD8, 0xD8, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x7C, 0x60, 0x60, 0xC0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7E, 0x18, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xFE, 0xC6, 0xC6, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x38, 0x6C, 0xC6, 0xC6, 0xC6, 0x6C, 0x6C, 0x6C, 0x6C, 0xEE, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1E, 0x30, 0x18, 0x0C, 0x3E, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0xDB, 0xDB, 0xDB, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x03, 0x06, 0x7E, 0xCF, 0xDB, 0xF3, 0x7E, 0x60, 0xC0, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1C, 0x30, 0x60, 0x60, 0x7C, 0x60, 0x60, 0x60, 0x30, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x7C, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0xC6, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x30, 0x18, 0x0C, 0x06, 0x0C, 0x18, 0x30, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0C, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0C, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0E, 0x1B, 0x1B, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18,
0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xD8, 0xD8, 0xD8, 0x70, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x7E, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0xDC, 0x00, 0x76, 0xDC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x38, 0x6C, 0x6C, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0F, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xEC, 0x6C, 0x6C, 0x3C, 0x1C, 0x00, 0x00, 0x00, 0x00,
0x00, 0xD8, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x70, 0x98, 0x30, 0x60, 0xC8, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
Console::Console()
{
is_console = 0;
if(detect_card_type()==COLOR_CARD) vid_mem = (unsigned char*) 0xB8000;
else if(detect_card_type()==MONO_CARD) vid_mem = (unsigned char*) 0xB0000;
curr_x = curr_y = 0;
c_maxx = 79;
c_maxy = 24;
last_result = 0;
textattrib = WHITE;
bgcolor = BLACK;
fgcolor = WHITE;
set_res(TEXT_90x30);
clrscr();
}
Console::~Console()
{
;
}
int Console::detect_card_type()
{
/* check for monochrome or color VGA emulation */
if((inportb(VGA_MISC_READ) & 0x01) == 1) return COLOR_CARD;
else return MONO_CARD;
}
void Console::update_cursor()
{
unsigned int position = (curr_y * (c_maxx + 1) + curr_x);
outportb(0x3D4, 0x0F);
outportb(0x3D5, (unsigned char)(position&0xFF));
outportb(0x3D4, 0x0E);
outportb(0x3D5, (unsigned char)((position>>8)&0xFF));
}
void Console::scroll_line_up(void)
{
memcpy(vid_mem, vid_mem + (c_maxx+1)*2, (c_maxy*(c_maxx+1)*2));
memsetb(vid_mem + (c_maxx+1) * (c_maxy)*2, NULL, (c_maxx+1)*2);
}
void Console::write_regs(unsigned char *regs)
{
unsigned i;
/* write MISCELLANEOUS reg */
outportb(VGA_MISC_WRITE, *regs);
regs++;
outportb(VGA_INSTAT_READ, 0x00);
/* write SEQUENCER regs */
for(i = 0; i < VGA_NUM_SEQ_REGS; i++)
{
outportb(VGA_SEQ_INDEX, i);
outportb(VGA_SEQ_DATA, *regs);
regs++;
}
/* unlock CRTC registers */
outportb(VGA_CRTC_INDEX, 0x03);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) | 0x80);
outportb(VGA_CRTC_INDEX, 0x11);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) & ~0x80);
/* make sure they remain unlocked */
regs[0x03] |= 0x80;
regs[0x11] &= ~0x80;
/* write CRTC regs */
for(i = 0; i < VGA_NUM_CRTC_REGS; i++)
{
outportb(VGA_CRTC_INDEX, i);
outportb(VGA_CRTC_DATA, *regs);
regs++;
}
/* write GRAPHICS CONTROLLER regs */
for(i = 0; i < VGA_NUM_GC_REGS; i++)
{
outportb(VGA_GC_INDEX, i);
outportb(VGA_GC_DATA, *regs);
regs++;
}
/* write ATTRIBUTE CONTROLLER regs */
for(i = 0; i < VGA_NUM_AC_REGS; i++)
{
(void)inportb(VGA_INSTAT_READ);
outportb(VGA_AC_INDEX, i);
outportb(VGA_AC_WRITE, *regs);
regs++;
}
/* lock 16-color palette and unblank display */
(void)inportb(VGA_INSTAT_READ);
outportb(VGA_AC_INDEX, 0x20);
}
int Console::init()
{
if(is_console == 1)
{
last_result = CONSOLE_ALREADY_INITIALIZED;
return KMSG_FALIURE;
}
else
{
is_console = 1;
cout<<"\nConsole:";
cout<<"\n\tColor Emulation Detected";
cout<<"\n\tVGA+ ";
cout<<c_maxx + 1<<" x "<<c_maxy + 1;
cout<<"\n\tUsing WHITE on BLACK";
return KMSG_SUCCESS;
}
return last_result;
}
int Console::set_res(unsigned int mode)
{
switch(mode)
{
case TEXT_40x25: write_regs(_40x25_text);
c_maxx = 39; c_maxy = 24;
break;
case TEXT_40x50: write_regs(_40x50_text);
c_maxx = 39; c_maxy = 49;
break;
case TEXT_80x25: write_regs(_80x25_text);
c_maxx = 79; c_maxy = 24;
break;
case TEXT_80x50: write_regs(_80x50_text);
c_maxx = 79; c_maxy = 49;
break;
case TEXT_90x30: write_regs(_90x30_text);
c_maxx = 89; c_maxy = 29;
break;
case TEXT_90x60: write_regs(_90x60_text);
c_maxx = 89; c_maxy = 59;
break;
default: last_result = MODE_NOT_SUPPORTED;
break;
};
clrscr();
return last_result;
}
void Console::settextbackground(int col)
{
if(col>7);
else
if(col<0);
else
bgcolor=col;
textattrib=(bgcolor*16)+fgcolor;
}
void Console::settextcolor(int col)
{
if(col > 15);
else
if(col < 0);
else
fgcolor = col;
textattrib = (bgcolor*16) + fgcolor;
}
void Console::settextattrib(int col)
{
textattrib = col;
}
int Console::gettextcolor()
{
return fgcolor;
}
int Console::gettextbgcolor()
{
return bgcolor;
}
int Console::gettextattrib()
{
return textattrib;
}
int Console::wherex(void)
{
return curr_x + 1;
}
int Console::wherey(void)
{
return curr_y + 1;
}
int Console::getmaxx()
{
return c_maxx + 1;
}
int Console::getmaxy()
{
return c_maxy + 1;
}
void Console::gotoxy(unsigned int x, unsigned int y)
{
if((y < 1)&&(x < 1));
else if((y>c_maxy)&&(x>c_maxx));
else
{
curr_x = x - 1; curr_y = y - 1;
update_cursor();
}
}
void Console::clrscr()
{
unsigned int i;
for (i=0; i != (c_maxx * c_maxy); i=i+1) putch(' ');
curr_x = 0; curr_y = 0;
update_cursor();
}
void Console::putch(const unsigned char ch)
{
int i;
switch(ch)
{
case BUFFER_UNDERFLOW: break;
case BUFFER_OVERFLOW: break;
case '\r':
case '\n': curr_x = 0; curr_y = curr_y + 1;
if(curr_y > c_maxy)
{
curr_x = 0; curr_y = c_maxy;
scroll_line_up();
}
break;
case '\t': for(i=0; i!=TAB; i=i+1)
{
putch(' ');
}
break;
case '\b': curr_x = curr_x - 1; //Bug at pos 0,0
if(curr_x < 0)
{
curr_x = c_maxx; curr_y = curr_y - 1;
}
if(curr_y < 0) { curr_x = 0; curr_y = 0; }
vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2)] = ' ';
vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2) + 1] = textattrib;
break;
default: if(ch >= ' ')
{
vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2)] = ch;
vid_mem[(((curr_y * (c_maxx + 1)) + curr_x) * 2) + 1] = textattrib;
curr_x = curr_x + 1;
if(curr_x > c_maxx)
{
putch('\n');
}
}
break;
}
update_cursor();
}
int Console::writeln(const char *buf)
{
while(*buf != '\0')
{
putch(*buf);
buf++;
}
}
void Console::writeint(const unsigned int num)
{
unsigned _num = num;
char _tnum[6];
int _i=0;
while(_num!=0)
{
_tnum[_i]=itoa(_num%10);
_num=_num/10;
_i=_i+1;
}
_tnum[_i]='\0';
for(_i=0;_tnum[_i]!='\0';_i=_i+1);
for(_i=_i-1;_i>=0;_i=_i-1)
{
putch(_tnum[_i]);
}
}
void Console::writeint(const int num)
{
int _num = num;
if(_num < 0)
{
_num = _num * -1;
putch('-');
}
char _tnum[10];
int _i=0;
while(_num!=0)
{
_tnum[_i]=itoa(_num%10);
_num=_num/10;
_i=_i+1;
}
_tnum[_i]='\0';
for(_i=0;_tnum[_i]!='\0';_i=_i+1);
for(_i=_i-1;_i>=0;_i=_i-1)
{
putch(_tnum[_i]);
}
}
#endif
| [
"codemaster.snake@gmail.com"
] | codemaster.snake@gmail.com |
7c608cbddda993f15491fbac404d58d4489c7a49 | 3e6da13329b52b1eec7ebb872523ffcec6b9114c | /L08/E8.4/Program.cpp | 3eb2cc5f94d17718fa7f2bf0cc16a848edf49bb7 | [] | no_license | GreenStaradtil/AU-E19-E1OPRG | 45d0d90e184564313a973b71822b73774ce9b888 | 47eed6970c86e0c054655e11fc56c6e69ebb605d | refs/heads/master | 2022-03-11T03:36:30.180320 | 2019-11-20T01:02:03 | 2019-11-20T01:02:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | cpp | #include <stdio.h>
#include "Weather.h"
int main(int argc, char const *argv[])
{
struct dataset entry1 = { 10, 20, 30, 40 };
struct dataset entry2 = { 1, 2, 3, 4 };
printf_s("Printing dataset with p-by-v\n");
printDataset(entry1);
printf_s("\nPrinting dataset with p-by-r\n");
printDatasetPtr(&entry2);
return 0;
}
| [
"kahr.rasmus@gmail.com"
] | kahr.rasmus@gmail.com |
d47546a32b5232a983a35ef2edf4a8bc0c020a98 | 978f387f5280b3f9a0c43bf9896de9376602fbf0 | /全局钩子注入/keyhook/keyhook/keyhook.cpp | 08c647310258ed4811149ae64c2ba5faa6140624 | [] | no_license | Neilai/game-hack | 313228d347592c5423d15e7fdfa088eda8e4eb81 | 0c42ad71fbfcb2cd89bd05e11071616dcaae727c | refs/heads/master | 2020-05-23T20:59:08.039503 | 2019-05-16T03:29:54 | 2019-05-16T03:29:54 | 186,942,572 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 88 | cpp | // keyhook.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
| [
"1131894367@qq.com"
] | 1131894367@qq.com |
f41fc318e95bf71ec4bf647746e1b9cbc709454c | be0d7f710f38f068faa0aa3227ac24a2a5450024 | /Programación dinámica/35.cpp | d665f277b9a4ddf8c55d13a6842129bac687d7de | [] | no_license | WyrnCael/TAIS | 297b4f1678772c282434ea54f146500bc081898a | a002cde88ffc80d8c73e6f5a48e379b7f202f7e2 | refs/heads/master | 2021-01-21T10:41:31.050264 | 2017-02-28T19:36:00 | 2017-02-28T19:36:08 | 83,471,170 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,511 | cpp | //TAIS04 Fernando Miñambres y Juan José Prieto
//
// El problema se resuelve utilizando una matriz para caluclar recursivamente
// el numero letras que pueden formar un palíndromo desde i hasta j. Siendo:
//
// Para todo j >= i
// Matriz[i][j] = 1; Si i = j;
// Matriz[i][j] = Matriz[i + 1][j - 1] + 2; Si la letra i es igual
// a la letra j.
// Matriz[i][j] = max(Matriz[i + 1][j], Matriz[i][j - 1]); En otro caso
//
// Despues se recorre la solucion cogiendo Matriz[i][j] si la letra i es igual a
// la letra j o recorriendo la matriz por el mayor numero entre Matriz[i][j - 1]
// y [i + 1][j].
//
//El coste de la función es de O(n*n) en tiempo y O(n*n) en espacio adicional, siendo
// n el numero de letras que forman la palabra inicial.
//
#include <fstream>
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <limits>
#include <climits>
#include <string>
#include <array>
#include "Matriz.h"
using namespace std;
string calculaPalindromoMayor(string palabra) {
int n = palabra.length();
Matriz<int> longuitudPalindromos(n, n, 0);
for (int i = 0; i < n; i++)
longuitudPalindromos[i][i] = 1;
for (size_t d = 1; d < n; ++d) { // recorre diagonales
for (size_t i = 0; i < n - d; ++i) { // recorre elementos de diagonal
size_t j = i + d;
if (palabra[i] == palabra[j]) {
longuitudPalindromos[i][j] = longuitudPalindromos[i + 1][j - 1] + 2;
}
else {
longuitudPalindromos[i][j] = max(longuitudPalindromos[i + 1][j], longuitudPalindromos[i][j - 1]);
}
}
}
int max = longuitudPalindromos[0][n - 1];
string resultado(max, '\0');
int j = n - 1, i = 0, pos = 0;
while (pos * 2 < max) {
if (max - (pos * 2) == 1) {
resultado[pos] = palabra[j];
pos++;
i++;
j--;
}
else {
if (palabra[i] == palabra[j]) {
resultado[pos] = palabra[j];
resultado[max - pos - 1] = palabra[j];
pos++;
i++;
j--;
}
else if (longuitudPalindromos[i][j - 1] <= longuitudPalindromos[i + 1][j]) {
i++;
}
else {
j--;
}
}
}
return resultado;
}
bool resuelveCaso() {
string palabra;
cin >> palabra;
if (!cin)
return false;
cout << calculaPalindromoMayor(palabra) << endl;
return true;
}
int main() {
#ifndef DOMJUDGE
std::ifstream in("casos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf());
#endif
while (resuelveCaso()) {
}
#ifndef DOMJUDGE
std::cin.rdbuf(cinbuf);
system("pause");
#endif
return 0;
} | [
"juanjpri@ucm.es"
] | juanjpri@ucm.es |
4ca035595152118991fb1d0867348c2c43067ea8 | 5509788aa5c5bacc053ea21796d3ef5ba878d744 | /Practice/Other/Luogu 1049 装箱问题.cpp | 3775e06c7d21bd96d120dbfe848ad43d8ea8720a | [
"MIT"
] | permissive | SYCstudio/OI | 3c5a6a9c5c9cd93ef653ad77477ad1cd849b8930 | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | refs/heads/master | 2021-06-25T22:29:50.276429 | 2020-10-26T11:57:06 | 2020-10-26T11:57:06 | 108,716,217 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
const int maxV=20001;
const int maxN=40;
const int inf=2147483647;
int V,N;
int weight[maxN];
int F[maxV];
int main()
{
cin>>V>>N;
for (int i=1; i<=N; i++)
cin>>weight[i];
memset(F,0,sizeof(F));
for (int i=1; i<=N; i++)
for (int j=V; j>=weight[i]; j--)
F[j]=max(F[j],F[j-weight[i]]+weight[i]);
cout<<V-F[V]<<endl;
return 0;
}
| [
"1726016246@qq.com"
] | 1726016246@qq.com |
f6951a9e6ca158a4fa5572d21ddeb4c6d7a38237 | 15a35df4de841aa5c504dc4f8778581c00397c87 | /Server1/Engine/Ext/netdsdk/src/Pipe.cpp | 31d81f921e780b5f06b1829a7f38593b40fc99c8 | [] | no_license | binbin88115/server | b6197fef8f35276ff7bdf471a025091d65f96fa9 | e3c178db3b6c6552c60b007cac8ffaa6d3c43c10 | refs/heads/master | 2021-01-15T13:49:38.647852 | 2014-05-05T12:47:20 | 2014-05-05T12:47:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,388 | cpp | #include "Pipe.h"
#include "Debug.h"
#include "SockAcceptor.h"
#include "SockConnector.h"
#include <unistd.h>
#include <stropts.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
Pipe::Pipe ()
{
handles_[0] = NDK_INVALID_HANDLE;
handles_[1] = NDK_INVALID_HANDLE;
}
Pipe::~Pipe ()
{
this->close ();
}
int Pipe::open ()
{
#if 0
InetAddr local_any = InetAddr::addr_any;
InetAddr local_addr;
SockAcceptor acceptor;
SockConnector connector;
SockStream writer;
SockStream reader;
int result = 0;
// Bind listener to any port and then find out what the port was.
if (acceptor.open (local_any) < 0
|| acceptor.get_local_addr (local_addr) != 0)
{
result = -1;
}else
{
InetAddr svr_addr(local_addr.get_port_number (), "127.0.0.1");
// Establish a connection within the same process.
if (connector.connect (writer, svr_addr) != 0)
result = -1;
else if (acceptor.accept (reader) != 0)
{
writer.close ();
result = -1;
}
}
// Close down the acceptor endpoint since we don't need it anymore.
acceptor.close ();
if (result == -1)
return -1;
this->handles_[0] = reader.handle ();
this->handles_[1] = writer.handle ();
int on = 1;
if (::setsockopt (this->handles_[1], IPPROTO_TCP, TCP_NODELAY,
&on,
sizeof(on)) == -1)
{
this->close();
return -1;
}
return 0;
#endif
#if 0
if (::socketpair (AF_UNIX, SOCK_STREAM, 0, this->handles_) == -1)
{
NDK_DBG ("socketpair");
return -1;
}
return 0;
#endif
if (::pipe (this->handles_) == -1)
{
NDK_DBG ("pipe");
return -1;
}
// Enable "msg no discard" mode, which ensures that record
// boundaries are maintained when messages are sent and received.
#if 0
int arg = RMSGN;
if (::ioctl (this->handles_[0],
I_SRDOPT,
(void*)arg) == -1
||
::ioctl (this->handles_[1],
I_SRDOPT,
(void*)arg) == -1
)
{
NDK_DBG ("ioctl pipe handles");
this->close ();
return -1;
}
#endif
return 0;
}
int Pipe::close ()
{
int result = 0;
if (this->handles_[0] != NDK_INVALID_HANDLE)
result = ::close (this->handles_[0]);
handles_[0] = NDK_INVALID_HANDLE;
if (this->handles_[1] != NDK_INVALID_HANDLE)
result |= ::close (this->handles_[1]);
handles_[1] = NDK_INVALID_HANDLE;
return result;
}
| [
"jjl_2009_hi@163.com"
] | jjl_2009_hi@163.com |
a0e7e627330bec274fb795baa3a91f4fafa07f3b | 1a60c841c4cf4159d9badacbe3e3c05dd4340d73 | /week_2/2292_tjdwn9410.cpp | 5e059555ae54c2c8aefb2a330725e5baf1bb8a8c | [] | no_license | sungjunyoung/algorithm-study | e5d38f0569ec7b639ebd905f0ef79398862696d2 | 5fb4bc9fa9f96a0d17a097ed641de01f378ead27 | refs/heads/master | 2020-12-03T03:46:05.244078 | 2017-10-14T08:01:25 | 2017-10-14T08:04:59 | 95,769,994 | 9 | 12 | null | 2017-10-14T08:05:00 | 2017-06-29T11:16:04 | C++ | UTF-8 | C++ | false | false | 299 | cpp | //
// Created by MAC on 2017. 7. 3..
//
#include<iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int N;
int startValue=1;
int res=1;
cin>>N;
while(N>startValue)
{
startValue += res*6;
res++;
}
cout<<res<<endl;
return 0;
} | [
"abc3176@nate.com"
] | abc3176@nate.com |
1ab8431b665fb21edb4324a9093c69c7049ece3d | 8edde9d2e5cea812b4b3db859d2202d0a65cb800 | /Engine/Graphics/GrUTCompress.cpp | 1ead775b05360f91d775fa9a83c1a9a0ed14a5bc | [
"MIT"
] | permissive | shawwn/bootstrap | 751cb00175933f91a2e5695d99373fca46a0778e | 39742d2a4b7d1ab0444d9129152252dfcfb4d41b | refs/heads/master | 2023-04-09T20:41:05.034596 | 2023-03-28T17:43:50 | 2023-03-28T17:43:50 | 130,915,922 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 55,040 | cpp | //----------------------------------------------------------
// File: GrUTCompress.cpp
// Author: Kevin Bray
// Created: 11-17-08
//
// Purpose: To provide compression services for the ubertexture
// worker thread.
//
// Copyright © 2004 Bootstrap Studios. All rights reserved.
//----------------------------------------------------------
#include "graphics_afx.h"
// class header.
#include "GrUTCompress.h"
// project includes.
#include "UHuffman.h"
#ifdef _DEBUG
bool gLibInit = false;
#define UT_CMP_INIT() gLibInit = true;
#define UT_CMP_CHECK_INIT() B_ASSERT( gLibInit );
#else
#define UT_CMP_INIT()
#define UT_CMP_CHECK_INIT()
#endif
// forward declarations.
void ExtractBlockBGRA( unsigned char* bgra, const unsigned char* bgraSource, unsigned int srcWidth,
unsigned int srcX, unsigned int srcY );
void ExtractBlockA( short* v, const unsigned char* vSource, unsigned int bytesPerPel,
unsigned int srcWidth, unsigned int srcX, unsigned int srcY );
void InsertBlockBGRA( unsigned char* bgraDest, unsigned int dstWidth, unsigned int dstX,
unsigned int dstY, unsigned char* bgra );
void InsertBlockA( unsigned char* vDest, unsigned int bytesPerPel, unsigned int dstWidth,
unsigned int dstX, unsigned int dstY, short* v );
void EncodeBlock( UHuffman* encoder, const short* src, const unsigned short* quant,
unsigned char chop );
void DecodeBlock( short* dest, UHuffman* decoder, const unsigned short* quant );
void UnpackYCoCg( unsigned char* bgra, const short* Y, const short* Co, const short* Cg );
void PackYCoCg( short* Y, short* Co, short* Cg, const unsigned char* bgra );
void ForwardDCT( short* dest, const short* coeff, const unsigned short* quant );
void InverseDCT( short* dest, const short* coeff, const unsigned short* quant );
void BuildDXTTables();
void CompressImageDXT1( const unsigned char* argb, unsigned char* dxt1, int width, int height );
void CompressImageDXT5(const unsigned char* argb, BYTE* dxt5, int width, int height);
//==========================================================
// DCT compression tables.
//==========================================================
//----------------------------------------------------------
// quantization table for Y.
static DECLARE_ALIGNED_16( unsigned short, kQuantY[ 64 ] ) =
{
// 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
// 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
5, 11, 10, 16, 28, 68, 80, 80,
12, 12, 14, 18, 32, 73, 90, 110,
14, 13, 16, 30, 51, 87, 138, 112,
14, 17, 28, 36, 80, 174, 160, 124,
18, 28, 47, 88, 136, 255, 206, 154,
30, 42, 86, 128, 162, 208, 226, 184,
60, 128, 156, 174, 206, 241, 240, 202,
144, 184, 190, 196, 224, 200, 206, 198,
};
//----------------------------------------------------------
// quantization table for Co.
static DECLARE_ALIGNED_16( unsigned short, kQuantCo[ 64 ] ) =
{
// 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
// 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
18, 20, 24, 32, 34, 38, 41, 50,
20, 30, 32, 40, 42, 50, 52, 58,
24, 32, 40, 45, 48, 52, 56, 60,
32, 40, 45, 56, 64, 70, 88, 102,
34, 42, 48, 64, 78, 92, 110, 120,
38, 50, 52, 70, 92, 120, 128, 160,
41, 52, 56, 88, 110, 128, 220, 190,
50, 58, 60, 102, 120, 160, 190, 190,
};
//----------------------------------------------------------
// quantization table for Cg.
static DECLARE_ALIGNED_16( unsigned short, kQuantCg[ 64 ] ) =
{
// 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
// 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
18, 20, 24, 32, 34, 38, 41, 50,
20, 30, 32, 40, 42, 50, 52, 58,
24, 32, 40, 45, 48, 52, 56, 60,
32, 40, 45, 56, 64, 70, 88, 102,
34, 42, 48, 64, 78, 92, 110, 120,
38, 50, 52, 70, 92, 120, 128, 160,
41, 52, 56, 88, 110, 128, 220, 190,
50, 58, 60, 102, 120, 160, 190, 190,
};
//----------------------------------------------------------
// quantization table for XY tangent space normal maps.
static DECLARE_ALIGNED_16( unsigned short, kQuantXY[ 64 ] ) =
{
8, 9, 11, 13, 16, 21, 24, 27,
9, 9, 12, 15, 18, 22, 24, 29,
11, 12, 15, 19, 22, 25, 28, 32,
13, 15, 19, 24, 27, 30, 34, 37,
16, 18, 22, 27, 34, 39, 41, 46,
21, 22, 25, 30, 39, 48, 59, 74,
24, 24, 28, 34, 41, 59, 81, 109,
27, 29, 32, 37, 46, 74, 109, 160,
};
//----------------------------------------------------------
// matrix block swizzle pattern 0.
static DECLARE_ALIGNED_16( const unsigned int, kDCTBlockSwizzle0[ 64 ] ) =
{
0,
1, 8,
16, 9, 2,
3, 10, 17, 24,
32, 25, 18, 11, 4,
5, 12, 19, 26, 33, 40,
48, 41, 34, 27, 20, 13, 6,
7, 14, 21, 28, 35, 42, 49, 56,
57, 50, 43, 36, 29, 22, 15,
23, 30, 37, 44, 51, 58,
59, 52, 45, 38, 31,
39, 46, 53, 60,
61, 54, 47,
55, 62,
63,
};
#define ONE_OVER_SQRT2 ( 0.5f / Sqrt( 2.0f ) )
#define DCT_COS( i ) ( 0.5f * Cos( i * PI / 16.0f ) )
//----------------------------------------------------------
// the DCT matrix.
static DECLARE_ALIGNED_16( const float, kDCTMatrix[ 64 ] ) =
{
ONE_OVER_SQRT2, ONE_OVER_SQRT2, ONE_OVER_SQRT2, ONE_OVER_SQRT2, ONE_OVER_SQRT2, ONE_OVER_SQRT2, ONE_OVER_SQRT2, ONE_OVER_SQRT2,
DCT_COS( 1 ), DCT_COS( 3 ), DCT_COS( 5 ), DCT_COS( 7 ), DCT_COS( 9 ), DCT_COS( 11 ), DCT_COS( 13 ), DCT_COS( 15 ),
DCT_COS( 2 ), DCT_COS( 6 ), DCT_COS( 10 ), DCT_COS( 14 ), DCT_COS( 18 ), DCT_COS( 22 ), DCT_COS( 26 ), DCT_COS( 30 ),
DCT_COS( 3 ), DCT_COS( 9 ), DCT_COS( 15 ), DCT_COS( 21 ), DCT_COS( 27 ), DCT_COS( 33 ), DCT_COS( 39 ), DCT_COS( 45 ),
DCT_COS( 4 ), DCT_COS( 12 ), DCT_COS( 20 ), DCT_COS( 28 ), DCT_COS( 36 ), DCT_COS( 44 ), DCT_COS( 52 ), DCT_COS( 60 ),
DCT_COS( 5 ), DCT_COS( 15 ), DCT_COS( 25 ), DCT_COS( 35 ), DCT_COS( 45 ), DCT_COS( 55 ), DCT_COS( 65 ), DCT_COS( 75 ),
DCT_COS( 6 ), DCT_COS( 18 ), DCT_COS( 30 ), DCT_COS( 42 ), DCT_COS( 54 ), DCT_COS( 66 ), DCT_COS( 78 ), DCT_COS( 90 ),
DCT_COS( 7 ), DCT_COS( 21 ), DCT_COS( 35 ), DCT_COS( 49 ), DCT_COS( 63 ), DCT_COS( 77 ), DCT_COS( 91 ), DCT_COS( 105 ),
};
//----------------------------------------------------------
// the transposed DCT matrix.
static DECLARE_ALIGNED_16( const float, kDCTMatrixT[ 64 ] ) =
{
ONE_OVER_SQRT2, DCT_COS( 1 ), DCT_COS( 2 ), DCT_COS( 3 ), DCT_COS( 4 ), DCT_COS( 5 ), DCT_COS( 6 ), DCT_COS( 7 ),
ONE_OVER_SQRT2, DCT_COS( 3 ), DCT_COS( 6 ), DCT_COS( 9 ), DCT_COS( 12 ), DCT_COS( 15 ), DCT_COS( 18 ), DCT_COS( 21 ),
ONE_OVER_SQRT2, DCT_COS( 5 ), DCT_COS( 10 ), DCT_COS( 15 ), DCT_COS( 20 ), DCT_COS( 25 ), DCT_COS( 30 ), DCT_COS( 35 ),
ONE_OVER_SQRT2, DCT_COS( 7 ), DCT_COS( 14 ), DCT_COS( 21 ), DCT_COS( 28 ), DCT_COS( 35 ), DCT_COS( 42 ), DCT_COS( 49 ),
ONE_OVER_SQRT2, DCT_COS( 9 ), DCT_COS( 18 ), DCT_COS( 27 ), DCT_COS( 36 ), DCT_COS( 45 ), DCT_COS( 54 ), DCT_COS( 63 ),
ONE_OVER_SQRT2, DCT_COS( 11 ), DCT_COS( 22 ), DCT_COS( 33 ), DCT_COS( 44 ), DCT_COS( 55 ), DCT_COS( 66 ), DCT_COS( 77 ),
ONE_OVER_SQRT2, DCT_COS( 13 ), DCT_COS( 26 ), DCT_COS( 39 ), DCT_COS( 52 ), DCT_COS( 65 ), DCT_COS( 78 ), DCT_COS( 91 ),
ONE_OVER_SQRT2, DCT_COS( 15 ), DCT_COS( 30 ), DCT_COS( 45 ), DCT_COS( 60 ), DCT_COS( 75 ), DCT_COS( 90 ), DCT_COS( 105 ),
};
// entropy encoding score macro.
#define SV( x ) ( ( ( 256 - ( ( x ) & 0x7F ) ) * ( 256 - ( ( x ) & 0x7F ) ) ) >> 6 )
//----------------------------------------------------------
// global tables.
static DECLARE_ALIGNED_16( short, gDCTCoeff[ 64 ] );
static DECLARE_ALIGNED_16( short, gEncodeCo[ 64 ] );
static DECLARE_ALIGNED_16( short, gEncodeCg[ 64 ] );
static DECLARE_ALIGNED_16( short, gEncodeY0[ 64 ] );
static DECLARE_ALIGNED_16( short, gEncodeY1[ 64 ] );
static DECLARE_ALIGNED_16( short, gEncodeY2[ 64 ] );
static DECLARE_ALIGNED_16( short, gEncodeY3[ 64 ] );
static DECLARE_ALIGNED_16( unsigned char, gEncodeBGRA[ 256 ] );
static DECLARE_ALIGNED_16( short, gDecodeCo[ 64 ] );
static DECLARE_ALIGNED_16( short, gDecodeCg[ 64 ] );
static DECLARE_ALIGNED_16( short, gDecodeY0[ 64 ] );
static DECLARE_ALIGNED_16( short, gDecodeY1[ 64 ] );
static DECLARE_ALIGNED_16( short, gDecodeY2[ 64 ] );
static DECLARE_ALIGNED_16( short, gDecodeY3[ 64 ] );
static DECLARE_ALIGNED_16( unsigned char, gDecodeBGRA[ 256 ] );
//**********************************************************
// Global functions
//**********************************************************
//----------------------------------------------------------
void GrUTInitCompressor()
{
BuildDXTTables();
UT_CMP_INIT();
}
//----------------------------------------------------------
void GrUTCompressBGRX( UHuffman* encoder, const unsigned char* bgrx, unsigned char chop )
{
UT_CMP_CHECK_INIT();
// iterate over each 8x8 block of pixels.
for ( unsigned int y = 0; y < 8; y += 2 )
{
for ( unsigned int x = 0; x < 8; x += 2 )
{
// extract 4 8x8 blocks.
ExtractBlockBGRA( gEncodeBGRA, bgrx, 64, x + 0, y + 0 );
PackYCoCg( gEncodeY0, gEncodeCo + 0, gEncodeCg + 0, gEncodeBGRA );
ExtractBlockBGRA( gEncodeBGRA, bgrx, 64, x + 1, y + 0 );
PackYCoCg( gEncodeY1, gEncodeCo + 4, gEncodeCg + 4, gEncodeBGRA );
ExtractBlockBGRA( gEncodeBGRA, bgrx, 64, x + 0, y + 1 );
PackYCoCg( gEncodeY2, gEncodeCo + 32, gEncodeCg + 32, gEncodeBGRA );
ExtractBlockBGRA( gEncodeBGRA, bgrx, 64, x + 1, y + 1 );
PackYCoCg( gEncodeY3, gEncodeCo + 36, gEncodeCg + 36, gEncodeBGRA );
// store the subsampled Co and Cg values.
EncodeBlock( encoder, gEncodeCo, kQuantCo, chop );
EncodeBlock( encoder, gEncodeCg, kQuantCg, chop );
// store Y values.
EncodeBlock( encoder, gEncodeY0, kQuantY, chop );
EncodeBlock( encoder, gEncodeY1, kQuantY, chop );
EncodeBlock( encoder, gEncodeY2, kQuantY, chop );
EncodeBlock( encoder, gEncodeY3, kQuantY, chop );
}
}
}
//----------------------------------------------------------
void GrUTCompressA( UHuffman* encoder, const unsigned char* a, unsigned int bytesPerPel, unsigned char chop )
{
UT_CMP_CHECK_INIT();
// iterate over each 8x8 block of pixels.
for ( unsigned int y = 0; y < 8; ++y )
{
for ( unsigned int x = 0; x < 8; ++x )
{
// extract the block and adjust so that we have -128..127 values.
ExtractBlockA( gEncodeY0, a, bytesPerPel, 64, x, y );
// encode the X and Y values.
EncodeBlock( encoder, gEncodeY0, kQuantY, chop );
}
}
}
//----------------------------------------------------------
void GrUTDecompressBGRX( unsigned char* bgrx, UHuffman* decoder )
{
UT_CMP_CHECK_INIT();
// iterate over 8x8 blocks of pixels.
for ( unsigned int y = 0; y < 8; y += 2 )
{
for ( unsigned int x = 0; x < 8; x += 2 )
{
// decode subsampled Co and Cg values.
DecodeBlock( gDecodeCo, decoder, kQuantCo );
DecodeBlock( gDecodeCg, decoder, kQuantCg );
// decode Y values.
DecodeBlock( gDecodeY0, decoder, kQuantY );
DecodeBlock( gDecodeY1, decoder, kQuantY );
DecodeBlock( gDecodeY2, decoder, kQuantY );
DecodeBlock( gDecodeY3, decoder, kQuantY );
// unpack colors and insert into the destination block.
UnpackYCoCg( gDecodeBGRA, gDecodeY0, gDecodeCo + 0, gDecodeCg + 0 );
InsertBlockBGRA( bgrx, 64, x + 0, y + 0, gDecodeBGRA );
UnpackYCoCg( gDecodeBGRA, gDecodeY1, gDecodeCo + 4, gDecodeCg + 4 );
InsertBlockBGRA( bgrx, 64, x + 1, y + 0, gDecodeBGRA );
UnpackYCoCg( gDecodeBGRA, gDecodeY2, gDecodeCo + 32, gDecodeCg + 32 );
InsertBlockBGRA( bgrx, 64, x + 0, y + 1, gDecodeBGRA );
UnpackYCoCg( gDecodeBGRA, gDecodeY3, gDecodeCo + 36, gDecodeCg + 36 );
InsertBlockBGRA( bgrx, 64, x + 1, y + 1, gDecodeBGRA );
}
}
}
//----------------------------------------------------------
void GrUTDecompressA( unsigned char* a, unsigned int bytesPerPel, UHuffman* decoder )
{
UT_CMP_CHECK_INIT();
// iterate over 8x8 blocks of pixels.
for ( unsigned int y = 0; y < 8; ++y )
{
for ( unsigned int x = 0; x < 8; ++x )
{
// decode X and Y values.
DecodeBlock( gDecodeY0, decoder, kQuantY );
// insert the block into the outgoing stream.
InsertBlockA( a, bytesPerPel, 64, x, y, gDecodeY0 );
}
}
}
//----------------------------------------------------------
void GrUTCompressDXT5( unsigned char* destSurface, unsigned int destStride, unsigned char* bgra )
{
UT_CMP_CHECK_INIT();
B_ASSERT( false );
}
//----------------------------------------------------------
void GrUTCompressDXT5XY( unsigned char* destSurface, unsigned int destStride, unsigned char* xy )
{
UT_CMP_CHECK_INIT();
B_ASSERT( false );
}
//**********************************************************
// File local functions
//**********************************************************
//----------------------------------------------------------
void ExtractBlockBGRA( unsigned char* bgra, const unsigned char* bgraSource, unsigned int srcWidth,
unsigned int srcX, unsigned int srcY )
{
unsigned int stride = 4 * srcWidth;
const unsigned char* scan = bgraSource + srcY * stride + srcX * 4;
for ( unsigned int y = 0; y < 8; ++y, scan += stride )
{
const unsigned char* pel = scan;
for ( unsigned int x = 0; x < 8; ++x, pel += 4, bgra += 4 )
{
bgra[ 0 ] = pel[ 0 ];
bgra[ 1 ] = pel[ 1 ];
bgra[ 2 ] = pel[ 2 ];
bgra[ 3 ] = pel[ 3 ];
}
}
}
//----------------------------------------------------------
void ExtractBlockA( short* dstA, const unsigned char* aSource, unsigned int bytesPerPel,
unsigned int srcWidth, unsigned int srcX, unsigned int srcY )
{
unsigned int stride = srcWidth * bytesPerPel;
const unsigned char* scan = aSource + srcY * stride + srcX * bytesPerPel;
for ( unsigned int y = 0; y < 8; ++y, scan += stride )
{
const unsigned char* pel = scan;
for ( unsigned int x = 0; x < 8; ++x, pel += bytesPerPel, ++dstA )
*dstA = *pel - 128;
}
}
//----------------------------------------------------------
void InsertBlockBGRA( unsigned char* bgraDest, unsigned int dstWidth, unsigned int dstX,
unsigned int dstY, unsigned char* bgra )
{
unsigned int stride = dstWidth * 4;
unsigned char* scan = bgraDest + dstY * stride + dstX * 4;
for ( unsigned int y = 0; y < 8; ++y, scan += stride )
{
unsigned char* pel = scan;
for ( unsigned int x = 0; x < 8; ++x, pel += 4, bgra += 4 )
{
pel[ 0 ] = bgra[ 0 ];
pel[ 1 ] = bgra[ 1 ];
pel[ 2 ] = bgra[ 2 ];
pel[ 3 ] = bgra[ 3 ];
}
}
}
//----------------------------------------------------------
void InsertBlockA( unsigned char* aDest, unsigned int bytesPerPel, unsigned int dstWidth,
unsigned int dstX, unsigned int dstY, short* srcA )
{
// note: The YCoCg decoding stage writes values as XMMWORDs.
// This means that the right way to do this is to read the values
// in as XMMWORDs, replace the alpha components, and then write
// them back out. If we don't do this, then we hit a store
// forwarding problem.
unsigned int stride = dstWidth * 2;
unsigned char* scan = aDest + dstY * stride + dstX * 2;
for ( unsigned int y = 0; y < 8; ++y, scan += stride )
{
unsigned char* pel = scan;
for ( unsigned int x = 0; x < 8; ++x, pel += bytesPerPel, ++srcA )
*pel = Clamp( *srcA + 128, 0, 255 );
}
}
//----------------------------------------------------------
void EncodeBlock( UHuffman* encoder, const short* src, const unsigned short* quant, unsigned char chop )
{
// perform the DCT and quantize.
ForwardDCT( gDCTCoeff, src, quant );
// store the DC term.
encoder->WriteValue( ( unsigned char )( gDCTCoeff[ 0 ] & 0xFF ) );
encoder->WriteValue( ( unsigned char )( gDCTCoeff[ 0 ] >> 8 ) );
// now encode the data as a run of bytes.
for ( unsigned int i = 1; i < 64; ++i )
{
// simply write out non-zero coefficients.
unsigned char curCoeff = ( unsigned char )( gDCTCoeff[ kDCTBlockSwizzle0[ i ] ] );
if ( abs( curCoeff ) > chop )
{
// note that we reserve these two values for the encoding
// process. Therefor, if any values match it, we must
// clamp it to 0x82 (-126).
if ( curCoeff == 0x80 || curCoeff == 0x81 )
curCoeff = 0x82;
encoder->WriteValue( curCoeff );
}
else
{
// write out a run of zeros.
unsigned int runLength = 0;
for ( unsigned int j = i + 1; j < 64; ++j )
{
if ( abs( gDCTCoeff[ kDCTBlockSwizzle0[ j ] ] ) <= chop )
++runLength;
else
break;
}
// if we have a run length greater than one, then we
// should encode it. Otherwise, simply write the 0.
if ( runLength > 0 )
{
// make sure we advance i.
i += runLength;
// write out the zero-length run if necessary.
if ( i < 63 )
{
encoder->WriteValue( 0x80 );
encoder->WriteValue( runLength );
}
else
{
// end the block.
encoder->WriteValue( 0x81 );
}
}
else
{
encoder->WriteValue( 0 );
}
}
}
}
//----------------------------------------------------------
void DecodeBlock( short* dest, UHuffman* decoder, const unsigned short* quant )
{
// buffer to hold decoded (but still quantized) coefficients.
short cur = 0;
// clear the coefficient matrix to zero.
MemSet( gDCTCoeff, 0, sizeof( gDCTCoeff ) );
// read the AC term.
gDCTCoeff[ 0 ] = decoder->ReadValue();
gDCTCoeff[ 0 ] |= decoder->ReadValue() << 8;
// huffman and RLE decode the data into the buffer.
for ( unsigned int i = 1; i < 64; ++i )
{
// determine if we have a run of deltas or a run of zeros.
unsigned char value = decoder->ReadValue();
if ( value == 0x80 )
{
// we have a run of zeros.
i += decoder->ReadValue();
}
else if ( value == 0x81 )
{
break;
}
else
{
// write out the new value.
gDCTCoeff[ kDCTBlockSwizzle0[ i ] ] = ( short )( char )value;
}
}
// perform the iDCT.
InverseDCT( dest, gDCTCoeff, quant );
}
//----------------------------------------------------------
void UnpackYCoCg( unsigned char* bgra, const short* Y, const short* Co, const short* Cg )
{
// This function takes in one block of Co Cg values that each
// have a stride of 8 values. However, only 4 values from each
// row are actually used because they are subsampled.
#if 1
// convert two rows at a time to RGB.
for ( unsigned int i = 0; i < 4; ++i, bgra += 64 )
{
__asm
{
mov eax, Co
mov ebx, Cg
mov esi, Y
mov edi, bgra
#if 0
short curY = Y[ x ];
short curCo = Co[ ( y >> 1 ) * 8 + ( x >> 1 ) ];
short curCg = Cg[ ( y >> 1 ) * 8 + ( x >> 1 ) ];
short t = curY - ( curCg >> 1 );
unsigned char g = Max( curCg + t, 0 );
unsigned char b = Max( t - ( curCo >> 1 ), 0 );
unsigned char r = Max( b + curCo, 0 );
#endif
; load the first line of Co and Cg.
movq mm0, [ eax ]
movq mm1, [ ebx ]
; promote Co and Cg to 8 words and replicate them across
; adjacent channels.
movq2dq xmm0, mm0
pshufd xmm0, xmm0, 01000100b ; x32103210
pshuflw xmm0, xmm0, 01010000b ; x32101100
pshufhw xmm0, xmm0, 11111010b ; x33221100
movq2dq xmm2, mm1
pshufd xmm2, xmm2, 01000100b ; x32103210
pshuflw xmm2, xmm2, 01010000b ; x32101100
pshufhw xmm2, xmm2, 11111010b ; x33221100
; calculate Co >> 1 and Cg >> 1
movdqa xmm1, xmm0
movdqa xmm3, xmm2
psraw xmm1, 1
psraw xmm3, 1
; load in two rows of Y and calculate G.
movdqa xmm4, [ esi + 0 ]
movdqa xmm5, [ esi + 16 ]
psubsw xmm4, xmm3 ; xmm4 = t = curY - ( curCg >> 1 )
psubsw xmm5, xmm3 ; xmm5 = t = curY - ( curCg >> 1 )
; xmm2, xmm3 // green.
; xmm4, xmm5 // blue.
; xmm6, xmm7 // red.
; calculate two rows of green.
movdqa xmm7, xmm5
paddsw xmm7, xmm2
paddsw xmm2, xmm4
movdqa xmm3, xmm7
; calculate blue as t - ( curCo >> 1 )
psubsw xmm4, xmm1
psubsw xmm5, xmm1
; calculate red as b + curCo
movdqa xmm6, xmm4
movdqa xmm7, xmm5
paddsw xmm6, xmm0
paddsw xmm7, xmm0
; pack the first set of blue and green into xmm0
packuswb xmm1, xmm2
packuswb xmm0, xmm4
punpckhbw xmm0, xmm1 ; xmm0 = bgbgbgbgbgbgbgbg
; pack the first set of red and 0 into xmm1
packuswb xmm1, xmm6
pxor xmm4, xmm4
punpckhbw xmm1, xmm4 ; xmm1 = r0r0r0r0r0r0r0r0
; pack the second set of blue and green into xmm2
packuswb xmm3, xmm3
packuswb xmm2, xmm5
punpckhbw xmm2, xmm3 ; xmm2 = bgbgbgbgbgbgbgbg
; pack the second set of red and 0 into xmm3
packuswb xmm3, xmm7
punpckhbw xmm3, xmm4 ; xmm3 = r0r0r0r0r0r0r0r0
; split the values across four registers.
movdqa xmm4, xmm0
punpcklwd xmm4, xmm1 ; xmm4 = bgr0bgr0bgr0bgr0
movdqa xmm5, xmm0
punpckhwd xmm5, xmm1 ; xmm5 = bgr0bgr0bgr0bgr0
movdqa xmm6, xmm2
punpcklwd xmm6, xmm3 ; xmm6 = bgr0bgr0bgr0bgr0
movdqa xmm7, xmm2
punpckhwd xmm7, xmm3 ; xmm7 = bgr0bgr0bgr0bgr0
; store the output.
movdqa [edi+ 0], xmm4
movdqa [edi+16], xmm5
movdqa [edi+32], xmm6
movdqa [edi+48], xmm7
};
Y += 16;
Co += 8;
Cg += 8;
}
// clear MMX state.
__asm emms;
#else
for ( unsigned int y = 0; y < 8; ++y, Y += 8 )
{
for ( unsigned int x = 0; x < 8; ++x, ++red, ++green, ++blue )
{
short curY = Y[ x ];
short curCo = Co[ ( y >> 1 ) * 8 + ( x >> 1 ) ];
short curCg = Cg[ ( y >> 1 ) * 8 + ( x >> 1 ) ];
short t = curY - ( curCg >> 1 );
unsigned char g = Max( curCg + t, 0 );
unsigned char b = Max( t - ( curCo >> 1 ), 0 );
unsigned char r = Max( b + curCo, 0 );
// unsigned char r = curY + curCo - curCg;
// unsigned char g = curY + curCg;
// unsigned char b = curY - curCo - curCg;
*red = r;
*green = g;
*blue = b;
}
}
#endif
}
//----------------------------------------------------------
void PackYCoCg( short* Y, short* Co, short* Cg, const unsigned char* bgra )
{
// This function takes in one block of Co Cg values that each
// have a stride of 8 values. However, only 4 values from each
// row are actually written to because they are subsampled.
// convert two rows at a time to RGB.
short CoFull[ 64 ];
short CgFull[ 64 ];
for ( unsigned int i = 0; i < 64; ++i, bgra += 4 )
{
// get RGB components and expand them to 16-bits.
short r = bgra[ 2 ];
short g = bgra[ 1 ];
short b = bgra[ 0 ];
CoFull[ i ] = ( r - b );
short t = b + ( CoFull[ i ] >> 1 );
CgFull[ i ] = ( g - t );
Y[ i ] = ( t + ( CgFull[ i ] >> 1 ) );
}
// subsample CoCg.
short* CoSrc = CoFull;
short* CgSrc = CgFull;
for ( unsigned int y = 0; y < 4; ++y, Co += 8, Cg += 8, CoSrc += 16, CgSrc += 16 )
{
for ( unsigned int x = 0; x < 4; ++x )
{
#if 1
short CoSum = CoSrc[ x + x + 0 ] + CoSrc[ x + x + 1 ] +
CoSrc[ x + x + 8 ] + CoSrc[ x + x + 9 ];
short CgSum = CgSrc[ x + x + 0 ] + CgSrc[ x + x + 1 ] +
CgSrc[ x + x + 8 ] + CgSrc[ x + x + 9 ];
Co[ x ] = ( CoSum + 2 ) >> 2;
Cg[ x ] = ( CgSum + 2 ) >> 2;
#else
Co[ x ] = CoSrc[ x + x ];
Cg[ x ] = CgSrc[ x + x ];
#endif
}
}
}
//----------------------------------------------------------
void ForwardDCT( short* dest, const short* coeff, const unsigned short* quant )
{
short temp1[ 64 ];
float temp2[ 64 ];
for ( unsigned int i = 0; i < 64; ++i )
temp1[ i ] = coeff[ i ];
// perform an 8x8 matrix multiply.
for ( unsigned int i = 0; i < 8; ++i )
{
for ( unsigned int j = 0; j < 8; ++j )
{
// convert the current coefficient to floating point.
float curCoeff = 0;
for ( unsigned int k = 0; k < 8; ++k )
curCoeff += kDCTMatrix[ 8 * i + k ] * temp1[ 8 * k + j ];
// store the current coefficient.
temp2[ 8 * i + j ] = ( curCoeff );
}
}
// perform an 8x8 matrix multiply.
for ( unsigned int i = 0; i < 8; ++i )
{
for ( unsigned int j = 0; j < 8; ++j )
{
// convert the current coefficient to floating point.
float curCoeff = 0;
for ( unsigned int k = 0; k < 8; ++k )
curCoeff += temp2[ 8 * i + k ] * kDCTMatrixT[ 8 * k + j ];
// quantize and store the current coefficient.
dest[ 8 * i + j ] = ( short )( ( curCoeff / quant[ 8 * i + j ] ) + 0.5f );
}
}
}
//----------------------------------------------------------
#define BITS_INV_ACC 5 // 4 or 5 for IEEE
#define SHIFT_INV_ROW 16 - BITS_INV_ACC
#define SHIFT_INV_COL 1 + BITS_INV_ACC
#define RND_INV_ROW 1024 * (6 - BITS_INV_ACC) // 1 << (SHIFT_INV_ROW-1)
#define RND_INV_COL 16 * (BITS_INV_ACC - 3) // 1 << (SHIFT_INV_COL-1)
#define DUP4( X ) (X),(X),(X),(X)
#define DUP8( X ) (X),(X),(X),(X),(X),(X),(X),(X)
#define BIAS_SCALE( X ) ( X / ( BITS_INV_ACC - 3 ) )
static DECLARE_ALIGNED_16( short, M128_tg_1_16[8] ) = { DUP8( 13036 ) }; // tg * (1<<16) + 0.5
static DECLARE_ALIGNED_16( short, M128_tg_2_16[8] ) = { DUP8( 27146 ) }; // tg * (1<<16) + 0.5
static DECLARE_ALIGNED_16( short, M128_tg_3_16[8] ) = { DUP8( -21746 ) }; // tg * (1<<16) + 0.5
static DECLARE_ALIGNED_16( short, M128_cos_4_16[8] ) = { DUP8( -19195 ) }; // cos * (1<<16) + 0.5
// Table for rows 0,4 - constants are multiplied by cos_4_16
static DECLARE_ALIGNED_16( short, M128_tab_i_04[] ) =
{
16384, 21407, 16384, 8867, // w05 w04 w01 w00
16384, -8867, 16384, -21407, // w13 w12 w09 w08
16384, 8867, -16384, -21407, // w07 w06 w03 w02
-16384, 21407, 16384, -8867, // w15 w14 w11 w10
22725, 19266, 19266, -4520, // w21 w20 w17 w16
12873, -22725, 4520, -12873, // w29 w28 w25 w24
12873, 4520, -22725, -12873, // w23 w22 w19 w18
4520, 19266, 19266, -22725 // w31 w30 w27 w26
};
// Table for rows 1,7 - constants are multiplied by cos_1_16
static DECLARE_ALIGNED_16( short, M128_tab_i_17[] ) =
{
22725, 29692, 22725, 12299, // w05 w04 w01 w00
22725, -12299, 22725, -29692, // w13 w12 w09 w08
22725, 12299, -22725, -29692, // w07 w06 w03 w02
-22725, 29692, 22725, -12299, // w15 w14 w11 w10
31521, 26722, 26722, -6270, // w21 w20 w17 w16
17855, -31521, 6270, -17855, // w29 w28 w25 w24
17855, 6270, -31521, -17855, // w23 w22 w19 w18
6270, 26722, 26722, -31521 // w31 w30 w27 w26
};
// Table for rows 2,6 - constants are multiplied by cos_2_16
static DECLARE_ALIGNED_16( short, M128_tab_i_26[] ) =
{
21407, 27969, 21407, 11585, // w05 w04 w01 w00
21407, -11585, 21407, -27969, // w13 w12 w09 w08
21407, 11585, -21407, -27969, // w07 w06 w03 w02
-21407, 27969, 21407, -11585, // w15 w14 w11 w10
29692, 25172, 25172, -5906, // w21 w20 w17 w16
16819, -29692, 5906, -16819, // w29 w28 w25 w24
16819, 5906, -29692, -16819, // w23 w22 w19 w18
5906, 25172, 25172, -29692 // w31 w30 w27 w26
};
// Table for rows 3,5 - constants are multiplied by cos_3_16
static DECLARE_ALIGNED_16( short, M128_tab_i_35[] ) = {
19266, 25172, 19266, 10426, // w05 w04 w01 w00
19266, -10426, 19266, -25172, // w13 w12 w09 w08
19266, 10426, -19266, -25172, // w07 w06 w03 w02
-19266, 25172, 19266, -10426, // w15 w14 w11 w10
26722, 22654, 22654, -5315, // w21 w20 w17 w16
15137, -26722, 5315, -15137, // w29 w28 w25 w24
15137, 5315, -26722, -15137, // w23 w22 w19 w18
5315, 22654, 22654, -26722 // w31 w30 w27 w26
};
static DECLARE_ALIGNED_16( const unsigned int, rounder_0[4] ) = { DUP4( RND_INV_ROW - BIAS_SCALE( 2048 ) + 65536 ) };
static DECLARE_ALIGNED_16( const unsigned int, rounder_1[4] ) = { DUP4( RND_INV_ROW + BIAS_SCALE( 3755 ) ) };
static DECLARE_ALIGNED_16( const unsigned int, rounder_2[4] ) = { DUP4( RND_INV_ROW + BIAS_SCALE( 2472 ) ) };
static DECLARE_ALIGNED_16( const unsigned int, rounder_3[4] ) = { DUP4( RND_INV_ROW + BIAS_SCALE( 1361 ) ) };
static DECLARE_ALIGNED_16( const unsigned int, rounder_4[4] ) = { DUP4( RND_INV_ROW + BIAS_SCALE( 0 ) ) };
static DECLARE_ALIGNED_16( const unsigned int, rounder_5[4] ) = { DUP4( RND_INV_ROW - BIAS_SCALE( 1139 ) ) };
static DECLARE_ALIGNED_16( const unsigned int, rounder_6[4] ) = { DUP4( RND_INV_ROW - BIAS_SCALE( 1024 ) ) };
static DECLARE_ALIGNED_16( const unsigned int, rounder_7[4] ) = { DUP4( RND_INV_ROW - BIAS_SCALE( 1301 ) ) };
#define DCT_8_INV_ROW( table1, table2, rounder1, rounder2 ) \
__asm pshuflw xmm0, xmm0, 0xD8 \
__asm pshufhw xmm0, xmm0, 0xD8 \
__asm pshufd xmm3, xmm0, 0x55 \
__asm pshufd xmm1, xmm0, 0 \
__asm pshufd xmm2, xmm0, 0xAA \
__asm pshufd xmm0, xmm0, 0xFF \
__asm pmaddwd xmm1, [table1+ 0] \
__asm pmaddwd xmm2, [table1+16] \
__asm pmaddwd xmm3, [table1+32] \
__asm pmaddwd xmm0, [table1+48] \
__asm paddd xmm0, xmm3 \
__asm pshuflw xmm4, xmm4, 0xD8 \
__asm pshufhw xmm4, xmm4, 0xD8 \
__asm paddd xmm1, rounder1 \
__asm pshufd xmm6, xmm4, 0xAA \
__asm pshufd xmm5, xmm4, 0 \
__asm pmaddwd xmm5, [table2+ 0] \
__asm paddd xmm5, rounder2 \
__asm pmaddwd xmm6, [table2+16] \
__asm pshufd xmm7, xmm4, 0x55 \
__asm pmaddwd xmm7, [table2+32] \
__asm pshufd xmm4, xmm4, 0xFF \
__asm pmaddwd xmm4, [table2+48] \
__asm paddd xmm1, xmm2 \
__asm movdqa xmm2, xmm1 \
__asm psubd xmm2, xmm0 \
__asm psrad xmm2, SHIFT_INV_ROW \
__asm pshufd xmm2, xmm2, 0x1B \
__asm paddd xmm0, xmm1 \
__asm psrad xmm0, SHIFT_INV_ROW \
__asm paddd xmm5, xmm6 \
__asm packssdw xmm0, xmm2 \
__asm paddd xmm4, xmm7 \
__asm movdqa xmm6, xmm5 \
__asm psubd xmm6, xmm4 \
__asm psrad xmm6, SHIFT_INV_ROW \
__asm paddd xmm4, xmm5 \
__asm psrad xmm4, SHIFT_INV_ROW \
__asm pshufd xmm6, xmm6, 0x1B \
__asm packssdw xmm4, xmm6
#define DCT_8_INV_COL_8 \
__asm movdqa xmm6, xmm4 \
__asm movdqa xmm2, xmm0 \
__asm movdqa xmm3, XMMWORD PTR [edx+3*16] \
__asm movdqa xmm1, XMMWORD PTR M128_tg_3_16 \
__asm pmulhw xmm0, xmm1 \
__asm movdqa xmm5, XMMWORD PTR M128_tg_1_16 \
__asm pmulhw xmm1, xmm3 \
__asm paddsw xmm1, xmm3 \
__asm pmulhw xmm4, xmm5 \
__asm movdqa xmm7, XMMWORD PTR [edx+6*16] \
__asm pmulhw xmm5, [edx+1*16] \
__asm psubsw xmm5, xmm6 \
__asm movdqa xmm6, xmm5 \
__asm paddsw xmm4, [edx+1*16] \
__asm paddsw xmm0, xmm2 \
__asm paddsw xmm0, xmm3 \
__asm psubsw xmm2, xmm1 \
__asm movdqa xmm1, xmm0 \
__asm movdqa xmm3, XMMWORD PTR M128_tg_2_16 \
__asm pmulhw xmm7, xmm3 \
__asm pmulhw xmm3, [edx+2*16] \
__asm paddsw xmm0, xmm4 \
__asm psubsw xmm4, xmm1 \
__asm movdqa [edx+7*16], xmm0 \
__asm psubsw xmm5, xmm2 \
__asm paddsw xmm6, xmm2 \
__asm movdqa [edx+3*16], xmm6 \
__asm movdqa xmm1, xmm4 \
__asm movdqa xmm0, XMMWORD PTR M128_cos_4_16 \
__asm movdqa xmm2, xmm0 \
__asm paddsw xmm4, xmm5 \
__asm psubsw xmm1, xmm5 \
__asm paddsw xmm7, [edx+2*16] \
__asm psubsw xmm3, [edx+6*16] \
__asm movdqa xmm6, [edx] \
__asm pmulhw xmm0, xmm1 \
__asm movdqa xmm5, [edx+4*16] \
__asm paddsw xmm5, xmm6 \
__asm psubsw xmm6, [edx+4*16] \
__asm pmulhw xmm2, xmm4 \
__asm paddsw xmm4, xmm2 \
__asm movdqa xmm2, xmm5 \
__asm psubsw xmm2, xmm7 \
__asm paddsw xmm0, xmm1 \
__asm paddsw xmm5, xmm7 \
__asm movdqa xmm1, xmm6 \
__asm movdqa xmm7, [edx+7*16] \
__asm paddsw xmm7, xmm5 \
__asm psraw xmm7, SHIFT_INV_COL \
__asm movdqa [edx], xmm7 \
__asm paddsw xmm6, xmm3 \
__asm psubsw xmm1, xmm3 \
__asm movdqa xmm7, xmm1 \
__asm movdqa xmm3, xmm6 \
__asm paddsw xmm6, xmm4 \
__asm psraw xmm6, SHIFT_INV_COL \
__asm movdqa [edx+1*16], xmm6 \
__asm paddsw xmm1, xmm0 \
__asm psraw xmm1, SHIFT_INV_COL \
__asm movdqa [edx+2*16], xmm1 \
__asm movdqa xmm1, [edx+3*16] \
__asm movdqa xmm6, xmm1 \
__asm psubsw xmm7, xmm0 \
__asm psraw xmm7, SHIFT_INV_COL \
__asm movdqa [edx+5*16], xmm7 \
__asm psubsw xmm5, [edx+7*16] \
__asm psraw xmm5, SHIFT_INV_COL \
__asm movdqa [edx+7*16], xmm5 \
__asm psubsw xmm3, xmm4 \
__asm paddsw xmm6, xmm2 \
__asm psubsw xmm2, xmm1 \
__asm psraw xmm6, SHIFT_INV_COL \
__asm movdqa [edx+3*16], xmm6 \
__asm psraw xmm2, SHIFT_INV_COL \
__asm movdqa [edx+4*16], xmm2 \
__asm psraw xmm3, SHIFT_INV_COL \
__asm movdqa [edx+6*16], xmm3
#define DEQUANTIZE( reg, mem ) __asm pmullw reg, mem
void InverseDCT( short *dest, const short *coeff, const unsigned short *quant )
{
__asm mov eax, coeff
__asm mov edx, dest
__asm mov esi, quant
__asm movdqa xmm0, XMMWORD PTR[eax+16*0] // row 0
__asm movdqa xmm4, XMMWORD PTR[eax+16*2] // row 2
DEQUANTIZE( xmm0, XMMWORD PTR[esi+16*0] )
DEQUANTIZE( xmm4, XMMWORD PTR[esi+16*2] )
DCT_8_INV_ROW( M128_tab_i_04, M128_tab_i_26, rounder_0, rounder_2 );
__asm movdqa XMMWORD PTR[edx+16*0], xmm0
__asm movdqa XMMWORD PTR[edx+16*2], xmm4
__asm movdqa xmm0, XMMWORD PTR[eax+16*4] // row 4
__asm movdqa xmm4, XMMWORD PTR[eax+16*6] // row 6
DEQUANTIZE( xmm0, XMMWORD PTR[esi+16*4] )
DEQUANTIZE( xmm4, XMMWORD PTR[esi+16*6] )
DCT_8_INV_ROW( M128_tab_i_04, M128_tab_i_26, rounder_4, rounder_6 );
__asm movdqa XMMWORD PTR[edx+16*4], xmm0
__asm movdqa XMMWORD PTR[edx+16*6], xmm4
__asm movdqa xmm0, XMMWORD PTR[eax+16*3] // row 3
__asm movdqa xmm4, XMMWORD PTR[eax+16*1] // row 1
DEQUANTIZE( xmm0, XMMWORD PTR[esi+16*3] )
DEQUANTIZE( xmm4, XMMWORD PTR[esi+16*1] )
DCT_8_INV_ROW( M128_tab_i_35, M128_tab_i_17, rounder_3, rounder_1 );
__asm movdqa XMMWORD PTR[edx+16*3], xmm0
__asm movdqa XMMWORD PTR[edx+16*1], xmm4
__asm movdqa xmm0, XMMWORD PTR[eax+16*5] // row 5
__asm movdqa xmm4, XMMWORD PTR[eax+16*7] // row 7
DEQUANTIZE( xmm0, XMMWORD PTR[esi+16*5] )
DEQUANTIZE( xmm4, XMMWORD PTR[esi+16*7] )
DCT_8_INV_ROW( M128_tab_i_35, M128_tab_i_17, rounder_5, rounder_7 );
DCT_8_INV_COL_8
}
//**********************************************************
// Implementation of the extreme DXT algorithm in SSE2.
//**********************************************************
unsigned int kColorDividerTable[768];
unsigned int kAlphaDividerTable[256];
unsigned int kColorIndicesTable[256];
unsigned int kAlphaIndicesTable[640];
DECLARE_ALIGNED_16( const unsigned char, kSSEByte0[16] ) = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEWord1[16] ) = { 0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00,0x01,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEWord8[16] ) = { 0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00,0x08,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEBoundsMask[16] ) = { 0x00,0x1F,0x00,0x1F,0xE0,0x07,0xE0,0x07,0x00,0xF8,0x00,0xF8,0x00,0xFF,0xFF,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEBoundScale[16] ) = { 0x20,0x00,0x20,0x00,0x08,0x00,0x08,0x00,0x00,0x01,0x00,0x01,0x00,0x01,0x01,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesMask0[16] ) = { 0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00,0xFF,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesMask1[16] ) = { 0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00,0x00,0xFF,0x00,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesMask2[16] ) = { 0x08,0x08,0x08,0x00,0x08,0x08,0x08,0x00,0x08,0x08,0x08,0x00,0x08,0x08,0x08,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesScale0[16] ) = { 0x01,0x00,0x04,0x00,0x10,0x00,0x40,0x00,0x01,0x00,0x04,0x00,0x10,0x00,0x40,0x00 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesScale1[16] ) = { 0x01,0x00,0x04,0x00,0x01,0x00,0x08,0x00,0x10,0x00,0x40,0x00,0x00,0x01,0x00,0x08 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesScale2[16] ) = { 0x01,0x04,0x10,0x40,0x01,0x04,0x10,0x40,0x01,0x04,0x10,0x40,0x01,0x04,0x10,0x40 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesScale3[16] ) = { 0x01,0x04,0x01,0x04,0x01,0x08,0x01,0x08,0x01,0x04,0x01,0x04,0x01,0x08,0x01,0x08 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesScale4[16] ) = { 0x01,0x00,0x10,0x00,0x01,0x00,0x00,0x01,0x01,0x00,0x10,0x00,0x01,0x00,0x00,0x01 };
DECLARE_ALIGNED_16( const unsigned char, kSSEIndicesScale[16] ) = { 0x00,0x02,0x04,0x06,0x01,0x03,0x05,0x07,0x08,0x0A,0x0C,0x0E,0x09,0x0B,0x0D,0x0F };
// temporary stores. This avoids stack frame generation for aligned
// local variables (ebx).
DECLARE_ALIGNED_16( unsigned char, gDXTMin[32] );
DECLARE_ALIGNED_16( unsigned char, gDXTRange[32] );
DECLARE_ALIGNED_16( unsigned char, gDXTBounds[32] );
DECLARE_ALIGNED_16( unsigned char, gDXTIndices[64] );
//----------------------------------------------------------
void BuildDXTTables()
{
// build the color divider table.
for ( int i = 0; i < 768; ++i )
kColorDividerTable[i] = ( ( ( 1 << 15 ) / ( i + 1 ) ) << 16 ) | ( ( 1 << 15 ) / ( i + 1 ) );
// build the alpha divider table.
for ( int i = 0; i < 256; ++i )
kAlphaDividerTable[i] = ( ( ( 1 << 16 ) / ( i + 1 ) ) << 16 );
// build the color indices table.
const unsigned char kColorIndexLUT[] =
{
1, 3, 2, 0,
};
for ( int i = 0; i < 256; ++i )
{
unsigned char ci3 = kColorIndexLUT[ ( i & 0xC0 ) >> 6 ] << 6;
unsigned char ci2 = kColorIndexLUT[ ( i & 0x30 ) >> 4 ] << 4;
unsigned char ci1 = kColorIndexLUT[ ( i & 0x0C ) >> 2 ] << 2;
unsigned char ci0 = kColorIndexLUT[ ( i & 0x03 ) >> 0 ] << 0;
kColorIndicesTable[ i ] = ci3 | ci2 | ci1 | ci0;
}
// build the alpha indices table.
const int kShiftLeft[] = { 0, 1, 2, 0, 1, 2, 3, 0, 1, 2 };
const int kShiftRight[] = { 0, 0, 0, 2, 2, 2, 2, 1, 1, 1 };
const unsigned short kAlphaIndex[] = { 1, 7, 6, 5, 4, 3, 2, 0 };
for ( int j = 0; j < 10; ++j )
{
int sl = kShiftLeft[ j ] * 6;
int sr = kShiftRight[ j ] * 2;
for ( int i = 0; i < 64; ++i )
{
unsigned short ai1 = kAlphaIndex[ ( i & 0x38 ) >> 3 ] << 3;
unsigned short ai0 = kAlphaIndex[ ( i & 0x07 ) >> 0 ] << 0;
kAlphaIndicesTable[ ( j * 64 ) + i ] = ( ( ai1 | ai0 ) << sl ) >> sr;
}
}
}
//----------------------------------------------------------
void CompressImageDXT1( const unsigned char* argb, unsigned char* dxt1, int width, int height )
{
int x_count;
int y_count;
__asm
{
mov esi, DWORD PTR argb // src
mov edi, DWORD PTR dxt1 // dst
mov eax, DWORD PTR height
mov DWORD PTR y_count, eax
y_loop:
mov eax, DWORD PTR width
mov DWORD PTR x_count, eax
x_loop:
mov eax, DWORD PTR width // width * 1
lea ebx, DWORD PTR [eax + eax*2] // width * 3
movdqa xmm0, XMMWORD PTR [esi + 0] // src + width * 0 + 0
movdqa xmm3, XMMWORD PTR [esi + eax*4 + 0] // src + width * 4 + 0
movdqa xmm1, xmm0
pmaxub xmm0, xmm3
pmaxub xmm0, XMMWORD PTR [esi + eax*8 + 0] // src + width * 8 + 0
pmaxub xmm0, XMMWORD PTR [esi + ebx*4 + 0] // src + width * 12 + 0
pminub xmm1, xmm3
pminub xmm1, XMMWORD PTR [esi + eax*8 + 0] // src + width * 8 + 0
pminub xmm1, XMMWORD PTR [esi + ebx*4 + 0] // src + width * 12 + 0
pshufd xmm2, xmm0, 0x4E
pshufd xmm3, xmm1, 0x4E
pmaxub xmm0, xmm2
pminub xmm1, xmm3
pshufd xmm2, xmm0, 0xB1
pshufd xmm3, xmm1, 0xB1
pmaxub xmm0, xmm2
pminub xmm1, xmm3
movdqa xmm4, XMMWORD PTR [esi + 16] // src + width * 0 + 16
movdqa xmm7, XMMWORD PTR [esi + eax*4 + 16] // src + width * 4 + 16
movdqa xmm5, xmm4
pmaxub xmm4, xmm7
pmaxub xmm4, XMMWORD PTR [esi + eax*8 + 16] // src + width * 8 + 16
pmaxub xmm4, XMMWORD PTR [esi + ebx*4 + 16] // src + width * 12 + 16
pminub xmm5, xmm7
pminub xmm5, XMMWORD PTR [esi + eax*8 + 16] // src + width * 8 + 16
pminub xmm5, XMMWORD PTR [esi + ebx*4 + 16] // src + width * 12 + 16
pshufd xmm6, xmm4, 0x4E
pshufd xmm7, xmm5, 0x4E
pmaxub xmm4, xmm6
pminub xmm5, xmm7
pshufd xmm6, xmm4, 0xB1
pshufd xmm7, xmm5, 0xB1
pmaxub xmm4, xmm6
pminub xmm5, xmm7
movdqa XMMWORD PTR gDXTMin[ 0], xmm1
movdqa XMMWORD PTR gDXTMin[16], xmm5
movdqa xmm7, XMMWORD PTR kSSEByte0
punpcklbw xmm0, xmm7
punpcklbw xmm4, xmm7
punpcklbw xmm1, xmm7
punpcklbw xmm5, xmm7
movdqa xmm2, xmm0
movdqa xmm6, xmm4
psubw xmm2, xmm1
psubw xmm6, xmm5
movq MMWORD PTR gDXTRange[ 0], xmm2
movq MMWORD PTR gDXTRange[16], xmm6
psrlw xmm2, 4
psrlw xmm6, 4
psubw xmm0, xmm2
psubw xmm4, xmm6
paddw xmm1, xmm2
paddw xmm5, xmm6
punpcklwd xmm0, xmm1
pmullw xmm0, XMMWORD PTR kSSEBoundScale
pand xmm0, XMMWORD PTR kSSEBoundsMask
movdqa XMMWORD PTR gDXTBounds[ 0], xmm0
punpcklwd xmm4, xmm5
pmullw xmm4, XMMWORD PTR kSSEBoundScale
pand xmm4, XMMWORD PTR kSSEBoundsMask
movdqa XMMWORD PTR gDXTBounds[16], xmm4
movzx ecx, WORD PTR gDXTRange [ 0]
movzx edx, WORD PTR gDXTRange [16]
mov eax, DWORD PTR gDXTBounds[ 0]
mov ebx, DWORD PTR gDXTBounds[16]
shr eax, 8
shr ebx, 8
or eax, DWORD PTR gDXTBounds[ 4]
or ebx, DWORD PTR gDXTBounds[20]
or eax, DWORD PTR gDXTBounds[ 8]
or ebx, DWORD PTR gDXTBounds[24]
mov DWORD PTR [edi + 0], eax
mov DWORD PTR [edi + 8], ebx
add cx, WORD PTR gDXTRange [ 2]
add dx, WORD PTR gDXTRange [18]
add cx, WORD PTR gDXTRange [ 4]
add dx, WORD PTR gDXTRange [20]
mov ecx, DWORD PTR kColorDividerTable[ecx*4]
mov edx, DWORD PTR kColorDividerTable[edx*4]
movzx eax, WORD PTR [edi + 0]
xor ax, WORD PTR [edi + 2]
cmovz ecx, eax
movzx ebx, WORD PTR [edi + 8]
xor bx, WORD PTR [edi + 10]
cmovz edx, ebx
mov eax, DWORD PTR width // width * 1
lea ebx, DWORD PTR [eax + eax*2] // width * 3
movdqa xmm0, XMMWORD PTR [esi + 0] // src + width * 0 + 0
movdqa xmm1, XMMWORD PTR [esi + eax*4 + 0] // src + width * 4 + 0
movdqa xmm7, XMMWORD PTR gDXTMin[ 0]
psubb xmm0, xmm7
psubb xmm1, xmm7
movdqa xmm2, XMMWORD PTR [esi + eax*8 + 0] // src + width * 8 + 0
movdqa xmm3, XMMWORD PTR [esi + ebx*4 + 0] // src + width * 12 + 0
psubb xmm2, xmm7
psubb xmm3, xmm7
movdqa xmm4, xmm0
movdqa xmm5, xmm1
movdqa xmm6, XMMWORD PTR kSSEIndicesMask0
movdqa xmm7, XMMWORD PTR kSSEIndicesMask1
pand xmm0, xmm6
pand xmm1, xmm6
pmaddwd xmm0, XMMWORD PTR kSSEWord8
pmaddwd xmm1, XMMWORD PTR kSSEWord8
pand xmm4, xmm7
pand xmm5, xmm7
psrlw xmm4, 5
psrlw xmm5, 5
paddw xmm0, xmm4
paddw xmm1, xmm5
movdqa xmm4, xmm2
movdqa xmm5, xmm3
pand xmm2, xmm6
pand xmm3, xmm6
pmaddwd xmm2, XMMWORD PTR kSSEWord8
pmaddwd xmm3, XMMWORD PTR kSSEWord8
pand xmm4, xmm7
pand xmm5, xmm7
psrlw xmm4, 5
psrlw xmm5, 5
paddw xmm2, xmm4
paddw xmm3, xmm5
movd xmm7, ecx
pshufd xmm7, xmm7, 0x00
packssdw xmm0, xmm1
pmulhw xmm0, xmm7
pmaddwd xmm0, XMMWORD PTR kSSEIndicesScale0
packssdw xmm2, xmm3
pmulhw xmm2, xmm7
pmaddwd xmm2, XMMWORD PTR kSSEIndicesScale0
packssdw xmm0, xmm2
pmaddwd xmm0, XMMWORD PTR kSSEWord1
movdqa XMMWORD PTR gDXTIndices[ 0], xmm0
movdqa xmm0, XMMWORD PTR [esi + 16] // src + width * 0 + 16
movdqa xmm1, XMMWORD PTR [esi + eax*4 + 16] // src + width * 4 + 16
movdqa xmm7, XMMWORD PTR gDXTMin[16]
psubb xmm0, xmm7
psubb xmm1, xmm7
movdqa xmm2, XMMWORD PTR [esi + eax*8 + 16] // src + width * 8 + 16
movdqa xmm3, XMMWORD PTR [esi + ebx*4 + 16] // src + width * 12 + 16
psubb xmm2, xmm7
psubb xmm3, xmm7
movdqa xmm4, xmm0
movdqa xmm5, xmm1
movdqa xmm6, XMMWORD PTR kSSEIndicesMask0
movdqa xmm7, XMMWORD PTR kSSEIndicesMask1
pand xmm4, xmm7
pand xmm5, xmm7
psrlw xmm4, 5
psrlw xmm5, 5
pand xmm0, xmm6
pand xmm1, xmm6
pmaddwd xmm0, XMMWORD PTR kSSEWord8
pmaddwd xmm1, XMMWORD PTR kSSEWord8
paddw xmm0, xmm4
paddw xmm1, xmm5
movdqa xmm4, xmm2
movdqa xmm5, xmm3
pand xmm4, xmm7
pand xmm5, xmm7
psrlw xmm4, 5
psrlw xmm5, 5
pand xmm2, xmm6
pand xmm3, xmm6
pmaddwd xmm2, XMMWORD PTR kSSEWord8
pmaddwd xmm3, XMMWORD PTR kSSEWord8
paddw xmm2, xmm4
paddw xmm3, xmm5
movd xmm7, edx
pshufd xmm7, xmm7, 0x00
packssdw xmm0, xmm1
pmulhw xmm0, xmm7
pmaddwd xmm0, XMMWORD PTR kSSEIndicesScale0
packssdw xmm2, xmm3
pmulhw xmm2, xmm7
pmaddwd xmm2, XMMWORD PTR kSSEIndicesScale0
packssdw xmm0, xmm2
pmaddwd xmm0, XMMWORD PTR kSSEWord1
movdqa XMMWORD PTR gDXTIndices[32], xmm0
movzx eax, BYTE PTR gDXTIndices[ 0]
movzx ebx, BYTE PTR gDXTIndices[ 4]
mov cl, BYTE PTR kColorIndicesTable[eax*1 + 0]
mov ch, BYTE PTR kColorIndicesTable[ebx*1 + 0]
mov BYTE PTR [edi + 4], cl
mov BYTE PTR [edi + 5], ch
movzx eax, BYTE PTR gDXTIndices[ 8]
movzx ebx, BYTE PTR gDXTIndices[12]
mov dl, BYTE PTR kColorIndicesTable[eax*1 + 0]
mov dh, BYTE PTR kColorIndicesTable[ebx*1 + 0]
mov BYTE PTR [edi + 6], dl
mov BYTE PTR [edi + 7], dh
movzx eax, BYTE PTR gDXTIndices[32]
movzx ebx, BYTE PTR gDXTIndices[36]
mov cl, BYTE PTR kColorIndicesTable[eax*1 + 0]
mov ch, BYTE PTR kColorIndicesTable[ebx*1 + 0]
mov BYTE PTR [edi + 12], cl
mov BYTE PTR [edi + 13], ch
movzx eax, BYTE PTR gDXTIndices[40]
movzx ebx, BYTE PTR gDXTIndices[44]
mov dl, BYTE PTR kColorIndicesTable[eax*1 + 0]
mov dh, BYTE PTR kColorIndicesTable[ebx*1 + 0]
mov BYTE PTR [edi + 14], dl
mov BYTE PTR [edi + 15], dh
add esi, 32 // src += 32
add edi, 16 // dst += 16
sub DWORD PTR x_count, 8
jnz x_loop
mov eax, DWORD PTR width // width * 1
lea ebx, DWORD PTR [eax + eax*2] // width * 3
lea esi, DWORD PTR [esi + ebx*4] // src += width * 12
sub DWORD PTR y_count, 4
jnz y_loop
}
}
//----------------------------------------------------------
void CompressImageDXT5( const unsigned char* argb, BYTE* dxt5, int width, int height )
{
int x_count;
int y_count;
__asm
{
mov esi, DWORD PTR argb // src
mov edi, DWORD PTR dxt5 // dst
mov eax, DWORD PTR height
mov DWORD PTR y_count, eax
y_loop:
mov eax, DWORD PTR width
mov DWORD PTR x_count, eax
x_loop:
mov eax, DWORD PTR width // width * 1
lea ebx, DWORD PTR [eax + eax*2] // width * 3
movdqa xmm0, XMMWORD PTR [esi + 0] // src + width * 0 + 0
movdqa xmm3, XMMWORD PTR [esi + eax*4 + 0] // src + width * 4 + 0
movdqa xmm1, xmm0
pmaxub xmm0, xmm3
pminub xmm1, xmm3
pmaxub xmm0, XMMWORD PTR [esi + eax*8 + 0] // src + width * 8 + 0
pminub xmm1, XMMWORD PTR [esi + eax*8 + 0] // src + width * 8 + 0
pmaxub xmm0, XMMWORD PTR [esi + ebx*4 + 0] // src + width * 12 + 0
pminub xmm1, XMMWORD PTR [esi + ebx*4 + 0] // src + width * 12 + 0
pshufd xmm2, xmm0, 0x4E
pmaxub xmm0, xmm2
pshufd xmm3, xmm1, 0x4E
pminub xmm1, xmm3
pshufd xmm2, xmm0, 0xB1
pmaxub xmm0, xmm2
pshufd xmm3, xmm1, 0xB1
pminub xmm1, xmm3
movdqa xmm4, XMMWORD PTR [esi + 16] // src + width * 0 + 16
movdqa xmm7, XMMWORD PTR [esi + eax*4 + 16] // src + width * 4 + 16
movdqa xmm5, xmm4
pmaxub xmm4, xmm7
pminub xmm5, xmm7
pmaxub xmm4, XMMWORD PTR [esi + eax*8 + 16] // src + width * 8 + 16
pminub xmm5, XMMWORD PTR [esi + eax*8 + 16] // src + width * 8 + 16
pmaxub xmm4, XMMWORD PTR [esi + ebx*4 + 16] // src + width * 12 + 16
pminub xmm5, XMMWORD PTR [esi + ebx*4 + 16] // src + width * 12 + 16
pshufd xmm6, xmm4, 0x4E
pmaxub xmm4, xmm6
pshufd xmm7, xmm5, 0x4E
pminub xmm5, xmm7
pshufd xmm6, xmm4, 0xB1
pmaxub xmm4, xmm6
pshufd xmm7, xmm5, 0xB1
pminub xmm5, xmm7
movdqa XMMWORD PTR gDXTMin[ 0], xmm1
movdqa XMMWORD PTR gDXTMin[16], xmm5
movdqa xmm7, XMMWORD PTR kSSEByte0
punpcklbw xmm0, xmm7
punpcklbw xmm4, xmm7
punpcklbw xmm1, xmm7
punpcklbw xmm5, xmm7
movdqa xmm2, xmm0
movdqa xmm6, xmm4
psubw xmm2, xmm1
psubw xmm6, xmm5
movq MMWORD PTR gDXTRange[ 0], xmm2
movq MMWORD PTR gDXTRange[16], xmm6
psrlw xmm2, 4
psrlw xmm6, 4
psubw xmm0, xmm2
psubw xmm4, xmm6
paddw xmm1, xmm2
paddw xmm5, xmm6
punpcklwd xmm0, xmm1
pmullw xmm0, XMMWORD PTR kSSEBoundScale
pand xmm0, XMMWORD PTR kSSEBoundsMask
movdqa XMMWORD PTR gDXTBounds[ 0], xmm0
punpcklwd xmm4, xmm5
pmullw xmm4, XMMWORD PTR kSSEBoundScale
pand xmm4, XMMWORD PTR kSSEBoundsMask
movdqa XMMWORD PTR gDXTBounds[16], xmm4
mov eax, DWORD PTR gDXTBounds[ 0]
mov ebx, DWORD PTR gDXTBounds[16]
shr eax, 8
shr ebx, 8
movzx ecx, WORD PTR gDXTBounds[13]
movzx edx, WORD PTR gDXTBounds[29]
mov DWORD PTR [edi + 0], ecx
mov DWORD PTR [edi + 16], edx
or eax, DWORD PTR gDXTBounds[ 4]
or ebx, DWORD PTR gDXTBounds[20]
or eax, DWORD PTR gDXTBounds[ 8]
or ebx, DWORD PTR gDXTBounds[24]
mov DWORD PTR [edi + 8], eax
mov DWORD PTR [edi + 24], ebx
movzx eax, WORD PTR gDXTRange [ 6]
movzx ebx, WORD PTR gDXTRange [22]
mov eax, DWORD PTR kAlphaDividerTable[eax*4]
mov ebx, DWORD PTR kAlphaDividerTable[ebx*4]
movzx ecx, WORD PTR gDXTRange [ 0]
movzx edx, WORD PTR gDXTRange [16]
add cx, WORD PTR gDXTRange [ 2]
add dx, WORD PTR gDXTRange [18]
add cx, WORD PTR gDXTRange [ 4]
add dx, WORD PTR gDXTRange [20]
movzx ecx, WORD PTR kColorDividerTable[ecx*4]
movzx edx, WORD PTR kColorDividerTable[edx*4]
or ecx, eax
or edx, ebx
mov eax, DWORD PTR width ; width * 1
lea ebx, DWORD PTR [eax + eax*2] ; width * 3
movdqa xmm0, XMMWORD PTR [esi + 0] ; src + width * 0 + 0
movdqa xmm1, XMMWORD PTR [esi + eax*4 + 0] ; src + width * 4 + 0
movdqa xmm7, XMMWORD PTR gDXTMin[ 0]
psubb xmm0, xmm7
psubb xmm1, xmm7
movdqa xmm2, XMMWORD PTR [esi + eax*8 + 0] ; src + 8 * width + 0
psubb xmm2, xmm7
movdqa xmm3, XMMWORD PTR [esi + ebx*4 + 0] ; src + 12 * width + 0
psubb xmm3, xmm7
movdqa xmm6, XMMWORD PTR kSSEIndicesMask0
movdqa xmm7, XMMWORD PTR kSSEWord8
movdqa xmm4, xmm0
movdqa xmm5, xmm1
pand xmm0, xmm6
pand xmm1, xmm6
psrlw xmm4, 8
psrlw xmm5, 8
pmaddwd xmm0, xmm7
pmaddwd xmm1, xmm7
psllw xmm4, 3
psllw xmm5, 3
paddw xmm0, xmm4
paddw xmm1, xmm5
movdqa xmm4, xmm2
movdqa xmm5, xmm3
pand xmm2, xmm6
pand xmm3, xmm6
psrlw xmm4, 8
psrlw xmm5, 8
pmaddwd xmm2, xmm7
pmaddwd xmm3, xmm7
psllw xmm4, 3
psllw xmm5, 3
paddw xmm2, xmm4
paddw xmm3, xmm5
movd xmm7, ecx
pshufd xmm7, xmm7, 0x00
pmulhw xmm0, xmm7
pmulhw xmm1, xmm7
pshuflw xmm0, xmm0, 0xD8
pshufhw xmm0, xmm0, 0xD8
pshuflw xmm1, xmm1, 0xD8
pshufhw xmm1, xmm1, 0xD8
movdqa xmm6, XMMWORD PTR kSSEIndicesScale1
pmaddwd xmm0, xmm6
pmaddwd xmm1, xmm6
packssdw xmm0, xmm1
pshuflw xmm0, xmm0, 0xD8
pshufhw xmm0, xmm0, 0xD8
pmaddwd xmm0, XMMWORD PTR kSSEWord1
movdqa XMMWORD PTR gDXTIndices[ 0 ], xmm0
pmulhw xmm2, xmm7
pmulhw xmm3, xmm7
pshuflw xmm2, xmm2, 0xD8
pshufhw xmm2, xmm2, 0xD8
pshuflw xmm3, xmm3, 0xD8
pshufhw xmm3, xmm3, 0xD8
pmaddwd xmm2, xmm6
pmaddwd xmm3, xmm6
packssdw xmm2, xmm3
pshuflw xmm2, xmm2, 0xD8
pshufhw xmm2, xmm2, 0xD8
pmaddwd xmm2, XMMWORD PTR kSSEWord1
movdqa XMMWORD PTR gDXTIndices[16], xmm2
movdqa xmm0, XMMWORD PTR [esi + 16] // src + width * 0 + 16
movdqa xmm1, XMMWORD PTR [esi + eax*4 + 16] // src + width * 4 + 16
movdqa xmm7, XMMWORD PTR gDXTMin[16]
psubb xmm0, xmm7
psubb xmm1, xmm7
movdqa xmm2, XMMWORD PTR [esi + eax*8 + 16] // src + width * 8 + 16
psubb xmm2, xmm7
movdqa xmm3, XMMWORD PTR [esi + ebx*4 + 16] // src + width * 12 + 16
psubb xmm3, xmm7
movdqa xmm6, XMMWORD PTR kSSEIndicesMask0
movdqa xmm7, XMMWORD PTR kSSEWord8
movdqa xmm4, xmm0
movdqa xmm5, xmm1
pand xmm0, xmm6
pand xmm1, xmm6
pmaddwd xmm0, xmm7
pmaddwd xmm1, xmm7
psrlw xmm4, 8
psrlw xmm5, 8
psllw xmm4, 3
psllw xmm5, 3
paddw xmm0, xmm4
paddw xmm1, xmm5
movdqa xmm4, xmm2
movdqa xmm5, xmm3
pand xmm2, xmm6
pand xmm3, xmm6
pmaddwd xmm2, xmm7
pmaddwd xmm3, xmm7
psrlw xmm4, 8
psrlw xmm5, 8
psllw xmm4, 3
psllw xmm5, 3
paddw xmm2, xmm4
paddw xmm3, xmm5
movd xmm7, edx
pshufd xmm7, xmm7, 0x00
pmulhw xmm0, xmm7
pmulhw xmm1, xmm7
pshuflw xmm0, xmm0, 0xD8
pshufhw xmm0, xmm0, 0xD8
pshuflw xmm1, xmm1, 0xD8
pshufhw xmm1, xmm1, 0xD8
movdqa xmm6, XMMWORD PTR kSSEIndicesScale1
pmaddwd xmm0, xmm6
pmaddwd xmm1, xmm6
packssdw xmm0, xmm1
pshuflw xmm0, xmm0, 0xD8
pshufhw xmm0, xmm0, 0xD8
pmaddwd xmm0, XMMWORD PTR kSSEWord1
movdqa XMMWORD PTR gDXTIndices[32], xmm0
pmulhw xmm2, xmm7
pmulhw xmm3, xmm7
pshuflw xmm2, xmm2, 0xD8
pshufhw xmm2, xmm2, 0xD8
pshuflw xmm3, xmm3, 0xD8
pshufhw xmm3, xmm3, 0xD8
pmaddwd xmm2, xmm6
pmaddwd xmm3, xmm6
packssdw xmm2, xmm3
pshuflw xmm2, xmm2, 0xD8
pshufhw xmm2, xmm2, 0xD8
pmaddwd xmm2, XMMWORD PTR kSSEWord1
movdqa XMMWORD PTR gDXTIndices[48], xmm2
movzx eax, BYTE PTR gDXTIndices[ 0]
movzx ebx, BYTE PTR gDXTIndices[ 8]
mov cl, BYTE PTR kColorIndicesTable[eax*1 + 0]
mov ch, BYTE PTR kColorIndicesTable[ebx*1 + 0]
mov BYTE PTR [edi + 12], cl
mov BYTE PTR [edi + 13], ch
movzx eax, BYTE PTR gDXTIndices[16]
movzx ebx, BYTE PTR gDXTIndices[24]
mov dl, BYTE PTR kColorIndicesTable[eax*1 + 0]
mov dh, BYTE PTR kColorIndicesTable[ebx*1 + 0]
mov BYTE PTR [edi + 14], dl
mov BYTE PTR [edi + 15], dh
movzx eax, BYTE PTR gDXTIndices[32]
movzx ebx, BYTE PTR gDXTIndices[40]
mov cl, BYTE PTR kColorIndicesTable[eax*1 + 0]
mov ch, BYTE PTR kColorIndicesTable[ebx*1 + 0]
mov BYTE PTR [edi + 28], cl
mov BYTE PTR [edi + 29], ch
movzx eax, BYTE PTR gDXTIndices[48]
movzx ebx, BYTE PTR gDXTIndices[56]
mov dl, BYTE PTR kColorIndicesTable[eax*1 + 0]
mov dh, BYTE PTR kColorIndicesTable[ebx*1 + 0]
mov BYTE PTR [edi + 30], dl
mov BYTE PTR [edi + 31], dh
movzx eax, BYTE PTR gDXTIndices[ 4]
movzx ebx, BYTE PTR gDXTIndices[36]
mov cx, WORD PTR kAlphaIndicesTable[eax*2 + 0]
mov dx, WORD PTR kAlphaIndicesTable[ebx*2 + 0]
movzx eax, BYTE PTR gDXTIndices[ 5]
movzx ebx, BYTE PTR gDXTIndices[37]
or cx, WORD PTR kAlphaIndicesTable[eax*2 + 128]
or dx, WORD PTR kAlphaIndicesTable[ebx*2 + 128]
movzx eax, BYTE PTR gDXTIndices[12]
movzx ebx, BYTE PTR gDXTIndices[44]
or cx, WORD PTR kAlphaIndicesTable[eax*2 + 256]
or dx, WORD PTR kAlphaIndicesTable[ebx*2 + 256]
mov WORD PTR [edi + 2], cx
mov WORD PTR [edi + 18], dx
mov cx, WORD PTR kAlphaIndicesTable[eax*2 + 384]
mov dx, WORD PTR kAlphaIndicesTable[ebx*2 + 384]
movzx eax, BYTE PTR gDXTIndices[13]
movzx ebx, BYTE PTR gDXTIndices[45]
or cx, WORD PTR kAlphaIndicesTable[eax*2 + 512]
or dx, WORD PTR kAlphaIndicesTable[ebx*2 + 512]
movzx eax, BYTE PTR gDXTIndices[20]
movzx ebx, BYTE PTR gDXTIndices[52]
or cx, WORD PTR kAlphaIndicesTable[eax*2 + 640]
or dx, WORD PTR kAlphaIndicesTable[ebx*2 + 640]
movzx eax, BYTE PTR gDXTIndices[21]
movzx ebx, BYTE PTR gDXTIndices[53]
or cx, WORD PTR kAlphaIndicesTable[eax*2 + 768]
or dx, WORD PTR kAlphaIndicesTable[ebx*2 + 768]
mov WORD PTR [edi + 4], cx
mov WORD PTR [edi + 20], dx
mov cx, WORD PTR kAlphaIndicesTable[eax*2 + 896]
mov dx, WORD PTR kAlphaIndicesTable[ebx*2 + 896]
movzx eax, BYTE PTR gDXTIndices[28]
movzx ebx, BYTE PTR gDXTIndices[60]
or cx, WORD PTR kAlphaIndicesTable[eax*2 + 1024]
or dx, WORD PTR kAlphaIndicesTable[ebx*2 + 1024]
movzx eax, BYTE PTR gDXTIndices[29]
movzx ebx, BYTE PTR gDXTIndices[61]
or cx, WORD PTR kAlphaIndicesTable[eax*2 + 1152]
or dx, WORD PTR kAlphaIndicesTable[ebx*2 + 1152]
mov WORD PTR [edi + 6], cx
mov WORD PTR [edi + 22], dx
add esi, 32 // src += 32
add edi, 32 // dst += 32
sub DWORD PTR x_count, 8
jnz x_loop
mov eax, DWORD PTR width // width * 1
lea ebx, DWORD PTR [eax + eax*2] // width * 3
lea esi, DWORD PTR [esi + ebx*4] // src += width * 12
sub DWORD PTR y_count, 4
jnz y_loop
}
}
| [
"shawnpresser@gmail.com"
] | shawnpresser@gmail.com |
6f402149560789ca4042cdf028cc5e744cd0c7ad | 512f6474f03964da335a32b7a6834ce1bbf4b651 | /Player.cpp | 0881b6ac9452bd9603911c871b20dd0d9207f7eb | [] | no_license | Eliaslb/Zelda | c797b1537f08ae39ae66f062012cfd1100b915a2 | 1a739871c670f6bf39a55233b11fd78fd49d7fb5 | refs/heads/master | 2021-01-20T11:01:05.316666 | 2017-08-28T16:30:34 | 2017-08-28T16:30:34 | 101,663,985 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,220 | cpp | #include "Player.h"
Player::Player(Arduboy2 &arduboy, Animation2 &PlayerLEFTanim1, Animation2 &PlayerRIGHTanim1, Animation2 &PlayerUPanim1, Animation2 &PlayerDOWNanim1)
{
this->ardu = &arduboy;
this->PlayerLEFTanim = &PlayerLEFTanim1;
this->PlayerRIGHTanim = &PlayerRIGHTanim1;
this->PlayerUPanim = &PlayerUPanim1;
this->PlayerDOWNanim = &PlayerDOWNanim1;
x = 64;
y = 32;
}
void Player::draw(void){
if (Player::GetMovement() == 0) {
if (Player::GetDirection() == 0) {
PlayerLEFTanim->play(Player::GetX(),Player::GetY());
} else if (Player::GetDirection() == 1) {
PlayerUPanim->play(Player::GetX(),Player::GetY());
} else if (Player::GetDirection() == 2) {
PlayerRIGHTanim->play(Player::GetX(),Player::GetY());
} else if (Player::GetDirection() == 3) {
PlayerDOWNanim->play(Player::GetX(),Player::GetY());
}
} else if (Player::GetMovement() == 4) {
if (Player::GetDirection() == 0) {
ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerLEFT1,16,16,BLACK);
} else if (Player::GetDirection() == 1) {
ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerUP1,16,16,BLACK);
} else if (Player::GetDirection() == 2) {
ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerRIGHT1,16,16,BLACK);
} else if (Player::GetDirection() == 3) {
ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerDOWN1,16,16,BLACK);
}
} else if (Player::GetMovement() == 1) {
if (Player::GetDirection() == 0) {
ardu->drawBitmap(Player::GetX() - 13, Player::GetY() + 3, SwordLEFT,16,16,BLACK);
ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerLEFT2,16,16,BLACK);
} else if (Player::GetDirection() == 1) {
ardu->drawBitmap(Player::GetX(), Player::GetY() - 14, SwordUP,16,16,BLACK);
ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerUP2,16,16,BLACK);
} else if (Player::GetDirection() == 2) {
ardu->drawBitmap(Player::GetX() + 12, Player::GetY() + 2, SwordRIGHT,16,16,BLACK);
ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerRIGHT2,16,16,BLACK);
} else if (Player::GetDirection() == 3) {
ardu->drawBitmap(Player::GetX(), Player::GetY() + 14, SwordDOWN,16,16,BLACK);
ardu->drawBitmap(Player::GetX(), Player::GetY(), PlayerDOWN2,16,16,BLACK);
}
}
}
void Player::init(void){
}
int Player::GetX(void){
return x;
}
int Player::GetY(void){
return y;
}
int Player::GetMovement(void){
return movement;
}
int Player::GetDirection(void){
return direction;
}
void Player::moveLeft(void){
//x -= moveSpeed;
direction = 0;
movement = 0;
if (x > 4) {
x -= moveSpeed;
}
}
void Player::moveRight(void){
//x += moveSpeed;
direction = 2;
movement = 0;
if (x < 112) {
x += moveSpeed;
}
}
void Player::moveUp(void){
//y -= moveSpeed;
direction = 1;
movement = 0;
if (y > 10) {
y -= moveSpeed;
}
}
void Player::moveDown(void){
//y += moveSpeed;
direction = 3;
movement = 0;
if (y < 48) {
y += moveSpeed;
}
}
void Player::Idle(void){
movement = 4;
}
void Player::Slash(void){
movement = 1;
}
| [
"eliaslb584@gmail.com"
] | eliaslb584@gmail.com |
bac5520dcbb84a30a8178f39e66441b4668bc6be | 599aa4ba4755d6021d1329ea6495b0d460af7606 | /Platforms/hackerEarth/monthlyEasy/mtd.cpp | f860fbde58d4643896acea5d17afccf07ca079a4 | [] | no_license | manosriram/Algorithms | 96109c86bb38a0bad43f6d6c465b224051145123 | 894a37d420aa65fab1e45bcef8d9f1ef262f4aaa | refs/heads/master | 2022-12-21T21:32:53.005160 | 2020-09-24T15:50:58 | 2020-09-24T15:50:58 | 159,975,079 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cpp | #include <iostream>
using namespace std;
void removeE(int g, int arr[],int n) {
for (int t=n;t>=0;t--) {
if (arr[t] == g) {
for (int h=t;h<n-t;h++) {
arr[h] = arr[h+1];
}
}
}
}
int main() {
int n,a,b,arr[10000];
int i,j,t;
int count=1;
int sum1=0;
cin >> n >> a >> b;
for (t=0;t<n;t++)
cin >> arr[t];
for (i=0;i<n;i++) {
for (j=i+1;j<n-i;j++) {
if (arr[i] == arr[j])
count++;
if (count >=3)
break;
}
if (count == 3) {
sum1 += a+b;
count=1;
int g = arr[i];
removeE(g,arr,n);
}
if (count==2) {
sum1 += b;
count=1;
}
}
cout << sum1;
} | [
"mano.sriram0@gmail.com"
] | mano.sriram0@gmail.com |
1f7b72cab0a0bb8e47da77df247bdc6b6b59a3fa | abdb28b3a907236ee75cdd8a8a49c4a8280c3c33 | /FinalProject/StockAccount.cpp | 239278fe72bd6dabc02f8dd53cc582bfa514b14f | [] | no_license | Aaron723/503Assignments-new- | 81d92db8dacf289d25ce7e8ee904e502a07cf8ae | 1788626c0d8d49d8e6ee47ed78f33f5f213081d1 | refs/heads/master | 2020-04-01T01:54:29.191928 | 2018-12-17T22:41:48 | 2018-12-17T22:41:48 | 152,757,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,034 | cpp | //
// Created by Zi Wan on 12/9/18.
//
#include "StockAccount.h"
void StockAccount::setCASH_BALANCE(double stockBalance) {
CASH_BALANCE=stockBalance;
}
StockAccount::StockAccount(){
readPortfolio();//every time construct stock account, we need portfolio information
}
StockAccount::~StockAccount() {}
void StockAccount::buyStock(string stockName, int shares, double amount) {
if(shares<0)
{
cout<<"Error: The shares number you want to buy can't be negative"<<endl;
return;
}
else if(shares==0)
{
cout<<"Error: You didn't buy anything"<<endl;
return;
}
iofile iofile1;
char*fileName=iofile1.selectFile();
if(iofile1.SearchName(fileName,stockName)!="")
{
double price=atof((iofile1.SearchName(fileName,stockName)).c_str());
timeCall timeCall1;
string time;
string date;
if(price*shares<=CASH_BALANCE&&amount>=price)
{
CASH_BALANCE-=price*shares;
iofile iofile2;
char *a=CASHBALANCE;
iofile2.writeTofile(a,CASH_BALANCE);
if(stockList->changeStockShares(stockName,shares,price, true))//true means buy, false means sell
{
iofile iofile3;
iofile3.writeToPortfolio(stockList);//every time buy stock, write it in portfolio, bankhistory and transaction history
time=timeCall1.getTime();
date=timeCall1.getDate();
iofile1.writeToBankHistory(date,CASH_BALANCE,price*shares,3);
iofile1.writeToTransactionHistory(stockName,time,price,shares,true);
//should I sort with random value red from results? Or just use the old value?
}
else
{
Node *newNode=new Node(stockName,price,shares);//add new stock to the end if this stock is not in the portfolio
stockList->addToEnd(newNode);
iofile iofile3;
iofile3.writeToPortfolio(stockList);
time=timeCall1.getTime();
date=timeCall1.getDate();
iofile1.writeToBankHistory(date,CASH_BALANCE,price*shares,3);
iofile1.writeToTransactionHistory(stockName,time,price,shares,true);
}
//true means buy, false means sell
}
else if(price*shares>CASH_BALANCE)
{
cout<<"Your cash balance is not enough! Fail to buy!"<<endl;
}
else if(price>amount)
{
cout<<"The current price is more expensive than you want!Fail to buy!"<<endl;
}
}
else
{
cout<<"This stock is not in the results!"<<endl;
}
}
void StockAccount::sellStock(string stockName, int shares, double amount) {// similar to what we do in buy, but remove stock if share==0
if(shares<0)
{
cout<<"Error: The shares number you want to sell can't be negative"<<endl;
return;
}
else if(shares==0)
{
cout<<"You didn't sell anything"<<endl;
return;
}
iofile iofile1;
char*fileName=iofile1.selectFile();
if(iofile1.SearchName(fileName,stockName)!="")
{
double price=atof((iofile1.SearchName(fileName,stockName)).c_str());
if(price<amount)
cout<<"current price is lower than your expect price! Fail to sell!"<<endl;
else if(stockList->changeStockShares(stockName,shares,price,false))
{
char *a=CASHBALANCE;
CASH_BALANCE+=shares*price;
iofile1.writeTofile(a,CASH_BALANCE);
cout<<"Sucessfully sell the stock!"<<endl;
timeCall timeCall1;
string time=timeCall1.getTime();
string date=timeCall1.getDate();
iofile1.writeToBankHistory(date,CASH_BALANCE,price*shares,4);
iofile1.writeToTransactionHistory(stockName,time,price,shares,false);
iofile iofile2;
iofile2.writeToPortfolio(stockList);
}
}
else
{
cout<<"This stock is not in the results! Fail to sell!"<<endl;
}
}
//read stock from stocklist, update each stock's price and sort stock list, then print portfolio.
void StockAccount::printPortfolio() {
iofile iofile1;
double sum=0;
if(stockList->getMySize()!=0)
{
Node* currentNode=stockList->getMyHead();
while (currentNode!=stockList->getMyTail())
{
string name=currentNode->getStockName();
if(name=="")
break;
double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str());
currentNode->setStockPrice(price);
sum+=price*currentNode->getShares();
currentNode=currentNode->getNext();
}
if(currentNode==stockList->getMyTail())
{
string name=currentNode->getStockName();
double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str());
currentNode->setStockPrice(price);
sum+=price*currentNode->getShares();
}
Sorter sorter;
cout<<"Please choose if you want to print in decent order or ascend order(1 means decent, 2 means asecnd)\n";
int i;
cin>>i;
if(i<1||i>2)
{
cout<<"Wrong sort choice, please enter again"<<endl;
cin>>i;
}
else if(i==2)
sorter.Sort(stockList,make_shared<ascendSortStrategy>());
else if(i==1)
sorter.Sort(stockList,make_shared<decentSortStrategy>());
string cashbal=iofile1.readCashBalance();
cout<<setiosflags(ios::fixed)<<setprecision(2);
cout << "Cash Balance = $" << cashbal << endl;
cout << std::left << setw(20) << "Company Symbol" << std::left << setw(10)
<< "Number" << std::left << setw(10) << "Price" << std::left << setw(15) << "Total value" << "\n";
stockList->printList();
cout<<"Total portfolio = $"<<CASH_BALANCE+sum<<endl;
} else
{
cout<<"There is no stock in the portfolio"<<endl;
cout<<setiosflags(ios::fixed)<<setprecision(2);
string cashbal=iofile1.readCashBalance();
cout << "Cash Balance = $" << cashbal << endl;
cout<<"Total portfolio = $"<<CASH_BALANCE+sum<<endl;
}
}
void StockAccount::printTransactionHistory() {
char line[100];
ifstream file;
char*a=TRANACTIONHISTORY;
file.open(a);
if(file.is_open())
{
while (!file.eof()) {
file.getline(line, 100);
string str=line;
cout << str << endl;
}
file.close();
}
else
{
file.close();
// cout<<"Error: fail to open transactionHistory.txt"<<endl;
}
}
void StockAccount::readPortfolio() {
char*a=PORTFOLIO;
ifstream file(a);
if(!file.is_open())
{
// cout<<"There is no stock in your portfolio."<<endl;
}
else
{
double totalValue=0;
while(!file.eof())
{
char line[100];
file.getline(line,100);
string str=line;
stringstream ss(str);
string name;
getline(ss,name,'\t');
string shares;
getline(ss,shares,'\t');
if(name=="")
return;
iofile iofile1;
double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str());
int int_shares=atoi(shares.c_str());
Node* newNode=new Node(name,price,int_shares);
stockList->addToEnd(newNode);
totalValue+=price*int_shares;
}
totalPortfolio=totalValue+CASH_BALANCE;
Sorter sorter;
sorter.Sort(stockList,make_shared<decentSortStrategy>());
}
}
void StockAccount::updatePortfolio() {
iofile iofile1;
double sum=0;
if(stockList->getMySize()!=0)
{
Node* currentNode=stockList->getMyHead();
while (currentNode!=stockList->getMyTail())
{
string name=currentNode->getStockName();
if(name=="")
break;
double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str());
currentNode->setStockPrice(price);
sum+=price*currentNode->getShares();
currentNode=currentNode->getNext();
}
if(currentNode==stockList->getMyTail())
{
string name=currentNode->getStockName();
double price=atof((iofile1.SearchName(iofile1.selectFile(),name)).c_str());
currentNode->setStockPrice(price);
sum+=price*currentNode->getShares();
}
}
sum+=CASH_BALANCE;
timeCall timeCall1;
string time=timeCall1.getTime();
string date=timeCall1.getDate();
iofile1.writeTototalValue(sum,time,date);
}
| [
"w745207699@gmail.com"
] | w745207699@gmail.com |
67df2629c6da09829d66ee120c50e9c896a84471 | 0f3d13bd7d68efbed8c7db1abcac57f8bd797458 | /HEPfit/examples-src/LibMode_header/libmode_header.cpp | 7a7dcee4c80eac0d32f702ec089e7dbbbdcaa00a | [
"DOC"
] | permissive | talismanbrandi/Belle_1809.03290 | 5b48b1fee290b12159326e04f72640898663540c | b6608353f9c685a95f9a9d2fe2677c3d128baf8a | refs/heads/master | 2020-05-27T05:06:30.404976 | 2019-05-28T17:02:13 | 2019-05-28T17:02:13 | 188,494,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,137 | cpp | /*
* Copyright (C) 2014 HEPfit Collaboration
*
*
* For the licensing terms see doc/COPYING.
*/
/**
* @example libmode_header.cpp
* This is an example of how to compute observables from the input parameters
* defined in the file InputParameters.h.
*
*/
#include <iostream>
#include <HEPfit.h>
#include <InputParameters.h>
int main(int argc, char** argv)
{
try {
/* Define the name of the model to be used. */
std::string ModelName = "NPEpsilons";
/* Create an object of the class InputParameters. */
InputParameters IP;
/* Read a map for the mandatory model parameters. (Default values in InputParameters.h) */
std::map<std::string, double> DPars_IN = IP.getInputParameters(ModelName);
/* Change the default values of the mandatory model parameters if necessary. */
/* This can also be done with DPars after creating an object of ComputeObservables. */
DPars_IN["mcharm"] = 1.3;
DPars_IN["mub"] = 4.2;
/* Create objects of the classes ModelFactory and ThObsFactory */
ModelFactory ModelF;
ThObsFactory ThObsF;
/* Set the flags for the model being used, if necessary. */
std::map<std::string, std::string> DFlags;
DFlags["epsilon2SM"] = "TRUE";
DFlags["epsilonbSM"] = "TRUE";
/* Create an object of the class ComputeObservables. */
ComputeObservables CO(ModelF, ThObsF, ModelName, DPars_IN, DFlags);
/* Add the observables to be returned. */
CO.AddObservable("Mw");
CO.AddObservable("GammaZ");
CO.AddObservable("AFBbottom");
/* Remove a previously added observables if necessary. */
//CO.RemoveObservable("AFBbottom");
/* Get the map of observables if necessary. */
std::map<std::string, double> DObs = CO.getObservables();
/* Define a map for the parameters to be varied. */
std::map<std::string, double> DPars;
for (int i = 0; i < 2; i++) {
/* Vary the parameters that need to be varied in the analysis. */
DPars["epsilon_1"] = 0. + i * 0.01;
DPars["epsilon_3"] = 0. + i * 0.01;
/* Get the map of observables with the parameter values defined above. */
DObs = CO.compute(DPars);
std::cout << "\nParameters[" << i + 1 << "]:"<< std::endl;
for (std::map<std::string, double>::iterator it = DPars.begin(); it != DPars.end(); it++) {
std::cout << it->first << " = " << it->second << std::endl;
}
std::cout << "\nObservables[" << i + 1 << "]:" << std::endl;
for (std::map<std::string, double>::iterator it = DObs.begin(); it != DObs.end(); it++) {
std::cout << it->first << " = " << it->second << std::endl;
}
}
return EXIT_SUCCESS;
} catch (const std::runtime_error& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
}
| [
"apaul2@alumni.nd.edu"
] | apaul2@alumni.nd.edu |
7883b573bdc66f6999ae56ae24991fc9f42610e2 | b8be015984622307394dc919ab711417da4fa911 | /Length of Last Word.h | cd54d6144712901fa709405f2a7c4159a8594ed3 | [] | no_license | boyxgc/Leetcode | de41651416e5aec30666f67653ab7736e0edc2aa | bd09a470628f7112198b70d52d63b30409cac12f | refs/heads/master | 2021-01-22T06:37:00.824562 | 2014-12-05T03:16:11 | 2014-12-05T03:16:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | class Solution {
public:
int lengthOfLastWord(const char *s) {
int size = 0;
const char *s1 = s;
while(*(s1++)) {
size++;
}
int lastword = size-1;
while(lastword >= 0 && s[lastword] == ' ')
lastword--;
int lastwordsize = 0;
while(lastword >= 0 && s[lastword] != ' '){
lastwordsize++;
lastword--;
}
return lastwordsize;
}
}; | [
"boyxgc@gmail.com"
] | boyxgc@gmail.com |
7d24c20c45672137603f10ae304b6d51202d5e12 | 25f8cc14652d2d4a799fb4e946d79b2672d24662 | /TestCases/main.cpp | 0441bab5def7c96415d4610406c42e802cfe7941 | [] | no_license | da-x-ace/openSSL-compatible-RSA-Engine | 2c313fb693d23c4bab44cf399c0c0c62ab30d70d | 899676109e699b996ed65fa73ef51ab94084f2c1 | refs/heads/master | 2016-08-03T14:43:15.560671 | 2013-01-31T02:44:14 | 2013-01-31T02:44:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 70,661 | cpp | #include <iostream>
#include <stdio.h>
#include <gmp.h>
#include <string.h>
#include <vector>
#include <fstream>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <openssl/evp.h>
#include <sys/syscall.h>
#include <openssl/sha.h>
#define MODULUSSIZE 1024 //No. of bits in n
#define SIZE (MODULUSSIZE/8) //No of bytes in n
#define PRIMEBITS (MODULUSSIZE/2)
#define BUFSIZE (MODULUSSIZE/8)/2
#define MSGSIZE SIZE-11 //MSG Length to be eligible for encrypting
#define BLOCKSIZE (MODULUSSIZE/8)/2
#define OCTET 8
#define MD5SUM_BYTES 16
#define SIGNSIZE SIZE
#define ENCRYPT 0
#define DEBUG 0
using namespace std;
unsigned char* gen_md5_digest(char *);
typedef unsigned char uint8_t ;
struct publicKey{
mpz_t n;
mpz_t e;
};
struct privateKey{
//char* header;
//char* algorithm;
mpz_t n;
mpz_t e;
mpz_t d;
mpz_t p;
mpz_t q;
mpz_t exp1;
mpz_t exp2;
mpz_t u;
};
static const string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
int hexToInt(string strHex)
{
int decimalValue = 0;
sscanf(strHex.c_str(), "%x", &decimalValue);
// cout<<decimalValue<<endl;
return decimalValue;
}
struct privateKey* getPrivateStructure(mpz_t n, mpz_t e, mpz_t d,mpz_t p,mpz_t q,mpz_t exp1,mpz_t exp2, mpz_t u)
{
struct privateKey* priKey = (struct privateKey*)malloc(sizeof(struct privateKey));
mpz_init(priKey->n);
mpz_set(priKey->n, n);
mpz_init(priKey->e);
mpz_set(priKey->e, e);
mpz_init(priKey->d);
mpz_set(priKey->d, d);
mpz_init(priKey->p);
mpz_set(priKey->p, p);
mpz_init(priKey->q);
mpz_set(priKey->q, q);
mpz_init(priKey->exp1);
mpz_set(priKey->exp1, exp1);
mpz_init(priKey->exp2);
mpz_set(priKey->exp2, exp2);
mpz_init(priKey->u);
mpz_set(priKey->u, u);
}
void freePrivateStructure(struct privateKey* priKey)
{
mpz_clear(priKey->p);
mpz_clear(priKey->q);
mpz_clear(priKey->n);
mpz_clear(priKey->e);
mpz_clear(priKey->d);
mpz_clear(priKey->exp1);
mpz_clear(priKey->exp2);
mpz_clear(priKey->u);
free(priKey);
}
vector<string> myTokenizer(char* input)
{
vector<string> myList;
int count = 2;
int index = 0;
int indexTemp = 0;
char temp[2];
for(int i=0; i<strlen(input); i++)
{
if(index < 2)
{
temp[indexTemp++] = input[i];
index++;
}
if(index==2)
{
myList.push_back(temp);
index=0;
indexTemp=0;
}
}
return myList;
}
/* Computes the multiplicative inverse of a number using Euclids algorithm.
Computes x such that a * x mod n = 1, where 0 < a < n. */
static void mpz_mod_inverse(MP_INT *x, MP_INT *a, MP_INT *n)
{
MP_INT g0, g1, v0, v1, div, mod, aux;
mpz_init_set(&g0, n);
mpz_init_set(&g1, a);
mpz_init_set_ui(&v0, 0);
mpz_init_set_ui(&v1, 1);
mpz_init(&div);
mpz_init(&mod);
mpz_init(&aux);
while (mpz_cmp_ui(&g1, 0) != 0)
{
mpz_divmod(&div, &mod, &g0, &g1);
mpz_mul(&aux, &div, &v1);
mpz_sub(&aux, &v0, &aux);
mpz_set(&v0, &v1);
mpz_set(&v1, &aux);
mpz_set(&g0, &g1);
mpz_set(&g1, &mod);
}
if (mpz_cmp_ui(&v0, 0) < 0)
mpz_add(x, &v0, n);
else
mpz_set(x, &v0);
mpz_clear(&g0);
mpz_clear(&g1);
mpz_clear(&v0);
mpz_clear(&v1);
mpz_clear(&div);
mpz_clear(&mod);
mpz_clear(&aux);
}
//Base64 Encoder
string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
char* base64Decoder(char *input)
{
int length = strlen(input);
int outputLength;
int countPad =0;
unsigned char char_array_4[4], char_array_3[3];
for(int k=length-1; k> 0 ; k--)
if(input[k]=='=')
countPad++;
else
break;
// printf("Pad length = %d\n", countPad);
if(countPad == 0)
outputLength = (length*3)/4;
else if(countPad == 1)
outputLength = ((length-4)*3)/4+ 2;
else if(countPad == 2)
outputLength = ((length-4)*3)/4+ 1;
int finalLength = 4*outputLength;
char* output = new char[finalLength];
memset(output, 0, finalLength);
char temp[2];
int index=0, k=0, start=0;
while (k<length && ( input[k] != '=') && is_base64(input[k]))
{
char_array_4[index++] = input[k++];
if(index == 4)
{
//printf("The segment is : %s \n", char_array_4);
index=0;
//printf("The segment is : %c \n", char_array_4[3]);
for (int j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
//printf("The segment is : %d \n", char_array_4[3]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
sprintf(temp,"%02x", char_array_3[0]);
strcat(output,temp);
strcat(output," ");
sprintf(temp,"%02x", char_array_3[1]);
strcat(output,temp);
strcat(output," ");
sprintf(temp,"%02x", char_array_3[2]);
strcat(output,temp);
strcat(output," ");
//printf("The value is : %02x \n", char_array_3[0]);
//printf("The value is : %02x \n", char_array_3[1]);
//printf("The value is : %02x \n", char_array_3[2]);
//printf("Output : %s\n", output);
}
}
if(index)
{
//printf("The segment is : %s \n", char_array_4);
for (start = index; start <4; start++)
char_array_4[start] = 0;
//printf("The segment is : %c \n", char_array_4[2]);
//printf("The segment is : %c \n", char_array_4[3]);
//printf("The segment is : %s \n", char_array_4);
for (start = 0; start <4; start++)
char_array_4[start] = base64_chars.find(char_array_4[start]);
// printf("The segment is : %d \n", char_array_4[3]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
sprintf(temp,"%02x", char_array_3[0]);
strcat(output,temp);
strcat(output," ");
sprintf(temp,"%02x", char_array_3[1]);
strcat(output,temp);
//strcat(output,"\n");
//sprintf(temp,"%x", char_array_3[2]);
//strcat(output,temp);
//printf("The value is : %c \n", char_array_3[0]);
//printf("The value is : %c \n", char_array_3[1]);
//printf("The value is : %c \n", char_array_3[2]);
// printf("Output : \n%s\n", output);
}
#if DEBUG
printf("Output : \n%s\n", output);
#endif
return output;
}
int TLVHeaderDecoder(vector<string> myList, int start,int size, string& TLVLength)
{
int type = hexToInt(myList[start]);
int length= hexToInt(myList[start+1]);
#if DEBUG
printf("Hiii = %d\n",hexToInt(myList[start+1]));
#endif
int blocksLength = 0;
int index;
if(length > 128)
{
blocksLength = length - 128;
index = start+2;
for(int i=0; i< blocksLength; i++)
TLVLength = TLVLength + myList[index++];
#if DEBUG
printf("Length = %s\n", TLVLength.c_str());
printf("Index = %d\n", index);
#endif
return index;
}
else
{
TLVLength = myList[start+1];
index = start+2;
//printf("Index = %d\n", index);
return index;
}
}
int TLVDecoder(vector<string> myList, int start, int size, string& TLVLength, string& TLVValue)
{
int type = hexToInt(myList[start]);
int length= hexToInt(myList[start+1]);
int blocksLength = 0;
int index;
if(length > 128)
{
blocksLength = length - 128;
index = start+2;
for(int i=0; i< blocksLength; i++)
TLVLength = TLVLength + myList[index++];
// printf("Length = %d\n", hexToInt(TLVLength));
// printf("Index = %d\n", index);
for(int i=0; i<hexToInt(TLVLength); i++)
{
TLVValue = TLVValue+myList[index++];
}
//cout<<TLVValue<<endl;
return index;
}
else
{
TLVLength = myList[start+1];
index = start+2;
#if DEBUG
printf("Index TLV LEngth = %s\n", TLVLength.c_str());
#endif
for(int i=0; i<hexToInt(TLVLength); i++)
{
TLVValue = TLVValue+myList[index++];
}
// cout<<TLVValue<<endl;
return index;
}
}
struct publicKey* decodePublicKey(char* input)
{
vector<string> myList;
char* parts;
parts = strtok(input," ");
while(parts)
{
//printf("%s\n",parts);
myList.push_back(parts);
parts = strtok(NULL," ");
}
#if DEBUG
printf("Size of the vector: %d\n", myList.size());
#endif
int value=0;
string myTypeValue[2], mytempTypeValue;
string myTypeLength[2], mytempTypeLength;
string headerLength;
string tempheaderLength;
value = TLVHeaderDecoder(myList, value, 2, tempheaderLength);
#if DEBUG
printf("Index = %d\n", value);
#endif
value = TLVDecoder(myList, value, 2, mytempTypeLength, mytempTypeValue);
// printf("Check best Index = %d\n", value);
value = TLVHeaderDecoder(myList, value, 2, tempheaderLength);
#if DEBUG
printf("Index = %d\n", value);
#endif
value++;
#if DEBUG
printf("This Index = %d\n", value);
#endif
value = TLVHeaderDecoder(myList, value, 2, tempheaderLength);
#if DEBUG
printf("Index = %d\n", value);
#endif
for(int i=0; i<2; i++)
{
value = TLVDecoder(myList, value, 2, myTypeLength[i], myTypeValue[i]);
#if DEBUG
printf("you Index = %d\n", value);
#endif
}
struct publicKey* pubKey = (struct publicKey*)malloc(sizeof(struct publicKey));
mpz_init(pubKey->n);
mpz_init_set_str(pubKey->n, myTypeValue[0].c_str(), 16);
mpz_init(pubKey->e);
mpz_init_set_str(pubKey->e, myTypeValue[1].c_str(), 16);
#if DEBUG
gmp_printf("\n%Zd\n", pubKey->n);
gmp_printf("\n%Zd\n", pubKey->e);
#endif
//if(mpz_cmp)
//*n = pubKey->n;
//*e = pubKey->e;
//mpz_clear(pubKey->n);
//mpz_clear(pubKey->e);
return pubKey;
}
struct privateKey* decodePrivateKey(char* input)
{
char* parts;
//Aim to fill the vector with 1 byte of hexdata
vector<string> myList;
parts = strtok(input," ");
while(parts)
{
//printf("%s\n",parts);
myList.push_back(parts);
parts = strtok(NULL," ");
}
#if DEBUG
printf("Size of the vector: %d\n", myList.size());
#endif
int value;
string myTypeValue[9];
string myTypeLength[9];
string headerLength;
value = TLVHeaderDecoder(myList, 0, 2, headerLength);
#if DEBUG
printf("Index = %d\n", value);
#endif
for(int i=0; i<9; i++)
{
value = TLVDecoder(myList, value, 2, myTypeLength[i], myTypeValue[i]);
#if DEBUG
printf("Index = %d\n", value);
#endif
}
struct privateKey* priKey = (struct privateKey*)malloc(sizeof(struct privateKey));
mpz_init(priKey->n);
mpz_init_set_str(priKey->n, myTypeValue[1].c_str(), 16);
mpz_init(priKey->e);
mpz_init_set_str(priKey->e, myTypeValue[2].c_str(), 16);
mpz_init(priKey->d);
mpz_init_set_str(priKey->d, myTypeValue[3].c_str(), 16);
mpz_init(priKey->p);
mpz_init_set_str(priKey->p, myTypeValue[4].c_str(), 16);
mpz_init(priKey->q);
mpz_init_set_str(priKey->q, myTypeValue[5].c_str(), 16);
mpz_init(priKey->exp1);
mpz_init_set_str(priKey->exp1, myTypeValue[6].c_str(), 16);
mpz_init(priKey->exp2);
mpz_init_set_str(priKey->exp2, myTypeValue[7].c_str(), 16);
mpz_init(priKey->u);
mpz_init_set_str(priKey->u, myTypeValue[8].c_str(), 16);
//mpz_t n; mpz_init(n); mpz_init_set_str(n, myTypeValue[1].c_str(), 16);
mpz_t p; mpz_init(p); mpz_init_set_str(p, myTypeValue[4].c_str(), 16);
mpz_t q; mpz_init(q); mpz_init_set_str(q, myTypeValue[5].c_str(), 16);
mpz_t temp; mpz_init(temp);
mpz_mul(temp, p, q);
//gmp_printf("\n%Zd\n", priKey->n);
//gmp_printf("\n%Zd\n", temp);
mpz_clear(p);
mpz_clear(q);
return priKey;
/*
mpz_clear(priKey->p);
mpz_clear(priKey->q);
mpz_clear(priKey->n);
mpz_clear(priKey->e);
mpz_clear(priKey->d);
mpz_clear(priKey->exp1);
mpz_clear(priKey->exp2);
mpz_clear(priKey->u);
mpz_clear(temp);
*/
}
//Certificate related stuff
struct tlv{
string t;
string l;
string v;
};
struct seq2{
string t;
string l;
struct tlv first;
struct tlv second;
};
struct set{
string t;
string l;
struct seq2 sequence;
};
struct sequence_7{
string t;
string l;
struct set setArray[7];
};
struct keyInfoSeq{
string t;
string l;
struct seq2 sequence;
struct set keyInfo;
};
struct sequence1{
string t;
string l;
struct tlv myInt;
struct seq2 s_1;
struct sequence_7 s_2;
struct seq2 s_3;
struct sequence_7 s_4;
struct keyInfoSeq s_5;
};
struct certificate{
string t;
string l;
struct sequence1 s1;
struct seq2 s2;
struct tlv s3;
};
int TLVHeaderDecoderNew(vector<string> myList, int start,int size, string& TLVTag, string& TLVLength)
{
int type = hexToInt(myList[start]);
TLVTag = myList[start];
int length= hexToInt(myList[start+1]);
int blocksLength = 0;
int index;
if(length > 128)
{
blocksLength = length - 128;
index = start+2;
for(int i=0; i< blocksLength; i++)
TLVLength = TLVLength + myList[index++];
//printf("Length = %d\n", hexToInt(TLVLength));
//printf("Index = %d\n", index);
return index;
}
else
{
TLVLength = myList[start+1];
index = start+2;
//printf("Index = %d\n", index);
return index;
}
}
int TLVDecoderNew(vector<string> myList, int start, int size,string& TLVTag, string& TLVLength, string& TLVValue)
{
int type = hexToInt(myList[start]);
TLVTag = myList[start];
int length= hexToInt(myList[start+1]);
int blocksLength = 0;
int index;
if(length > 128)
{
blocksLength = length - 128;
index = start+2;
for(int i=0; i< blocksLength; i++)
TLVLength = TLVLength + myList[index++];
// printf("Length = %d\n", hexToInt(TLVLength));
// printf("Index = %d\n", index);
for(int i=0; i<hexToInt(TLVLength); i++)
{
TLVValue = TLVValue+myList[index++];
}
//cout<<TLVValue<<endl;
return index;
}
else
{
TLVLength = myList[start+1];
index = start+2;
//printf("Index = %d\n", index);
for(int i=0; i<hexToInt(TLVLength); i++)
{
TLVValue = TLVValue+myList[index++];
}
// cout<<TLVValue<<endl;
return index;
}
}
struct seq2 sequenceWith2(vector<string> myList, int start, int& index)
{
int type;
int length;
//int index;
string myTypeTag[2];
string myTypeValue[2];
string myTypeLength[2];
string headerLength;
string headerType;
struct seq2 mySeq;
struct tlv myTLV[2];
index = TLVHeaderDecoderNew(myList, start, 2, headerType, headerLength);
//printf("Index = %d\n", index);
mySeq.t = headerType;
mySeq.l = headerLength;
//printf("Type:%s ", mySeq.t.c_str());
//printf("Length:%s\n", mySeq.l.c_str());
for(int i=0; i<2; i++)
{
//myTLV[i] = (struct tlv*) malloc(sizeof(struct tlv));
index = TLVDecoderNew(myList, index, 2, myTypeTag[i], myTypeLength[i], myTypeValue[i]);
myTLV[i].t = myTypeTag[i];
myTLV[i].l = myTypeLength[i];
myTLV[i].v = myTypeValue[i];
if(i==0)
mySeq.first = myTLV[i];
else
mySeq.second = myTLV[i];
//free(myTLV);
// printf("Index = %d\n", index);
}
//printf("Value 1:\n%s\n", (mySeq.first.v).c_str());
//printf("Value 2:\n%s\n", (mySeq.second.v).c_str());
//inputSeq = mySeq;
//free(mySeq);
return mySeq;
}
struct set makeSet(vector<string> myList, int start, int& value)
{
struct set mySet;
struct seq2 mySeq;
string headerLength;
string headerType;
start = TLVHeaderDecoderNew(myList, start, 2, headerType, headerLength);
#if DEBUG
printf("Index = %d\n", start);
#endif
mySet.t = headerType;
mySet.l = headerLength;
if(hexToInt(headerType) == 3)
start++;
mySeq = sequenceWith2(myList, start, value);
mySet.sequence = mySeq;
//printf("Value 1:\n%s\n", (mySet.sequence.first.v).c_str());
//printf("Value 2:\n%s\n", (mySet.sequence.second.v).c_str());
//printf("Index = %d\n", value);
//return value;
return mySet;
}
int decodeLargeSequence(vector<string> myList, int start, struct sequence_7& bigSeq)
{
//struct sequence_7 bigSeq;
string headerLength;
string headerType;
struct set mySet[8];
start = TLVHeaderDecoderNew(myList, start, 2, headerType, headerLength);
bigSeq.t = headerType;
bigSeq.l = headerLength;
//printf("Value 1:\n%s\n", bigSeq.t.c_str());
//printf("Value 2:\n%s\n", bigSeq.l.c_str());
int lengthSub = hexToInt(headerLength);
//printf("Length of subsequence: %d\n", lengthSub);
int offset = lengthSub+start;
//printf("Index before offset= %d\n", start);
int value = start;
for(int i=0; i<8, value<offset; i++)
{
mySet[i] = makeSet(myList, value, start);
bigSeq.setArray[i] = mySet[i];
value = start;
//printf("Length at bigSeq for i= %d is %d\n", i, value);
}
//printf("Some random check : %s \n", bigSeq.setArray[3].sequence.first.v.c_str());
#if DEBUG
printf("Index = %d\n", start);
#endif
return start;
}
int decodeAlgo(vector<string> myList, int start, struct seq2& seqAlgo)
{
int index=0;
seqAlgo= sequenceWith2(myList,start,index);
#if DEBUG
printf("Algo type = %s\n", seqAlgo.first.v.c_str());
#endif
return index;
}
int decodeTimeValidity(vector<string> myList, int start, struct seq2& timeValidity)
{
int index=0;
timeValidity= sequenceWith2(myList,start,index);
//printf("Time type = %s\n", timeValidity.first.t.c_str());
return index;
}
int decodeKeySequence(vector<string> myList, int start, struct keyInfoSeq& keyInformation)
{
string headerLength;
string headerType;
struct seq2 myObj;
struct set keyInfoString;
start = TLVHeaderDecoderNew(myList, start, 2, headerType, headerLength);
keyInformation.t = headerType;
keyInformation.l = headerLength;
#if DEBUG
printf("Index in decode key sequence = %d\n", start);
#endif
int index = start;
myObj = sequenceWith2(myList,start,index);
start = index;
#if DEBUG
printf("Index in decode key sequence = %d\n", start);
#endif
keyInfoString = makeSet(myList,start,index);
keyInformation.sequence=myObj;
keyInformation.keyInfo = keyInfoString;
#if DEBUG
printf("Check for key : %s\n", keyInformation.keyInfo.sequence.second.v.c_str());
printf("Index in decode key sequence = %d\n", index);
#endif
return index;
}
int sequence1Decoder(vector<string> myList, int value, struct sequence1& s1)
{
string myTypeTag[2];
string myTypeLength[2];
string myTypeValue[2];
value = TLVHeaderDecoderNew(myList, value, 2, myTypeTag[0], myTypeLength[0]);
#if DEBUG
printf("Index = %d\n", value);
#endif
s1.t = myTypeTag[0];
s1.l = myTypeLength[0];
value = TLVDecoderNew(myList, value, 2, myTypeTag[1], myTypeLength[1], myTypeValue[1]);
#if DEBUG
printf("Index = %d\n", value);
#endif
struct tlv myInteger;
myInteger.t= myTypeTag[1];
myInteger.l = myTypeLength[1];
myInteger.v = myTypeValue[1];
s1.myInt = myInteger;
#if DEBUG
printf("Check Integer value= %s\n", s1.myInt.v.c_str());
printf("length = %s\n", myTypeValue[1].c_str());
#endif
//Validity Set sequence
struct seq2 seqAlgo;
value = decodeAlgo(myList, value, seqAlgo);
#if DEBUG
printf("Index = %d\n", value);
#endif
s1.s_1 = seqAlgo;
#if DEBUG
printf("Check Algo Value= %s\n", s1.s_1.first.v.c_str());
#endif
//After NULL
//First 7 element set
struct sequence_7 bigSeq1;
value = decodeLargeSequence(myList, value, bigSeq1);
#if DEBUG
printf("Index = %d\n", value);
#endif
s1.s_2 = bigSeq1;
#if DEBUG
printf("Check sequence 7 first value= %s\n", s1.s_2.setArray[0].sequence.first.v.c_str());
#endif
//printf("IMP check sequence 7 first value= %s\n", s1.s_2.setArray[7].sequence.first.v.c_str());
//printf("Some random check : %s \n", bigSeq1.setArray[3].sequence.first.v.c_str());
//Validity Set sequence
struct seq2 seqValidity;
value = decodeTimeValidity(myList, value, seqValidity);
//printf("Index = %d\n", value);
s1.s_3 = seqValidity;
//printf("Check time validity= %s\n", s1.s_3.first.v.c_str());
//Second 7 element set
struct sequence_7 bigSeq2;
value = decodeLargeSequence(myList, value, bigSeq2);
//printf("Index = %d\n", value);
s1.s_4 = bigSeq2;
#if DEBUG
printf("Check sequence 7 second= %s\n", s1.s_4.setArray[0].sequence.first.v.c_str());
#endif
//Decode double sequence
struct keyInfoSeq keyInformation;
value = decodeKeySequence(myList, value, keyInformation);
#if DEBUG
printf("Index = %d\n", value);
#endif
s1.s_5 = keyInformation;
#if DEBUG
printf("Check public key= %s\n", s1.s_5.keyInfo.sequence.first.v.c_str());
#endif
return value;
}
int sequence2Decoder(vector<string> myList, int start, struct seq2& s2)
{
int index=0;
s2= sequenceWith2(myList,start,index);
#if DEBUG
printf("Sequence 2 = %s\n", s2.first.v.c_str());
#endif
return index;
}
struct certificate decodeX509(char* input)
{
vector<string> myList;
char* parts;
parts = strtok(input," ");
while(parts)
{
//printf("%s\n",parts);
myList.push_back(parts);
parts = strtok(NULL," ");
}
//printf("Size of the vector: %d\n", myList.size());
struct certificate X509Structure;
int value;
string myTypeTag;
string myTypeValue;
string myTypeLength;
string headerLength;
value = TLVHeaderDecoder(myList, 0, 2, headerLength);
#if DEBUG
printf("Index = %d\n", value);
#endif
X509Structure.t = "30";
X509Structure.l = headerLength;
struct sequence1 s1;
value = sequence1Decoder(myList, value, s1);
#if DEBUG
printf("Index = %d\n", value);
//printf("length = %s\n", headerLength.c_str());
//printf("length = %d\n", hexToInt(headerLength));
#endif
struct seq2 s2;
value = sequence2Decoder(myList, value, s2);
#if DEBUG
printf("Index = %d\n", value);
#endif
struct tlv s3;
value = TLVDecoderNew(myList, value, 2, myTypeTag, myTypeLength, myTypeValue);
#if DEBUG
printf("Index = %d\n", value);
#endif
s3.t= myTypeTag;
s3.l = myTypeLength;
s3.v = myTypeValue;
X509Structure.s1 = s1;
X509Structure.s2 = s2;
X509Structure.s3 = s3;
return X509Structure;
}
struct publicKey* extractKeysFromCertificate(struct certificate cert)
{
int fp;
#if DEBUG
printf("Check modulus key= %s\n", cert.s1.s_5.keyInfo.sequence.first.v.c_str());
printf("Check e key= %s\n", cert.s1.s_5.keyInfo.sequence.second.v.c_str());
#endif
struct publicKey* pubKey = (struct publicKey*)malloc(sizeof(struct publicKey));
mpz_init(pubKey->n);
mpz_init_set_str(pubKey->n, cert.s1.s_5.keyInfo.sequence.first.v.c_str(), 16);
mpz_init(pubKey->e);
mpz_init_set_str(pubKey->e, cert.s1.s_5.keyInfo.sequence.second.v.c_str(), 16);
#if DEBUG
gmp_printf("\n%Zd\n", pubKey->n);
gmp_printf("\n%Zd\n", pubKey->e);
printf("Length of the certificate = %d\n", hexToInt(cert.l));
//printf("Length of the certificate = %s\n", cert.l.c_str());
#endif
/*int index=0;
fp =open("parseCert",O_WRONLY|O_CREAT);
if ( fp < 0 ) {
printf("unable to open file\n");
}
write(fp, "Certificate:\n",13);
write(fp, );
close(fp);*/
return pubKey;
}
//End the certificate related stuff
uint8_t generateNonZeroOctet()
{
srand(time(NULL));
uint8_t temp = rand()% 0xFF;
while(temp == 0x00)
temp = rand()% 0xFF;
temp |= 0x11;
return temp;
}
uint8_t* rsaEncryption(mpz_t n,mpz_t e,char* m,int mLen)
{
uint8_t* EM = new uint8_t[SIZE];
memset(EM, 0, SIZE);
uint8_t zeroByte=0x00;
uint8_t padStart=0x02;
uint8_t temp;
uint8_t* msg = (uint8_t*)m;
int start =0;
int index=0;
EM[index++]=zeroByte;
EM[index++]=padStart;
int padLen = SIZE - mLen -3;
for(int i=0; i<padLen; i++)
{
temp =generateNonZeroOctet();
EM[index++]=temp;
}
EM[index++]=zeroByte;
while(index<SIZE)
EM[index++]=msg[start++];
#if DEBUG
cout<<endl<<"Encryption thing"<<endl;
#endif
//for(int i=0; i<SIZE; i++)
// printf("%02x", EM[i]);
//cout<<endl;
mpz_t msgNum; mpz_init(msgNum);
mpz_t cipherNum; mpz_init(cipherNum);
mpz_import(msgNum, SIZE, 1, sizeof(EM[0]),0,0, EM);
#if DEBUG
gmp_printf("\n%Zd\n", msgNum);
printf("Size of the number : %d\n", mpz_sizeinbase(msgNum, 2));
#endif
mpz_powm(cipherNum,msgNum,e,n);
size_t cipherLen;
uint8_t* cipher= (uint8_t *)mpz_export(NULL,&cipherLen,1,1,0,0,cipherNum);
#if DEBUG
printf("The length of the ciphertext = %d\n", cipherLen);
#endif
if(cipherLen != SIZE)
{
printf("Encryption Failed: Cipher Length != BitRsa/8");
}
mpz_clear(msgNum);
mpz_clear(cipherNum);
return cipher;
}
uint8_t* leftPad(uint8_t* temp, int length, int size)
{
uint8_t* array = new uint8_t[size];
int diff = size-length;
memset(array,0, size);
memcpy(array+diff,temp, length);
return array;
}
uint8_t* rsaDecryption(mpz_t n, mpz_t d, uint8_t* cipher, int* finalLength)
{
mpz_t cipherNum; mpz_init(cipherNum);
mpz_t msgNum; mpz_init(msgNum);
mpz_import(cipherNum, SIZE, 1, sizeof(cipher[0]),0,0, cipher);
mpz_powm(msgNum, cipherNum, d, n);
//gmp_printf("\n%Zd\n", msgNum);
size_t msgLen;
uint8_t* tempMsg= (uint8_t *)mpz_export(NULL,&msgLen,1,1,0,0,msgNum);
//printf("The length of the message = %d\n", msgLen);
uint8_t* msg;
if(msgLen < SIZE)
{
msg = leftPad(tempMsg, msgLen, SIZE);
msgLen = SIZE;
}
else if (msgLen == SIZE)
{
msg = tempMsg;
}
else
{
printf("Decryption Failed:The size of the ecrypted message > BitRsa/8");
}
//for(int i=0; i<msgLen; i++)
// printf("%02x", msg[i]);
//cout<<endl;
//Checks for the added padding while encrypting
int index=0;
if(msg[index++] != 0x00)
{
printf("Decryption Failed: First Byte != 0x00");
return NULL;
}
if(msg[index++] != 0x02)
{
printf("Decryption Failed: Second Byte != 0x02");
return NULL;
}
int countNonZero =0;
while(msg[index++] != 0x00)
{
countNonZero++;
}
if(countNonZero <= 8)
{
printf("Decryption Failed: The psuedo random padding < 8");
return NULL;
}
#if DEBUG
for(int i=0; i<SIZE; i++)
printf("%02x",msg[i]);
cout<<endl;
#endif
uint8_t* m = new uint8_t[SIZE];
memset(m, 0, SIZE);
int j=0;
int k=index;
for(int i=index; i<SIZE; i++)
m[j++]=msg[index++];
//m[j]='\0';
//memcpy
*finalLength = SIZE-k;
return m;
}
string TLVEncoderHeader(int length)
{
string format;
char buf[2];
char typeHeader[2];
sprintf(typeHeader, "%02x", 48);
format += typeHeader;
if((length/2) <= 127)
{
sprintf(buf, "%02x", length/2);
format += buf;
}
else if((length/2) < 65536)
{
if((length/2) < 256)
{
sprintf(buf, "%02x", 129);
format += buf;
sprintf(buf, "%02x", length/2);
format += buf;
}
else
{
sprintf(buf, "%02x", 130);
format += buf;
char newBuf[4];
sprintf(newBuf, "%04x", length/2);
format += newBuf;
}
}
else
{
printf("Write code for this also x-( \n");
}
return format;
}
string TLVEncoder(char *input)
{
int length = strlen(input);
#if DEBUG
printf("Length is = %d of \n%s\n", length, input);
#endif
string format;
char *value;
char firstChar;
int temp=0;
if(length%2)
{
value = (char *)malloc(length+2);
memset(value, 0, length+2);
value[0] = '0';
memcpy((value+1),input, length);
}
else
{
//value = input;
//strcat(value, input);
firstChar = input[0];
#if DEBUG
printf("%c\n", firstChar);
#endif
if(isdigit(firstChar) && (temp=firstChar - '0')< 8)
{
#if DEBUG
printf("No 00 \n");
#endif
value = (char *)malloc(length+1);
memset(value, 0, length+1);
memcpy((value),input, length);
}
else
{
#if DEBUG
printf("yes 00 \n");
#endif
value = (char *)malloc(length+3);
memset(value, 0, length+3);
value[0] = '0';
value[1] = '0';
memcpy((value+2),input, length);
}
}
length = strlen(value);
//printf("%s\n", value);
//printf("%d\n", length);
char buf[2];
sprintf(buf, "%02x", 2);
format += buf;
if((length/2) <= 127)
{
sprintf(buf, "%02x", length/2);
format += buf;
}
else if((length/2) < 65536)
{
if((length/2) < 256)
{
sprintf(buf, "%02x", 129);
format += buf;
sprintf(buf, "%02x", length/2);
format += buf;
}
else
{
sprintf(buf, "%02x", 130);
format += buf;
char newBuf[4];
sprintf(newBuf, "%04x", length/2);
format += newBuf;
}
}
else
{
printf("Write code for this also x-( \n");
}
format +=value;
#if DEBUG
cout<<"Format :"<<endl<<format<<endl<<endl;
cout<<"Length : "<<format.size()<<endl<<endl;
#endif
return format;
}
uint8_t* NewEncoder(uint8_t *input, size_t length, size_t* outputSize)
{
uint8_t *output;
int flag=0;
size_t outputLength = length;
size_t tempLength = length;
//printf("%02x\n", input[0]);
uint8_t first = input[0] & 0x80;
//printf("%02x\n", first);
//printf("Length is :%d\n", length);
if(first == 0x80)
{
outputLength++;
flag=1;
}
tempLength = outputLength;
if(outputLength <=127)
{
outputLength++;
}
else if(outputLength > 127 && outputLength <= 255)
{
outputLength= outputLength+2;
}
else if(outputLength < 65536)
{
outputLength = outputLength+3;
}
outputLength = outputLength+1; //For byte of header
output = new uint8_t[outputLength];
int index=0;
output[index++]=0x02;
if(tempLength <=127)
{
output[index++]=(uint8_t)tempLength;
}
else if(tempLength > 127 && tempLength <= 255)
{
output[index++]=0x81;
output[index++]=(uint8_t)(tempLength);
}
else if(tempLength < 65536)
{
output[index++]=0x82;
output[index++]=(uint8_t)((tempLength & 0x0000ff00) >> 8);
output[index++]=(uint8_t)(tempLength);
}
if(flag==1)
output[index++]=0x00;
for(int i=0; i< length; i++)
output[index++]=input[i];
#if DEBUG
for(int i=0; i<outputLength; i++)
printf("%02x", output[i]);
cout<<endl;
#endif
*outputSize = outputLength;
return output;
}
uint8_t* NewHeaderEncoder(size_t length, size_t* outputSize)
{
uint8_t *output;
int flag=0;
size_t outputLength = 0;
size_t tempLength = length;
//printf("%02x\n", input[0]);
//printf("Length is :%d\n", length);
if(tempLength <=127)
{
outputLength++;
}
else if(tempLength > 127 && tempLength <= 255)
{
outputLength= outputLength+2;
}
else if(tempLength < 65536)
{
outputLength = outputLength+3;
}
outputLength = outputLength+1; //For byte of header
output = new uint8_t[outputLength];
int index=0;
output[index++]=0x30;
if(tempLength <=127)
{
output[index++]=(uint8_t)tempLength;
}
else if(tempLength > 127 && tempLength <= 255)
{
output[index++]=0x81;
output[index++]=(uint8_t)(tempLength);
}
else if(tempLength < 65536)
{
output[index++]=0x82;
output[index++]=(uint8_t)((tempLength & 0x0000ff00) >> 8);
output[index++]=(uint8_t)(tempLength);
}
#if DEBUG
for(int i=0; i<outputLength; i++)
printf("%02x", output[i]);
cout<<endl;
#endif
*outputSize = outputLength;
return output;
}
uint8_t* BitStringHeaderEncoder(size_t length, size_t* outputSize)
{
uint8_t *output;
int flag=0;
size_t outputLength = 0;
size_t tempLength = length;
//printf("%02x\n", input[0]);
//printf("Length is :%d\n", length);
if(tempLength <=127)
{
outputLength++;
}
else if(tempLength > 127 && tempLength <= 255)
{
outputLength= outputLength+2;
}
else if(tempLength < 65536)
{
outputLength = outputLength+3;
}
outputLength = outputLength+1; //For byte of header
output = new uint8_t[outputLength];
int index=0;
output[index++]=0x03;
if(tempLength <=127)
{
output[index++]=(uint8_t)tempLength;
}
else if(tempLength > 127 && tempLength <= 255)
{
output[index++]=0x81;
output[index++]=(uint8_t)(tempLength);
}
else if(tempLength < 65536)
{
output[index++]=0x82;
output[index++]=(uint8_t)((tempLength & 0x0000ff00) >> 8);
output[index++]=(uint8_t)(tempLength);
}
#if DEBUG
for(int i=0; i<outputLength; i++)
printf("%02x", output[i]);
cout<<endl;
#endif
*outputSize = outputLength;
return output;
}
void encodePublicKey(mpz_t n, mpz_t e, char* publicKeyFileName)
{
//Modulus
size_t mod_size;
uint8_t *modulus_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,n);
size_t nSize=0;
uint8_t* nBytes = NewEncoder(modulus_bytes, mod_size, &nSize);
// printf("Output Length is :%d\n\n", nSize);
uint8_t *e_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,e);
size_t eSize=0;
uint8_t* eBytes = NewEncoder(e_bytes, mod_size, &eSize);
// printf("Output Length is :%d\n\n", eSize);
//Without Header
size_t hSize = nSize+eSize;
// cout<<"Length of the document w/o header length "<<hSize<<endl;
//Header
size_t hLength=0;
uint8_t *hBytes = NewHeaderEncoder(hSize, &hLength);
// printf("Output Length is :%d\n\n", hLength);
//Total
size_t docSize = hLength+hSize;
// printf("Document size is :%d\n\n", docSize);
uint8_t *docBytes = new uint8_t[docSize+22];
memset(docBytes,0, sizeof(uint8_t)*(docSize+22));
//int count=0;
// while(count<docSize)
int index=0;
docBytes[index++]=0x30;
docBytes[index++]=0x81;
docBytes[index++]=0x9f;
docBytes[index++]=0x30;
docBytes[index++]=0x0d;
docBytes[index++]=0x06;
docBytes[index++]=0x09;
docBytes[index++]=0x2a;
docBytes[index++]=0x86;
docBytes[index++]=0x48;
docBytes[index++]=0x86;
docBytes[index++]=0xf7;
docBytes[index++]=0x0d;
docBytes[index++]=0x01;
docBytes[index++]=0x01;
docBytes[index++]=0x01;
docBytes[index++]=0x05;
docBytes[index++]=0x00;
docBytes[index++]=0x03;
docBytes[index++]=0x81;
docBytes[index++]=0x8d;
docBytes[index++]=0x00;
{
memcpy(docBytes+index, hBytes, hLength);
memcpy(docBytes+index+hLength, nBytes, nSize);
memcpy(docBytes+index+hLength+nSize, eBytes, eSize);
}
/*for(int i=0; i<(docSize+index++); i++)
printf("%02x", docBytes[i]);
cout<<endl<<endl;
*/ docSize = docSize+index++;
int DERFile;
// for(int i=0; i<docSize; i++)
// printf("%02x", docBytes[i]);
DERFile =open("public_1k.der",O_WRONLY|O_CREAT);
if ( DERFile < 0 ) {
printf("unable to open file\n");
}
for(int i=0; i<docSize; i++)
write(DERFile, (const void*)&docBytes[i], 1);
close(DERFile);
string encoded = base64_encode(reinterpret_cast<const unsigned char*>(docBytes),docSize);
// cout<<endl<<"Base64Coded string is:"<<endl<<encoded<<endl;
int PEMFile;
int counter = 0;
index=0;
const char* startPEM ="-----BEGIN PUBLIC KEY-----";
const char* endPEM="-----END PUBLIC KEY-----";
int encodedLength = encoded.size();
// printf("The size of encoded string is : %d\n", encodedLength);
char* base64encoded = (char*)(encoded.c_str());
PEMFile =open(publicKeyFileName,O_RDWR|O_CREAT);
if ( PEMFile < 0 )
{
printf("unable to open file\n");
}
write(PEMFile, startPEM, strlen(startPEM));
write(PEMFile,"\n", 1);
for(int i=0; i<encodedLength ; i++)
{
write(PEMFile,(const char*)&base64encoded[i], 1);
counter++;
if(counter == 64)
{
counter=0;
write(PEMFile,"\n", 1);
}
}
write(PEMFile,"\n", 1);
write(PEMFile, endPEM, strlen(endPEM));
write(PEMFile,"\n", 1);
close(PEMFile);
}
void encodePrivateKey(mpz_t n, mpz_t pub_key, mpz_t pri_key, mpz_t p, mpz_t q, mpz_t exp1, mpz_t exp2, mpz_t coef, char* privateKeyFileName)
{
//Algorithm
uint8_t aBytes[3];
aBytes[0]=0x02;
aBytes[1]=0x01;
aBytes[2]=0x00;
size_t aSize=3;
string algoString;
algoString="020100";
size_t mod_size;
//Modulus
uint8_t *modulus_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,n);
size_t nSize=0;
uint8_t* nBytes = NewEncoder(modulus_bytes, mod_size, &nSize);
// printf("Output Length is :%d\n\n", nSize);
/*
for(int i=0; i<nSize; i++)
printf("%02x", nBytes[i]);
cout<<endl;
*/
//string checkString = TLVEncoder((char *)modulus_bytes);
//string nString;
//nString = TLVEncoder(mpz_get_str(NULL, 16, n));
//Public key
uint8_t *e_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,pub_key);
size_t eSize=0;
uint8_t* eBytes = NewEncoder(e_bytes, mod_size, &eSize);
// printf("Output Length is :%d\n\n", eSize);
//string eString;
//eString = TLVEncoder(mpz_get_str(NULL, 16, pub_key));
//Private Key
uint8_t *d_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,pri_key);
size_t dSize=0;
uint8_t* dBytes = NewEncoder(d_bytes, mod_size, &dSize);
// printf("Output Length is :%d\n\n", dSize);
//string dString;
//dString = TLVEncoder(mpz_get_str(NULL, 16, pri_key));
//Prime p
uint8_t *p_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,p);
size_t pSize=0;
uint8_t* pBytes = NewEncoder(p_bytes, mod_size, &pSize);
// printf("Output Length is :%d\n\n", pSize);
//string pString;
//pString = TLVEncoder(mpz_get_str(NULL, 16, p));
//Prime q
uint8_t *q_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,q);
size_t qSize=0;
uint8_t* qBytes = NewEncoder(q_bytes, mod_size, &qSize);
// printf("Output Length is :%d\n\n", qSize);
//string qString;
//qString = TLVEncoder(mpz_get_str(NULL, 16, q));
//CRT EXP1
uint8_t *exp1_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,exp1);
size_t exp1Size=0;
uint8_t* exp1Bytes = NewEncoder(exp1_bytes, mod_size, &exp1Size);
// printf("Output Length is :%d\n\n", exp1Size);
//string exp1String;
//exp1String = TLVEncoder(mpz_get_str(NULL, 16, exp1));
//CRT EXP2
uint8_t *exp2_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,exp2);
size_t exp2Size=0;
uint8_t* exp2Bytes = NewEncoder(exp2_bytes, mod_size, &exp2Size);
// printf("Output Length is :%d\n\n", exp2Size);
//string exp2String;
//exp2String = TLVEncoder(mpz_get_str(NULL, 16, exp2));
//CRT COEF
uint8_t *u_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,coef);
size_t uSize=0;
uint8_t* uBytes = NewEncoder(u_bytes, mod_size, &uSize);
// printf("Output Length is :%d\n\n", uSize);
//string uString;
//uString = TLVEncoder(mpz_get_str(NULL, 16, coef));
//Without Header
size_t hSize = aSize+nSize+eSize+dSize+pSize+qSize+exp1Size+exp2Size+uSize;
// cout<<"Length of the document w/o header length "<<hSize<<endl;
//string totalWithoutHeader;
//totalWithoutHeader = algoString+nString+eString+dString+pString+qString+exp1String+exp2String+uString;
//int headerLength = totalWithoutHeader.size();
//cout<<"Length of the document = header length "<<headerLength<<endl;
cout<<endl<<endl;
//cout<<totalWithoutHeader<<endl;
//Header
size_t hLength=0;
uint8_t *hBytes = NewHeaderEncoder(hSize, &hLength);
// printf("Output Length is :%d\n\n", hLength);
//Total
size_t docSize = hLength+hSize;
// printf("Document size is :%d\n\n", docSize);
uint8_t *docBytes = new uint8_t[docSize];
memset(docBytes,0, sizeof(uint8_t)*docSize);
//int count=0;
// while(count<docSize)
{
memcpy(docBytes, hBytes, hLength);
memcpy(docBytes+hLength, aBytes, aSize);
memcpy(docBytes+hLength+aSize, nBytes, nSize);
memcpy(docBytes+hLength+aSize+nSize, eBytes, eSize);
memcpy(docBytes+hLength+aSize+nSize+eSize, dBytes, dSize);
memcpy(docBytes+hLength+aSize+nSize+eSize+dSize, pBytes, pSize);
memcpy(docBytes+hLength+aSize+nSize+eSize+dSize+pSize, qBytes, qSize);
memcpy(docBytes+hLength+aSize+nSize+eSize+dSize+pSize+qSize, exp1Bytes, exp1Size);
memcpy(docBytes+hLength+aSize+nSize+eSize+dSize+pSize+qSize+exp1Size, exp2Bytes, exp2Size);
memcpy(docBytes+hLength+aSize+nSize+eSize+dSize+pSize+qSize+exp1Size+exp2Size, uBytes, uSize);
}
#if DEBUG
for(int i=0; i<docSize; i++)
printf("%02x", docBytes[i]);
cout<<endl<<endl;
#endif
//string headerString;
//headerString = TLVEncoderHeader(headerLength);
//cout<<"Header String is : "<<headerString<<endl;
//string document;
//document = headerString+totalWithoutHeader;
cout<<endl<<endl;
//cout<<document<<endl;
//ofstream HEXFile;
// HEXFile.open("private_1024.hex");
// HEXFile<<document;
// HEXFile.close();
/*
ofstream DERFile;
DERFile.open("private_1024.der");
int index = 0;
vector<string> myList = myTokenizer(const_cast<char*>(document.c_str()));
for (vector<string>::iterator i = myList.begin();i != myList.end();i++)
{
//cout<< *i <<endl;
index = hexToInt(*i);
DERFile << (unsigned char)index;
}
DERFile.close();
*/
int DERFile;
#if DEBUG
for(int i=0; i<docSize; i++)
printf("%02x", docBytes[i]);
#endif
DERFile =open("private_1k.der",O_RDWR|O_CREAT);
if ( DERFile < 0 ) {
printf("unable to open file\n");
}
for(int i=0; i<docSize; i++)
write(DERFile, (const void*)&docBytes[i], 1);
close(DERFile);
string encoded = base64_encode(reinterpret_cast<const unsigned char*>(docBytes),docSize);
#if DEBUG
cout<<endl<<"Base64Coded string is:"<<endl<<encoded<<endl;
#endif
int PEMFile;
int counter = 0;
int index=0;
const char* startPEM ="-----BEGIN RSA PRIVATE KEY-----";
const char* endPEM="-----END RSA PRIVATE KEY-----";
int encodedLength = encoded.size();
// printf("The size of encoded string is : %d\n", encodedLength);
char* base64encoded = (char*)(encoded.c_str());
int newLineCheck = encodedLength;
PEMFile =open(privateKeyFileName,O_WRONLY|O_CREAT);
if ( PEMFile < 0 )
{
printf("unable to open file\n");
}
write(PEMFile, startPEM, strlen(startPEM));
write(PEMFile,"\n", 1);
for(int i=0; i<encodedLength ; i++)
{
write(PEMFile,(const char*)&base64encoded[i], 1);
counter++;
if(counter == 64)
{
counter=0;
if( i != (newLineCheck-1))
write(PEMFile,"\n", 1);
}
}
write(PEMFile,"\n", 1);
write(PEMFile, endPEM, strlen(endPEM));
close(PEMFile);
}
string readPEMFile(char* inputFile)
{
string output;
string line;
ifstream myfile (inputFile);
if(myfile.is_open())
{
while(myfile.good())
{
getline(myfile,line);
//cout<<line<<endl;
if(line[0]=='-')
continue;
output.append(line.c_str());
//output.append("\n");
//break;
}
#if DEBUG
cout<<output<<endl;
#endif
myfile.close();
}
#if DEBUG
printf("Length of the string array : %d\n",output.size());
printf("Length of the string array to char : %d\n",strlen(output.c_str()));
#endif
return output;
}
void encrypt(char* publicPEM, char* inputFileName, char* cipherFileName)
{
struct publicKey* pubKey;
string output = readPEMFile(publicPEM);
char *decoded = base64Decoder((char *)output.c_str());
pubKey = decodePublicKey(decoded);
int fmsg;
int msgLen;
//char* inputFileName = new char[255];
//printf("Enter the Message filename :\n");
//scanf("%s", inputFileName);
fmsg = open(inputFileName, O_RDONLY);
if(fmsg<0)
{
printf("Unable to open a read File\n");
}
char* textMessage = new char[SIZE-11];
memset(textMessage, 0, SIZE-11);
int numRead = read(fmsg, textMessage, SIZE-11);
#if DEBUG
printf("The length read from file : %d\n", strlen(textMessage));
printf("Message is:\n%s\n", textMessage);
#endif
msgLen = strlen(textMessage);
if(msgLen > MSGSIZE)
{
printf("Message too large for encryption\n");
exit(1);
}
//gmp_printf("\n%Zd\n", pubKey->e);
//gmp_printf("\n%Zd\n", pubKey->n);
uint8_t* encryptedText = rsaEncryption(pubKey->n,pubKey->e,textMessage,msgLen);
// printf("Returned from encryption\n");
int cipherFile;
//char* cipherFileName = new char[255];
//printf("Enter the Cipher filename :\n");
//scanf("%s", cipherFileName);
cipherFile =open(cipherFileName,O_RDWR|O_CREAT);
if ( cipherFile < 0 ) {
printf("unable to open file\n");
}
for(int i=0; i<SIZE; i++)
write(cipherFile, (const void*)&encryptedText[i], 1);
close(cipherFile);
mpz_clear(pubKey->n);
mpz_clear(pubKey->e);
free(pubKey);
}
uint8_t* rsaSignature(mpz_t n,mpz_t d,uint8_t* EM,int mLen)
{
mpz_t msgNum; mpz_init(msgNum);
mpz_t cipherNum; mpz_init(cipherNum);
mpz_import(msgNum, SIZE, 1, sizeof(EM[0]),0,0, EM);
//gmp_printf("\n%Zd\n", msgNum);
//printf("Size of the number : %d\n", mpz_sizeinbase(msgNum, 2));
mpz_powm(cipherNum,msgNum,d,n);
size_t cipherLen;
uint8_t* cipher= (uint8_t *)mpz_export(NULL,&cipherLen,1,1,0,0,cipherNum);
// printf("The length of the ciphertext = %d\n", cipherLen);
if(cipherLen != SIGNSIZE)
{
printf("Encryption Failed: Cipher Length != BitRsa/8");
}
mpz_clear(msgNum);
mpz_clear(cipherNum);
return cipher;
}
uint8_t* calculateT(uint8_t* hashMessage)
{
uint8_t* T = new uint8_t[SIGNSIZE];
memset(T, 0, SIGNSIZE);
uint8_t algoInfo[15] ={0x30,0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14};
//20+15
T[0]= 0x00;
T[1]= 0x01;
int lengthPS = SIZE - 35 - 3;
const uint8_t constantPad = 0xff;
int index=2;
for(int i=0; i<lengthPS; i++)
{
T[index++]=0xff;
}
T[index++]=0x00;
memcpy(T+index, algoInfo, sizeof(uint8_t)*15);
memcpy(T+index+15, hashMessage, sizeof(uint8_t)*20);
#if DEBUG
for(int i=0; i<SIGNSIZE; i++)
printf("%02x ",T[i]);
printf("\n");
#endif
return T;
}
void signMessage(char* priPEM, char* inputFileName, char* cipherFileName)
{
struct privateKey* priKey;
string output = readPEMFile(priPEM);
char *decoded = base64Decoder((char *)output.c_str());
priKey = decodePrivateKey(decoded);
int fmsg;
int msgLen;
//char* inputFileName = new char[255];
//printf("Enter the Message filename :\n");
//scanf("%s", inputFileName);
fmsg = open(inputFileName, O_RDONLY);
if(fmsg<0)
{
printf("Unable to open a read File\n");
}
char* textMessage = new char[SIGNSIZE];
memset(textMessage, 0, SIGNSIZE);
int numRead = read(fmsg, textMessage, SIGNSIZE);
// printf("The length read from file : %d\n", strlen(textMessage));
// printf("Message is:\n%s\n", textMessage);
msgLen = strlen(textMessage);
uint8_t* hashMessage = new uint8_t[20];
memset(hashMessage, 0, 20);
SHA1((const unsigned char*)textMessage,msgLen, hashMessage);
// printf("Hash message = %s\n", hashMessage);
uint8_t* T = calculateT(hashMessage);
#if DEBUG
for(int i=0; i<SIGNSIZE; i++)
printf("%02x ",T[i]);
printf("\n");
#endif
//gmp_printf("\n%Zd\n", pubKey->e);
//gmp_printf("\n%Zd\n", pubKey->n);
uint8_t* encryptedText = rsaSignature(priKey->n,priKey->d,T, SIZE);
// printf("Returned from encryption\n");
int cipherFile;
//char* cipherFileName = new char[255];
//printf("Enter the Cipher sign filename :\n");
//scanf("%s", cipherFileName);
cipherFile =open(cipherFileName,O_RDWR|O_CREAT);
if ( cipherFile < 0 ) {
printf("unable to open file\n");
}
for(int i=0; i<SIGNSIZE; i++)
write(cipherFile, (const void*)&encryptedText[i], 1);
close(cipherFile);
freePrivateStructure(priKey);
}
void encryptByCertificate(char* certPEM, char* inputFileName, char* cipherFileName)
{
string output;
string line;
ifstream myfile (certPEM);
if(myfile.is_open())
{
while(myfile.good())
{
getline(myfile,line);
//cout<<line<<endl;
if(line[0]=='-')
continue;
output.append(line.c_str());
//output.append("\n");
//break;
}
#if DEBUG
cout<<output<<endl;
#endif
myfile.close();
}
char *decoded = base64Decoder((char *)output.c_str());
//char *decoded = base64Decoder(input);
struct certificate structure;
structure = decodeX509(decoded);
struct publicKey* pubKey = extractKeysFromCertificate(structure);
int fmsg;
int msgLen;
//char* inputFileName = new char[255];
//printf("Enter the Message filename :\n");
//scanf("%s", inputFileName);
fmsg = open(inputFileName, O_RDONLY);
if(fmsg<0)
{
printf("Unable to open a read File\n");
}
char* textMessage = new char[SIZE-11];
memset(textMessage, 0, SIZE-11);
int numRead = read(fmsg, textMessage, SIZE-11);
#if DEBUG
printf("The length read from file : %d\n", strlen(textMessage));
printf("Message is:\n%s\n", textMessage);
#endif
msgLen = strlen(textMessage);
if(msgLen > MSGSIZE)
{
printf("Message too large for encryption\n");
exit(1);
}
//gmp_printf("\n%Zd\n", pubKey->e);
//gmp_printf("\n%Zd\n", pubKey->n);
uint8_t* encryptedText = rsaEncryption(pubKey->n,pubKey->e,textMessage,msgLen);
// printf("Returned from encryption\n");
int cipherFile;
//char* cipherFileName = new char[255];
//printf("Enter the Cipher filename :\n");
//scanf("%s", cipherFileName);
cipherFile =open(cipherFileName,O_WRONLY|O_CREAT);
if ( cipherFile < 0 ) {
printf("unable to open file\n");
}
for(int i=0; i<SIZE; i++)
write(cipherFile, (const void*)&encryptedText[i], 1);
close(cipherFile);
mpz_clear(pubKey->n);
mpz_clear(pubKey->e);
free(pubKey);
}
void decrypt(char* privatePEM, char* cipherFileName, char* decipherFileName)
{
struct privateKey* priKey;
string output = readPEMFile(privatePEM);
char *decoded = base64Decoder((char *)output.c_str());
priKey = decodePrivateKey(decoded);
//char* cipherFileName = new char[255];
//printf("Enter the encrypted File name :\n");
//scanf("%s", cipherFileName);
int cmsg;
cmsg = open(cipherFileName, O_RDONLY);
if(cmsg<0)
{
printf("Unable to open a read File\n");
}
uint8_t* encryptedText = new uint8_t[SIZE];
memset(encryptedText, 0, SIZE);
int numRead = read(cmsg, encryptedText, SIZE);
//printf("The length read from file : %d\n", strlen((unsigned char *)encryptedText));
int finalLength;
uint8_t* decryptedText = rsaDecryption(priKey->n, priKey->d, encryptedText, &finalLength);
//printf("FinalLength = %d\n", finalLength);
int decryptedFile;
decryptedFile =open(decipherFileName,O_RDWR|O_CREAT);
if ( decryptedFile < 0 ) {
printf("unable to open file\n");
}
for(int i=0; i<finalLength; i++)
write(decryptedFile, (const void*)&decryptedText[i], 1);
close(decryptedFile);
}
void rsaVerify(mpz_t n, mpz_t e, uint8_t* cipher, int* finalLength, char* inputFileName)
{
mpz_t cipherNum; mpz_init(cipherNum);
mpz_t msgNum; mpz_init(msgNum);
mpz_import(cipherNum, SIZE, 1, sizeof(cipher[0]),0,0, cipher);
mpz_powm(msgNum, cipherNum, e, n);
//gmp_printf("\n%Zd\n", msgNum);
size_t tempmsgLen;
uint8_t* tempMsg= (uint8_t *)mpz_export(NULL,&tempmsgLen,1,1,0,0,msgNum);
// printf("The length of the message = %d\n", tempmsgLen);
uint8_t* msg;
if(tempmsgLen < SIZE)
{
msg = leftPad(tempMsg, tempmsgLen, SIZE);
tempmsgLen = SIZE;
}
else if (tempmsgLen == SIZE)
{
msg = tempMsg;
}
else
{
printf("Decryption Failed:The size of the ecrypted message > BitRsa/8");
}
int fmsg;
int msgLen;
//char* inputFileName = new char[255];
//printf("Enter the Message filename :\n");
//scanf("%s", inputFileName);
fmsg = open(inputFileName, O_RDONLY);
if(fmsg<0)
{
printf("Unable to open a read File\n");
}
char* textMessage = new char[SIGNSIZE];
memset(textMessage, 0, SIGNSIZE);
int numRead = read(fmsg, textMessage, SIGNSIZE);
#if DEBUG
printf("The length read from file : %d\n", strlen(textMessage));
printf("Message is:\n%s\n", textMessage);
#endif
msgLen = strlen(textMessage);
uint8_t* hashMessage = new uint8_t[20];
memset(hashMessage, 0, 20);
SHA1((const unsigned char*)textMessage,msgLen, hashMessage);
// printf("Hash message = %s\n", hashMessage);
uint8_t* T = calculateT(hashMessage);
if(memcmp(T, msg, SIGNSIZE) == 0)
{
printf("\nVerification OK\n");
}
else
{
printf("\nVerification Failure\n");
}
}
void verifySign(char* pubPEM, char* cipherFileName, char* inputFileName)
{
struct publicKey* pubKey;
string output = readPEMFile(pubPEM);
char *decoded = base64Decoder((char *)output.c_str());
pubKey = decodePublicKey(decoded);
//char* cipherFileName = new char[255];
//printf("Enter the encrypted Sig File name :\n");
//scanf("%s", cipherFileName);
int cmsg;
cmsg = open(cipherFileName, O_RDONLY);
if(cmsg<0)
{
printf("Unable to open a read File\n");
}
uint8_t* encryptedText = new uint8_t[SIZE];
memset(encryptedText, 0, SIZE);
int numRead = read(cmsg, encryptedText, SIZE);
//printf("The length read from file : %d\n", strlen((unsigned char *)encryptedText));
int finalLength;
rsaVerify(pubKey->n, pubKey->e, encryptedText, &finalLength, inputFileName);
}
void verifySignByCertificate(char* certPEM, char* cipherFileName, char* inputFileName)
{
string output;
string line;
ifstream myfile (certPEM);
if(myfile.is_open())
{
while(myfile.good())
{
getline(myfile,line);
//cout<<line<<endl;
if(line[0]=='-')
continue;
output.append(line.c_str());
//output.append("\n");
//break;
}
#if DEBUG
cout<<output<<endl;
#endif
myfile.close();
}
char *decoded = base64Decoder((char *)output.c_str());
//char *decoded = base64Decoder(input);
struct certificate structure;
structure = decodeX509(decoded);
struct publicKey* pubKey = extractKeysFromCertificate(structure);
int cmsg;
cmsg = open(cipherFileName, O_RDONLY);
if(cmsg<0)
{
printf("Unable to open a read File\n");
}
uint8_t* encryptedText = new uint8_t[SIZE];
memset(encryptedText, 0, SIZE);
int numRead = read(cmsg, encryptedText, SIZE);
//printf("The length read from file : %d\n", strlen((unsigned char *)encryptedText));
int finalLength;
rsaVerify(pubKey->n, pubKey->e, encryptedText, &finalLength, inputFileName);
}
void encodePublicKeyNew(mpz_t n, mpz_t e, char* publicKeyFileName)
{
// printf("Public key Part\n");
//Modulus
size_t mod_size;
uint8_t *modulus_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,n);
size_t nSize=0;
uint8_t* nBytes = NewEncoder(modulus_bytes, mod_size, &nSize);
#if DEBUG
printf("Output Length is :%d\n\n", nSize);
#endif
uint8_t *e_bytes = (uint8_t *)mpz_export(NULL,&mod_size,1,1,0,0,e);
size_t eSize=0;
uint8_t* eBytes = NewEncoder(e_bytes, mod_size, &eSize);
#if DEBUG
printf("Output Length is :%d\n\n", eSize);
#endif
//Without Header
size_t hSize = nSize+eSize;
// cout<<"Length of the document w/o header length "<<hSize<<endl;
//Header
size_t hLength=0;
uint8_t *hBytes = NewHeaderEncoder(hSize, &hLength);
// printf("Output Length is :%d\n\n", hLength);
size_t bitStringSequenceLength = hLength+hSize+1;
size_t bitStringHeaderLength=0;
uint8_t *bitStringBytes = BitStringHeaderEncoder(bitStringSequenceLength, &bitStringHeaderLength);
#if DEBUG
printf("Output Length including bit string is :%d\n\n", bitStringHeaderLength);
for(int i=0; i<(bitStringHeaderLength); i++)
printf("%02x", bitStringBytes[i]);
cout<<endl<<endl;
#endif
uint8_t bitpadByte = 0x00;
size_t sequenceLength = 15;
size_t lengthWOHeader = sequenceLength+bitStringHeaderLength+bitStringSequenceLength;
// printf("Output Length except header is :%d\n\n", lengthWOHeader);
size_t docHeaderLength=0;
uint8_t *startBytes = NewHeaderEncoder(lengthWOHeader, &docHeaderLength);
#if DEBUG
printf("Output Header Length is :%d\n\n", docHeaderLength);
for(int i=0; i<(docHeaderLength); i++)
printf("%02x", startBytes[i]);
cout<<endl<<endl;
#endif
//Total
size_t docSize = docHeaderLength+lengthWOHeader;
// printf("Document size is :%d\n\n", docSize);
uint8_t *docBytes = new uint8_t[docSize];
memset(docBytes,0, sizeof(uint8_t)*(docSize));
//int count=0;
// while(count<docSize)
int index=0;
memcpy(docBytes, startBytes, docHeaderLength);
//docBytes[index++]=0x30;
//docBytes[index++]=0x81;
//docBytes[index++]=0x9f;
index = docHeaderLength;
docBytes[index++]=0x30;
docBytes[index++]=0x0d;
docBytes[index++]=0x06;
docBytes[index++]=0x09;
docBytes[index++]=0x2a;
docBytes[index++]=0x86;
docBytes[index++]=0x48;
docBytes[index++]=0x86;
docBytes[index++]=0xf7;
docBytes[index++]=0x0d;
docBytes[index++]=0x01;
docBytes[index++]=0x01;
docBytes[index++]=0x01;
docBytes[index++]=0x05;
docBytes[index++]=0x00;
memcpy(docBytes+index,bitStringBytes, bitStringHeaderLength);
index = index+bitStringHeaderLength;
//docBytes[index++]=0x03;
//docBytes[index++]=0x81;
//docBytes[index++]=0x8d;
docBytes[index++]=0x00;
{
memcpy(docBytes+index, hBytes, hLength);
memcpy(docBytes+index+hLength, nBytes, nSize);
memcpy(docBytes+index+hLength+nSize, eBytes, eSize);
}
#if DEBUG
for(int i=0; i<(docSize); i++)
printf("%02x", docBytes[i]);
cout<<endl<<endl;
#endif
int DERFile;
// for(int i=0; i<docSize; i++)
// printf("%02x", docBytes[i]);
DERFile =open("public_1k.der",O_WRONLY|O_CREAT);
if ( DERFile < 0 ) {
printf("unable to open file\n");
}
for(int i=0; i<docSize; i++)
write(DERFile, (const void*)&docBytes[i], 1);
close(DERFile);
string encoded = base64_encode(reinterpret_cast<const unsigned char*>(docBytes),docSize);
#if DEBUG
cout<<endl<<"Base64Coded string is:"<<endl<<encoded<<endl;
#endif
int PEMFile;
int counter = 0;
index=0;
const char* startPEM ="-----BEGIN PUBLIC KEY-----";
const char* endPEM="-----END PUBLIC KEY-----";
int encodedLength = encoded.size();
// printf("The size of encoded string is : %d\n", encodedLength);
char* base64encoded = (char*)(encoded.c_str());
int newLineCheck = encodedLength;
PEMFile =open(publicKeyFileName,O_RDWR|O_CREAT);
if ( PEMFile < 0 )
{
printf("unable to open file\n");
}
write(PEMFile, startPEM, strlen(startPEM));
write(PEMFile,"\n", 1);
for(int i=0; i<encodedLength ; i++)
{
write(PEMFile,(const char*)&base64encoded[i], 1);
counter++;
if(counter == 64)
{
counter=0;
if( i != (newLineCheck-1))
write(PEMFile,"\n", 1);
}
}
write(PEMFile,"\n", 1);
write(PEMFile, endPEM, strlen(endPEM));
write(PEMFile,"\n", 1);
close(PEMFile);
}
void genKeys(char* privateKeyFile, char* publicKeyFile)
{
mpz_t pub_key; mpz_init(pub_key);
mpz_t pri_key; mpz_init(pri_key);
mpz_t p; mpz_init(p);
mpz_t q; mpz_init(q);
mpz_t phi; mpz_init(phi);
mpz_t n; mpz_init(n);
mpz_t temp; mpz_init(temp);
mpz_t temp1; mpz_init(temp1);
mpz_t check; mpz_init(check);
mpz_t exp1; mpz_init(exp1);
mpz_t exp2; mpz_init(exp2);
mpz_t coef; mpz_init(coef);
char buf[BUFSIZE];
char infile[100];
char outfile[100];
FILE *fin, *fout;
long lFileLen;
int index=0;
//Initializing my public key
//65,537
mpz_set_ui(pub_key, 0x10001);
#if DEBUG
printf("My Public key is :");
gmp_printf("\n%Zd\n", pub_key);
#endif
//srand(time(NULL));
for (int i=0; i< BUFSIZE; i++)
{
buf[i]= rand() % 0xFF;
}
//Set the initial bits of the buffer to 1, so te ensure we get a relatively large number
buf[0] |= 0xC0;
//Set the last bit of buffer to 1, so to get an odd number
buf[BUFSIZE-1] |= 0x01;
//Now convert this char buffer to an int
mpz_import(temp, BUFSIZE, 1, sizeof(buf[0]), 0, 0, buf);
//gmp_printf("\n%Zd\n", temp);
mpz_nextprime(p, temp);
//gmp_printf("\n%Zd\n", p);
//printf("Check if p is coprime or not, Ideally it should be :) \n");
//mpz_mod(check,p,pub_key);
//gmp_printf("%Zd\n",check);
//printf("......Finished checking......\n");
memset(buf, 0, sizeof(buf));
do{
for (int i=0; i< BUFSIZE; i++)
{
buf[i]= rand() % 0xFF;
}
//Set the initial bits of the buffer to 1, so te ensure we get a relatively large number
buf[0] |= 0xC0;
//Set the last bit of buffer to 1, so to get an odd number
buf[BUFSIZE-1] |= 0x01;
//Now convert this char buffer to an int
mpz_import(temp, BUFSIZE, 1, sizeof(buf[0]), 0, 0, buf);
// gmp_printf("\n%Zd\n", temp);
mpz_nextprime(q, temp);
// gmp_printf("\n%Zd\n", q);
// printf("Check if q is coprime or not, Ideally it should be :) \n");
// mpz_mod(check,q,pub_key);
// gmp_printf("%Zd\n",check);
// printf("......Finished checking......\n");
}while(mpz_cmp(p,q) == 0);
//Computing and storing the value of n = p.q
mpz_mul(n,p,q);
//gmp_printf("\n Value of n \n%Zd\n", n);
//Compute phi = (p-1).(q-1)
mpz_sub_ui(temp, p, 1);
mpz_sub_ui(temp1, q, 1);
mpz_mul(phi, temp, temp1);
//gmp_printf("\n Value of phi \n%Zd\n", phi);
//if(mpz_cmp(n,phi) > 0)
// printf("\n n > phi \n");
mpz_gcd(temp, pub_key, phi);
if(mpz_cmp_ui(temp,1) != 0)
{
printf("\n Rechoose your public key or use different primes: e mod(phi)!=1\n");
exit(0);
}
//Calculating private key
mpz_invert(pri_key, pub_key, phi);
//gmp_printf("\n Value of private key \n%Zd\n", pri_key);
mpz_mul(temp, pub_key, pri_key);
mpz_mod(temp1, temp, phi);
gmp_printf("\n e.d mod(phi) = %Zd\n", temp1);
//gmp_printf("\n%Zd\n", p);
//gmp_printf("\n%Zd\n", q);
//Checking p<q
/*if(mpz_cmp(p,q) > 0)
{
mpz_set(temp, p);
mpz_set(p, q);
mpz_set(q, temp);
}*/
//gmp_printf("\n%Zd\n", p);
//gmp_printf("\n%Zd\n", q);
//Generating the chinese remainder coefficient
mpz_sub_ui(temp, p, 1);
mpz_sub_ui(temp1, q, 1);
mpz_mod(exp1, pri_key, temp);
mpz_mod(exp2, pri_key, temp1);
mpz_mod_inverse(coef,q ,p);
encodePrivateKey(n, pub_key, pri_key, p, q, exp1, exp2, coef, privateKeyFile);
encodePublicKeyNew(n, pub_key, publicKeyFile);
mpz_clear(pub_key);
mpz_clear(pri_key);
mpz_clear(p);
mpz_clear(q);
mpz_clear(n);
mpz_clear(phi);
mpz_clear(exp1);
mpz_clear(exp2);
mpz_clear(coef);
mpz_clear(temp);
mpz_clear(temp1);
mpz_clear(check);
exit(0);
}
void printUsage(char* execName)
{
printf("For generating private and public key pair\n");
printf("%s genra <privateKeyFileName> <publicKeyFileName>\n", execName);
printf("For encryption\n");
printf("%s -e -key <PrivatePemFile> -in PlainTextFile -out CipherTextFile\n", execName);
printf("For encryption from certificate\n");
printf("%s -e -crt <Certificate> -in PlainTextFile -out CipherTextFile\n", execName);
printf("For decryption\n");
printf("%s -d -key <PublicPemFile> -in CipherTextFile -out DecipheredTextFile\n", execName);
printf("For Signing data with Private Key\n");
printf("%s -s -key <PrivatePemFile> -in PlainTextFile -out SignedDataFile\n", execName);
printf("For Verifying data with Public Key\n");
printf("%s -v -key <PublicPemFile> -signature SignedDataFile PlainTextFile\n", execName);
printf("For Verifying data with Certificate\n");
printf("%s -v -crt <Certificate> -signature SignedDataFile PlainTextFile\n", execName);
exit(0);
}
int main(int argc, char *argv[])
{
char buf[BUFSIZE], message[MSGSIZE], *cipherText, *decreptedText;
FILE *fin, *fout;
long lFileLen;
int index=0;
const char *s1,*s2,*s3;
const char *s4,*s5,*s6;
const char *s7, *s8, *s9;
const char *s10;
const char *help;
help="-h";
s1 = "genrsa";
s2 = "-e";
s3 = "-d";
s4 = "-key";
s5 ="-in";
s6 = "-out";
s7 = "-crt";
s8 = "-s";
s9 = "-v";
s10= "-signature";
int argCheck =0;
//Command Line options
if(argc == 2)
{
if(strcmp(argv[1],help) == 0)
{
printUsage(argv[0]);
}
exit(0);
}
if (argc == 4)
{
if(strcmp(argv[1], s1) == 0)
{
printf("Usage:\n%s genrsa\n", argv[0]);
genKeys((char*)argv[2], (char*)argv[3]);
}
else if(strcmp(argv[1],help) == 0)
{
printUsage(argv[0]);
}
else
{
printf("Type:\n%s -h for help commands \n", argv[0]);
exit(0);
}
exit(0);
}
//printf("In ecryption\n");
if((argc == 8) && ((strcmp(argv[1],s2)==0) || (strcmp(argv[1],s3)==0)))
{
//printf("In ecryption\n");
if((strcmp(argv[1],s2)==0) && (strcmp(argv[2], s4)==0) && (strcmp(argv[4], s5)==0) && (strcmp(argv[6], s6)==0))
{
//printf("In ecryption\n");
encrypt((char*)argv[3], (char*)argv[5], (char*)argv[7]);
exit(0);
}
else if((strcmp(argv[1],s2)==0) && (strcmp(argv[2], s7)==0) && (strcmp(argv[4], s5)==0) && (strcmp(argv[6], s6)==0))
{
encryptByCertificate((char*)argv[3], (char*)argv[5], (char*)argv[7]);
exit(0);
}
else if((strcmp(argv[1],s3)==0) && (strcmp(argv[2], s4)==0) && (strcmp(argv[4], s5)==0) && (strcmp(argv[6], s6)==0))
{
decrypt((char*)argv[3], (char*)argv[5], (char*)argv[7]);
exit(0);
}
else
{
printf("Type:\n%s -h for help commands \n", argv[0]);
exit(0);
}
}
else if((argc == 8) && ((strcmp(argv[1],s8)==0)))
{
if((strcmp(argv[2], s4)==0) && (strcmp(argv[4], s5)==0) && (strcmp(argv[6], s6)==0))
{
signMessage((char*)argv[3], (char*)argv[5], (char*)argv[7]);
exit(0);
}
else
{
printf("Type:\n%s -h for help commands \n", argv[0]);
exit(0);
}
}
if(argc == 7)
{
if((strcmp(argv[1],s9)==0) && (strcmp(argv[2], s4)==0) && (strcmp(argv[4], s10)==0) )
{
verifySign((char*)argv[3], (char*)argv[5], (char*)argv[6]);
exit(0);
}
else if((strcmp(argv[1],s9)==0) && (strcmp(argv[2], s7)==0) && (strcmp(argv[4], s10)==0))
{
verifySignByCertificate((char*)argv[3], (char*)argv[5], (char*)argv[6]);
exit(0);
}
}
else
{
printf("Type:\n%s -h for help commands \n", argv[0]);
exit(0);
}
printf("Type:\n%s -h for help commands \n", argv[0]);
exit(0);
exit(0);
#if ENCRYPT
char* pubFileName = new char[255];
printf("Enter the Public Key File for encryption:\n");
scanf("%s", pubFileName);
encrypt((char *)pubFileName);
char* priFileName = new char[255];
printf("Enter the Private Key File for signature:\n");
scanf("%s", priFileName);
signMessage((char *)priFileName);
char* pubSignFileName = new char[255];
printf("Enter the Public Key File for signature:\n");
scanf("%s", pubSignFileName);
verifySign((char *)pubSignFileName);
#endif
#if ENCRYPT
char* priPemFileName = new char[255];
printf("Enter the Private Key File for decryption:\n");
scanf("%s", priPemFileName);
decrypt((char *)priPemFileName);
#endif
//encryptByCertificate();
#if ENCRYPT
/**
** Code take cares of the decryption
**/
char* decryptedText = rsaDecryption(n, pri_key, encryptedText);
int decryptedFile;
decryptedFile =open("decipheredText",O_WRONLY|O_CREAT);
if ( decryptedFile < 0 ) {
printf("unable to open file\n");
}
for(int i=0; i<SIZE; i++)
write(decryptedFile, (const void*)&decryptedText[i], 1);
close(decryptedFile);
#endif
}
| [
"prankur.07@gmail.com"
] | prankur.07@gmail.com |
dd65570b9ce936d8b256816347695d10cda4f77f | 8b63f0deb717cbd11a13f418d70f18a612c99d56 | /Metos_Numericos/6-Runge-Kutte.cpp | 3e63cc4ee1ded8b4cbe6bd79f5ffe8ff2355f4d9 | [] | no_license | Israel-Eskape/C- | ebb5aeacbb6f9603b6b1ec79f51c81c033188a0a | 58ac60d42d57634974bc8d73beed655d7683fb47 | refs/heads/master | 2022-04-19T23:40:40.912906 | 2020-04-21T01:46:09 | 2020-04-21T01:46:09 | 257,428,376 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double yi(double y,double k1,double k2,double h){
return y+(0.5*k1+0.5*k2)*h;
}
double fun(double x,double y){
return x-y;
}
int main(){
double y,x,h,k1,k2,r;
int yf=10;
y=2;
h=0.2;
x=0;
for(int i=0;i<yf/2;i++){
k1=fun(x,y);
k2=fun(x+h,y+k1*h);
y=yi(y,k1,k2,h);
x+=h;
printf("X(%d)= %g Y(%d)= %g\n",i+1,x,i+1,y);
}
system ("pause");
return 0;
}
| [
"isra.ixoye@gmail.com"
] | isra.ixoye@gmail.com |
15b771928b361c5b13dc56109c65a3bc6d15ef4e | 5885fd1418db54cc4b699c809cd44e625f7e23fc | /codeforces/1167/d.cpp | 98262d5a7737484a17355b2854185cb07d3650cb | [] | no_license | ehnryx/acm | c5f294a2e287a6d7003c61ee134696b2a11e9f3b | c706120236a3e55ba2aea10fb5c3daa5c1055118 | refs/heads/master | 2023-08-31T13:19:49.707328 | 2023-08-29T01:49:32 | 2023-08-29T01:49:32 | 131,941,068 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,651 | cpp | #include <bits/stdc++.h>
using namespace std;
#define _USE_MATH_DEFINES
#define For(i,n) for (int i=0; i<n; i++)
#define FOR(i,a,b) for (int i=a; i<=b; i++)
#define Down(i,n) for (int i=n-1; i>=0; i--)
#define DOWN(i,a,b) for (int i=b; i>=a; i--)
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ld,ld> pdd;
typedef complex<ld> pt;
typedef vector<pt> pol;
typedef vector<int> vi;
const char nl = '\n';
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3f;
const ll MOD = 1e9+7;
const ld EPS = 1e-10;
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
const int N = 2e5+1;
vector<int> adj[N];
int par[N], col[N], depth[N], height[N];
void dfs(int u) {
if (u) depth[u] = 1 + depth[par[u]];
for (int v : adj[u]) {
dfs(v);
height[u] = max(height[u], 1 + height[v]);
}
col[u] = (depth[u] > height[u]);
}
//#define FILEIO
int main() {
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cout << fixed << setprecision(10);
#ifdef FILEIO
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);
#endif
int n;
cin >> n;
string s;
cin >> s;
{
int u = 0;
int id = 1;
for (char c : s) {
if (c == '(') {
par[id] = u;
adj[u].push_back(id);
u = id++;
} else {
u = par[u];
}
}
}
dfs(0);
{
int u = 0;
int id = 1;
for (char c : s) {
if (c == '(') {
par[id] = u;
adj[u].push_back(id);
u = id++;
cout << col[u];
} else {
cout << col[u];
u = par[u];
}
}
cout << nl;
}
return 0;
}
| [
"henryxia9999@gmail.com"
] | henryxia9999@gmail.com |
b5d4c2a972249ffed244f9592d42a62a2264ab8c | a565dc8a731c4166548d3e3bf8156c149d793162 | /PLATFORM/TI_EVM_3530/SRC/DRIVERS/PM/DLL/pmrelation.cpp | 689b19fed64d53a6d09859b9c68a3571d70956ce | [] | no_license | radtek/MTI_WINCE317_BSP | eaaf3147d3de9a731a011b61f30d938dc48be5b5 | 32ea5df0f2918036f4b53a4b3aabecb113213cc6 | refs/heads/master | 2021-12-08T13:09:24.823090 | 2016-03-17T15:27:44 | 2016-03-17T15:30:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,324 | cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.
//
//
// This module contains routines for handling power relationships. A
// device such as NDIS or a bus driver can register as a parent of another
// device. The parent will act as a proxy for all requests going to the
// child device. Parent devices can register with the PM when they handle
// the IOCTL_REGISTER_POWER_RELATIONSHIP message.
//
#include <pmimpl.h>
// This routine sets up a proxy relationship between a parent device
// and a child device. This will overwrite any other proxy relationships
// created for the child device. Only one level of relationships is
// supported; that is, a parent device cannot itself be a child device.
// This routine passes back an handle to the relationship and sets the
// global error status to:
// ERROR_SUCCESS - relationship set up ok
// ERROR_INVALID_PARAMETER - bad parameter of some sort
// ERROR_FILE_EXISTS - child device already registered
// Note that in this implementation, a device cannot register itself
// (using AdvertiseInterface()) and then have a parent register to
// proxy for it.
EXTERN_C HANDLE WINAPI
PmRegisterPowerRelationship(PVOID pvParent, PVOID pvChild,
PPOWER_CAPABILITIES pCaps, DWORD dwFlags)
{
PDEVICEID pdiParent = NULL, pdiChild = NULL;
PDEVICE_LIST pdlParent, pdlChild;
PDEVICE_STATE pdsParent = NULL;
PDEVICE_STATE pdsChild = NULL;
DWORD dwStatus = ERROR_SUCCESS;
SETFNAME(_T("PmRegisterPowerRelationship"));
PMLOGMSG(ZONE_API, (_T("+%s\r\n"), pszFname));
// sanity check parameters
if(pvParent == NULL
|| pvChild == NULL
|| (pdiParent = DeviceIdParseNameString((LPCTSTR) pvParent, dwFlags)) == NULL
|| (pdiChild = DeviceIdParseNameString((LPCTSTR) pvChild, dwFlags)) == NULL) {
dwStatus = ERROR_INVALID_PARAMETER;
}
// parameters ok so far?
if(dwStatus == ERROR_SUCCESS) {
pdlChild = GetDeviceListFromClass(pdiChild->pGuid);
if(dwStatus == ERROR_SUCCESS) {
// Look up device lists for parent and child, plus the parent
// and child device structures. The child cannot already exist.
pdlParent = GetDeviceListFromClass(pdiParent->pGuid);
if(pdlParent == NULL || pdlChild == NULL) {
PMLOGMSG(ZONE_WARN, (_T("%s: can't find class for parent or child\r\n"),
pszFname));
dwStatus = ERROR_INVALID_PARAMETER;
} else if((pdsChild = DeviceStateFindList(pdlChild, pdiChild->pszName)) != NULL) {
PMLOGMSG(ZONE_WARN, (_T("%s: child '%s' already exists\r\n"),
pszFname, pdiChild->pszName));
DeviceStateDecRef(pdsChild);
dwStatus = ERROR_FILE_EXISTS;
} else {
pdsParent = DeviceStateFindList(pdlParent, pdiParent->pszName);
if(pdsParent == NULL) {
PMLOGMSG(ZONE_WARN, (_T("%s: can't find parent '%s'\r\n"),
pszFname, pdiParent->pszName));
dwStatus = ERROR_INVALID_PARAMETER;
} else if(pdsParent->pParent != NULL) {
PMLOGMSG(ZONE_WARN, (_T("%s: parent '%s' can't also be a child\r\n"),
pszFname, pdsParent->pszName));
}
}
}
}
// if parameters were ok, proceed
if(dwStatus == ERROR_SUCCESS) {
// create and/or initialize the new device
AddDevice(pdiChild->pGuid, pdiChild->pszName, pdsParent, pCaps);
// get the return value
pdsChild = DeviceStateFindList(pdlChild, pdiChild->pszName);
if(pdsChild != NULL) {
// we only want the pointer value for now
DeviceStateDecRef(pdsChild);
} else {
// couldn't create the child device for some reason
dwStatus = ERROR_GEN_FAILURE;
}
}
// release resources
if(pdsParent != NULL) DeviceStateDecRef(pdsParent);
if(pdiParent != NULL) DeviceIdDestroy(pdiParent);
if(pdiChild != NULL) DeviceIdDestroy(pdiChild);
PMLOGMSG((dwStatus != ERROR_SUCCESS && ZONE_WARN) || ZONE_API,
(_T("%s: returning 0x%08x, status is %d\r\n"), pszFname, pdsChild,
dwStatus));
SetLastError(dwStatus);
return (HANDLE) pdsChild;
}
// This routine releases a power relationship that was created with
// PmRegisterPowerRelationship(). It returns
// ERROR_SUCCESS - relationship removed
// ERROR_INVALID_PARAMETER - bad handle
// Deregistering a power relationship has the side effect of deregistering
// the child device with the PM. Note that if the child exits while
// the relationship is outstanding, the caller will get ERROR_INVALID_PARAMETER
// when they attempt to release the relationship handle.
EXTERN_C DWORD WINAPI
PmReleasePowerRelationship(HANDLE h)
{
PDEVICE_STATE pds = (PDEVICE_STATE) h;
DWORD dwStatus = ERROR_INVALID_PARAMETER;
SETFNAME(_T("PmReleasePowerRelationship"));
PMLOGMSG(ZONE_API, (_T("%s: releasing 0x%08x\r\n"), pszFname, h));
// make sure that this pointer is a child node with a parent
if(pds != NULL) {
BOOL fExists = CheckDevicePointer(pds); // increments refcnt if TRUE
if(fExists) {
// delete the device
PREFAST_DEBUGCHK(pds->pListHead != NULL);
RemoveDevice(pds->pListHead->pGuid, pds->pszName);
// done with the pointer
DeviceStateDecRef(pds);
// return a good status
dwStatus = ERROR_SUCCESS;
}
}
PMLOGMSG(ZONE_API || (dwStatus != ERROR_SUCCESS && ZONE_WARN), (_T("%s: returning %d\r\n"),
pszFname, dwStatus));
return dwStatus;
}
| [
"ruslan.sirota@micronet-inc.com"
] | ruslan.sirota@micronet-inc.com |
2ce6f67ba7f336772b326ad9853252225a43a99a | 5bb7cf6f6f38e8a96ef5d522d26cf78c7c097c41 | /src/engine/server/library/serverGame/src/shared/command/CommandQueue.cpp | d581b8aeb5090b282605f42ba1df8338eab51244 | [] | no_license | hackerlank/SWG_Client_Next_Main | 1c88015af11bd42c662a7d7c4fe0807924f4077a | d737257b8fc28f7ad4d8d02113e7662682187194 | refs/heads/master | 2021-01-12T06:25:56.627527 | 2016-06-01T19:32:59 | 2016-06-01T19:32:59 | 77,359,203 | 6 | 4 | null | 2016-12-26T05:09:07 | 2016-12-26T05:09:06 | null | UTF-8 | C++ | false | false | 54,330 | cpp | // ======================================================================
//
// CommandQueue.cpp
//
// Copyright 2002 Sony Online Entertainment
//
// ======================================================================
#include "serverGame/FirstServerGame.h"
#include "serverGame/CommandQueue.h"
#include "UnicodeUtils.h"
#include "serverGame/Chat.h"
#include "serverGame/ConfigServerGame.h"
#include "serverGame/CreatureController.h"
#include "serverGame/CreatureObject.h"
#include "serverGame/NameManager.h"
#include "serverGame/PlayerObject.h"
#include "serverGame/ServerSecureTrade.h"
#include "serverGame/WeaponObject.h"
#include "serverScript/GameScriptObject.h"
#include "serverScript/ScriptParameters.h"
#include "serverUtility/ServerClock.h"
#include "sharedFoundation/Clock.h"
#include "sharedFoundation/Crc.h"
#include "sharedFoundation/FormattedString.h"
#include "sharedFoundation/GameControllerMessage.h"
#include "sharedGame/Command.h"
#include "sharedGame/CommandTable.h"
#include "sharedLog/Log.h"
#include "sharedNetworkMessages/GenericValueTypeMessage.h"
#include "sharedNetworkMessages/MessageQueueCommandQueueRemove.h"
#include "sharedNetworkMessages/MessageQueueCommandTimer.h"
#include "sharedNetworkMessages/MessageQueueGenericValueType.h"
#include "sharedObject/NetworkIdManager.h"
// --------------------------------------------------------------------------
namespace CommandQueueNamespace
{
/**
* @brief whether or not to produce debug logging
*/
#ifdef _DEBUG
const bool cs_debug = false;
#endif
/**
* @brief used to assign sequence Ids to server-generated commands
* that need to be replicated on the client.
*/
const uint32 cs_sequenceStart = 0x40000000;
/**
* @brief the maximum number of combat commands that are allowed in
* the queue at any given time.
*/
const uint32 cs_maxQueuedCombatCommands = 2;
/**
* @brief the number of seconds in a real-time day.
*
* This value is used for sanity checking
* @see setCommandTimerValue
*/
const float cs_secondsPerDay = 86400.f;
/**
* @brief the current time is cached in this class variable.
*
* this is used to reduce the number of calls to Clock::getCurrentTime().
* note it may not be appropriate to use this value in every
* place in the code since there's guarantee that it's accurate from
* every entry point in script.
*
* @see Clock::getCurrentTime
*/
double s_currentTime = 0.f;
}
using namespace CommandQueueNamespace;
// --------------------------------------------------------------------------
CommandQueue::CommandQueue(ServerObject & owner) :
Property(getClassPropertyId(), owner),
m_status (Command::CEC_Success),
m_statusDetail (0),
m_state ( State_Waiting ),
m_nextEventTime ( 0.f ),
m_queue ( ),
m_cooldowns ( ),
m_commandTimes ( TimerClass_MAX ),
m_combatCount ( 0 ),
m_eventStartTime ( 0.0 ),
m_logCommandEnqueue (false)
{
}
// ----------------------------------------------------------------------
PropertyId CommandQueue::getClassPropertyId()
{
return PROPERTY_HASH(CommandQueue, 889825674);
}
// ----------------------------------------------------------------------
bool CommandQueue::isFull() const
{
// is it empty?
if ( m_combatCount.get() == 0 )
{
return false;
}
// is it at the max?
if ( m_combatCount.get() >= cs_maxQueuedCombatCommands )
{
return true;
}
// test to see if the current command is waiting on a cooldown. we're considered
// full if we're waiting on a cooldown timer
if ( m_state.get() == State_Waiting && !m_queue.empty() )
{
const CommandQueueEntry &entry = *(m_queue.begin());
if ( (getCooldownTimeLeft( entry.m_command->m_coolGroup ) > 0.f) ||
(getCooldownTimeLeft( entry.m_command->m_coolGroup2) > 0.f) )
{
return true;
}
}
return false;
}
// ----------------------------------------------------------------------
void CommandQueue::enqueue(Command const &command, NetworkId const &targetId, Unicode::String const ¶ms, uint32 sequenceId, bool clearable, Command::Priority priority)
{
DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::enqueue(%s, %s, %s, %d, %d, %d)\n",
Clock::getCurrentTime(),
command.m_commandName.c_str(),
targetId.getValueString().c_str(),
Unicode::wideToNarrow(params).c_str(),
static_cast<int>(sequenceId),
clearable ? 1 : 0,
static_cast<int>(priority) ));
// make sure the cooldown timer value is initialized if it's not in the map
if(static_cast<int>(command.m_coolGroup) != -1)
{
if ( m_cooldowns.find( command.m_coolGroup ) == m_cooldowns.end() )
{
m_cooldowns.set( command.m_coolGroup, std::make_pair( 0.f, 0.f ) );
}
}
if(static_cast<int>(command.m_coolGroup2) != -1)
{
if ( m_cooldowns.find( command.m_coolGroup2 ) == m_cooldowns.end() )
{
m_cooldowns.set( command.m_coolGroup2, std::make_pair( 0.f, 0.f ) );
}
}
if ( priority == Command::CP_Default )
{
priority = command.m_defaultPriority;
}
//
// execute immediate commands imemdiately
//
if ( priority == Command::CP_Immediate )
{
Command::ErrorCode status = Command::CEC_Success;
int statusDetail = 0;
executeCommand(command, targetId, params, status, statusDetail, false);
notifyClientOfCommandRemoval(sequenceId, 0.0f, status, statusDetail);
}
else
{
if ( command.m_addToCombatQueue && isFull() )
{
// we do special things if the command queue is full or the current command is waiting on a cooldown
// timer of combat actions and the player tries to add another
// combat action!
// look in the queue for a command to replace this with
for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); )
{
EntryList::iterator j = it++;
// if there's a command warming up or executing then we can skip the first command in the queue
if ( m_state.get() != State_Waiting && j == m_queue.begin() )
{
continue;
}
const CommandQueueEntry &entry = *j;
// test to see of this command is a combat command
if ( entry.m_command->m_addToCombatQueue )
{
// remove command from queue
m_queue.erase( j );
// we want to end this loop
it = m_queue.end();
}
}
}
// create the command queue entry object
const CommandQueueEntry entry( command, targetId, params, sequenceId, clearable, priority, false );
m_queue.push( entry );
if ( command.m_addToCombatQueue )
{
m_combatCount = m_combatCount.get() + 1;
}
// debug - /spewCommandQueue available from console
if (m_logCommandEnqueue)
spew();
// if there's only one thing in the command queue ,
// then its okay to start execution immediately.
if ( ( m_queue.size() == 1 ) )
{
executeCommandQueue();
}
}
}
// ----------------------------------------------------------------------
void CommandQueue::remove(uint32 sequenceId)
{
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::remove(0x%08x)\n", (int)sequenceId ) );
if ( sequenceId == 0 )
{
// this would occur as a command from the client to cancel all pending combat actions
// as a result of the player hitting ESC
clearPendingCombatCommands();
}
else
{
// sometimes the game server wants to remove a specific command from the queue
// iterate over each item in the queue
for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); /* no action */ )
{
EntryList::iterator j = it++;
if ( ( j != m_queue.begin() ) || ( m_state.get() != State_Execute ) ) // <- don't cancel an executing command
{
const CommandQueueEntry &entry = *j;
if ( entry.m_sequenceId == sequenceId )
{
if ( j == m_queue.begin() )
{
m_nextEventTime = 0;
m_state = State_Waiting;
}
handleEntryRemoved(entry );
m_queue.erase( j );
// force this loop to terminate, since sequenceIds must be unique
// there's no way that if we removed a matching sequenceId that
// there are any more of them in the command queue
it = m_queue.end();
}
}
}
}
}
// ----------------------------------------------------------------------
void CommandQueue::update(float time)
{
PROFILER_AUTO_BLOCK_DEFINE("CommandQueue::update");
executeCommandQueue();
}
void CommandQueue::executeCommandQueue()
{
// cache the current time, so that we don't have to hit the getCurrentTime() method every time
s_currentTime = Clock::getCurrentTime();
//
// iterate through each command in the queue
//
while ( !m_queue.empty() )
{
CommandQueueEntry &entry = *(m_queue.begin());
// try to recover from having a null command
// maybe this should result in a fatal error?
if ( entry.m_command == 0 )
{
WARNING( true, ( "executeCommandQueue: entry.m_command was NULL! WTF?\n" ) );
m_queue.pop();
m_state = State_Waiting;
m_nextEventTime = 0.f;
continue;
}
// check the cooldown timer for this command's group
const unsigned int cooldownGroup = entry.m_command->m_coolGroup;
const unsigned int cooldownGroup2 = entry.m_command->m_coolGroup2;
// if this group is still cooling down, we need to break
// out of this loop and go do something else
if(static_cast<int>(cooldownGroup) != -1)
{
float coolTimeLeft = getCooldownTimeLeft( cooldownGroup );
if ( coolTimeLeft > FLT_EPSILON )
{
DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::executeCommandQueue(): waiting on cooldown group 0x%u: %f seconds left!\n", s_currentTime, cooldownGroup, coolTimeLeft ) );
break;
}
}
if(static_cast<int>(cooldownGroup2) != -1)
{
float coolTimeLeft2 = getCooldownTimeLeft( cooldownGroup2 );
if ( coolTimeLeft2 > FLT_EPSILON )
{
DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::executeCommandQueue(): waiting on cooldown group 2 0x%u: %f seconds left!\n", s_currentTime, cooldownGroup2, coolTimeLeft2 ) );
break;
}
}
// if we need to wait more time before switching states, we should
// just update the timer and leave now.
if ( m_nextEventTime.get() > s_currentTime )
{
DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::executeCommandQueue(): waiting on state %s: %f seconds left!\n",
s_currentTime,
getStateAsString((State) m_state.get() ),
m_nextEventTime.get() - s_currentTime ) );
break;
}
switchState();
switch ( m_state.get() )
{
case State_Waiting:
{
// don't call cancelCurrentCommand() here, because that method jacks with the command timer
// so we do the work manually
// NOTE RHanz:
// this is the one place in this class that we're not calling
// handleEntryRemoved when we're getting rid of an entry.
// It was explicitly removed... if there seems to be a problem
// with entries not being removed, this might be the culprit.
// Leaving for the time being as it was explicitly removed.
// NOTE SWyckoff:
// Turns out that there were problems with not calling
// handleEntryRemoved here that would cause the client to
// trigger a cool down even if the command failed. Putting it
// back in now.
// This pop removes commands that were executed last frame and
// need to be taken off the queue
// switch state might have removed elements from the queue and invalidated entry
// so we can't assume that we're still safe
if(!m_queue.empty() && (&(*(m_queue.begin())) == &entry) && m_queue.begin()->m_command != NULL)
{
handleEntryRemoved(*(m_queue.begin()), true);
m_queue.pop();
}
break;
}
case State_Warmup:
{
// do something in script
bool result = doWarmupTrigger(entry );
if ( result == false )
{
cancelCurrentCommand();
}
else
{
notifyClient();
}
}
break;
case State_Execute:
{
// The matching m_queue.pop() for this doExecute is in the next frame's State_Waiting
doExecute(entry );
}
break;
default:
FATAL( true, ( "command queue is in an invalid state. value=%d", (int)m_state.get() ) );
break;
}
}
}
// ----------------------------------------------------------------------
void CommandQueue::doExecute(const CommandQueueEntry &entry )
{
// execute command here
m_status = Command::CEC_Success;
m_statusDetail = 0;
// push the command on the stack
m_commandStack.push( &entry );
executeCommand( *entry.m_command, entry.m_targetId, entry.m_params, m_status, m_statusDetail, true );
FATAL( m_commandStack.empty(), ( "the command stack was empty! something is horribly wrong with the command queue!" ) );
// pop
m_commandStack.pop();
// check to see if the command was not removed from the queue
// or if the command failed
if ( !m_queue.empty() && (*(m_queue.begin())).m_sequenceId == entry.m_sequenceId && m_status == Command::CEC_Success )
{
// after executing the command, send execute and cooldown times to the client
notifyClient();
}
}
// ----------------------------------------------------------------------
void CommandQueue::updateClient(TimerClass timerClass )
{
CreatureObject * const creatureOwner = getServerOwner().asCreatureObject();
if ( (creatureOwner == NULL)
|| !creatureOwner->getClient())
{
return;
}
//
// grab the command that's currently working
//
if ( m_queue.empty() )
return;
const CommandQueueEntry &entry = *(m_queue.begin());
if ( entry.m_command == 0 ) // woah that's bad news!
{
WARNING( true, ( "CommandQueue::updateClient(): command was NULL!\n" ) );
return;
}
// create a message
MessageQueueCommandTimer *msg = new MessageQueueCommandTimer(
entry.m_sequenceId,
entry.m_command->m_coolGroup,
entry.m_command->m_coolGroup2,
Crc::normalizeAndCalculate(entry.m_command->m_commandName.c_str()) );
float currentTimer = 0.f;
// figure out what to put in the message based on our current state
if ( ( timerClass == TimerClass_Warmup && m_state.get() == State_Warmup ) || ( timerClass == TimerClass_Execute && m_state.get() == State_Execute ) )
{
currentTimer = static_cast< float > ( s_currentTime - m_eventStartTime.get() );
}
switch ( timerClass )
{
case TimerClass_Warmup:
msg->setCurrentTime( MessageQueueCommandTimer::F_warmup, currentTimer );
msg->setMaxTime ( MessageQueueCommandTimer::F_warmup, m_commandTimes[ TimerClass_Warmup ] );
break;
case TimerClass_Execute:
msg->setCurrentTime( MessageQueueCommandTimer::F_execute, currentTimer );
msg->setMaxTime ( MessageQueueCommandTimer::F_execute, m_commandTimes[ TimerClass_Execute ] );
break;
case TimerClass_Cooldown:
msg->setCurrentTime( MessageQueueCommandTimer::F_cooldown, currentTimer );
msg->setMaxTime ( MessageQueueCommandTimer::F_cooldown, m_commandTimes[ TimerClass_Cooldown ] );
if(static_cast<int>(entry.m_command->m_coolGroup2) != -1)
{
msg->setCurrentTime( MessageQueueCommandTimer::F_cooldown2, currentTimer );
msg->setMaxTime ( MessageQueueCommandTimer::F_cooldown2, m_commandTimes[ TimerClass_Cooldown2] );
}
break;
case TimerClass_Cooldown2:
DEBUG_WARNING(true, ("MessageQueueCommandTimer: updateClient; don't update cooldown 2 timer directly, please"));
break;
default:
break;
}
// send message
creatureOwner->getController()->appendMessage(
static_cast< int >( CM_commandTimer ),
0.0f,
msg,
GameControllerMessageFlags::SEND |
GameControllerMessageFlags::RELIABLE |
GameControllerMessageFlags::DEST_AUTH_CLIENT );
}
// ----------------------------------------------------------------------
void CommandQueue::notifyClient()
{
CreatureObject * const creatureOwner = getServerOwner().asCreatureObject();
if ( (creatureOwner == NULL)
|| !creatureOwner->getClient())
{
return;
}
if ( m_queue.empty() )
{
WARNING( true, ( "CommandQueue::notifyClient(): queue is empty!\n" ) );
return;
}
const CommandQueueEntry &entry = *(m_queue.begin());
if ( entry.m_command == 0 )
{
WARNING( true, ( "CommandQueue::notifyClient(): command was NULL!\n" ) );
return;
}
MessageQueueCommandTimer *msg = new MessageQueueCommandTimer( entry.m_sequenceId, entry.m_command->m_coolGroup,
entry.m_command->m_coolGroup2,
Crc::normalizeAndCalculate(entry.m_command->m_commandName.c_str()) );
DEBUG_REPORT_LOG( cs_debug && creatureOwner->getClient(), ( "%f: CommandQueue::notifyClient() [%f] warmup=%f execute=%f cooldown=%f cooldown2=%f\n",
s_currentTime,
s_currentTime - m_eventStartTime.get(),
m_commandTimes[ TimerClass_Warmup ],
m_commandTimes[ TimerClass_Execute ],
m_commandTimes[ TimerClass_Cooldown ],
m_commandTimes[ TimerClass_Cooldown2 ]) );
switch ( m_state.get() )
{
case State_Warmup:
msg->setCurrentTime( MessageQueueCommandTimer::F_warmup, static_cast< float >( s_currentTime - m_eventStartTime.get() ) );
msg->setMaxTime ( MessageQueueCommandTimer::F_warmup, m_commandTimes[ TimerClass_Warmup ] );
break;
case State_Execute:
msg->setCurrentTime( MessageQueueCommandTimer::F_execute, static_cast< float >( s_currentTime - m_eventStartTime.get() ) );
msg->setMaxTime ( MessageQueueCommandTimer::F_execute, m_commandTimes[ TimerClass_Execute ] );
msg->setCurrentTime( MessageQueueCommandTimer::F_cooldown, 0.f );
msg->setMaxTime ( MessageQueueCommandTimer::F_cooldown, m_commandTimes[ TimerClass_Cooldown ] );
msg->setCurrentTime( MessageQueueCommandTimer::F_cooldown2, 0.f );
msg->setMaxTime ( MessageQueueCommandTimer::F_cooldown2, m_commandTimes[ TimerClass_Cooldown2 ] );
break;
default:
break;
}
creatureOwner->getController()->appendMessage(
static_cast< int >( CM_commandTimer ),
0.0f,
msg,
GameControllerMessageFlags::SEND |
GameControllerMessageFlags::RELIABLE |
GameControllerMessageFlags::DEST_AUTH_CLIENT );
}
// ----------------------------------------------------------------------
bool CommandQueue::doWarmupTrigger(const CommandQueueEntry &entry )
{
bool result = false;
// make sure we could actually execute this command
m_status = Command::CEC_Success;
m_statusDetail = 0;
CreatureObject * const creatureOwner = getServerOwner().asCreatureObject();
if (creatureOwner != NULL)
{
creatureOwner->doWarmupChecks( *entry.m_command, entry.m_targetId, entry.m_params, m_status, m_statusDetail );
// if everything is okay, start the warmup trigger
if ( m_status == Command::CEC_Success )
{
FATAL( entry.m_command == 0, ( "entry had a null command\n" ) );
std::vector<float> timeValues;
timeValues.push_back( entry.m_command->m_warmTime );
timeValues.push_back( entry.m_command->m_execTime );
timeValues.push_back( getCooldownTime(*entry.m_command) );
timeValues.push_back( entry.m_command->m_coolTime2 );
ScriptParams params;
std::string entryParams( Unicode::wideToNarrow( entry.m_params ) );
params.addParam( entry.m_command->m_commandName.c_str() );
params.addParam( (int)entry.m_command->m_coolGroup );
params.addParam( (int)entry.m_command->m_coolGroup2 );
params.addParam( timeValues );
params.addParam( entryParams.c_str() );
params.addParam( entry.m_targetId );
result = SCRIPT_OVERRIDE != creatureOwner->getScriptObject()->trigAllScripts( Scripting::TRIG_BEGIN_WARMUP, params );
}
}
return result;
}
// ----------------------------------------------------------------------
uint32 CommandQueue::getCurrentCommand() const
{
if ( m_queue.empty() )
{
return 0;
}
const CommandQueueEntry &entry = *(m_queue.begin());
if ( entry.m_command == 0 )
{
WARNING( true, ( "CommandQueue::getCurrentCommand(): command was NULL!\n" ) );
return 0;
}
return Crc::calculate( entry.m_command->m_commandName.c_str() );
}
// ----------------------------------------------------------------------
void CommandQueue::switchState()
{
if ( m_queue.empty() )
{
WARNING( true, ( "CommandQueue::switchState(): queue is empty!\n" ) );
return;
}
const CommandQueueEntry &entry = *(m_queue.begin());
if ( entry.m_command == 0 )
{
WARNING( true, ( "CommandQueue::switchState(): command was NULL!\n" ) );
return;
}
#if defined(COMMAND_QUEUE_ENTRY_LOGGING)
CommandQueueEntry const entryCopy = entry;
#endif
m_eventStartTime = s_currentTime;
const unsigned int savedQueueSize = m_queue.size();
switch ( m_state.get() )
{
case State_Waiting:
// set timing info for execute and cooldown timers
m_commandTimes.set( TimerClass_Execute, entry.m_command->m_execTime );
m_commandTimes.set( TimerClass_Cooldown, getCooldownTime(*entry.m_command) );
m_commandTimes.set( TimerClass_Cooldown2, entry.m_command->m_coolTime2 );
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): cooldown timer setting id=%lu time=%f id2=%lu time2=%f\n", entry.m_command->m_coolGroup, getCooldownTime(*entry.m_command),
entry.m_command->m_coolGroup2, entry.m_command->m_coolTime2) );
if ( entry.m_command->m_warmTime < FLT_EPSILON )
{
if( entry.m_command->m_execTime < FLT_EPSILON )
{
// skipping both warmup and execute if both the timers are 0
m_nextEventTime = s_currentTime;
doExecute(entry );
bool entryIsTopOfQueue = true;
if (!m_queue.empty())
{
entryIsTopOfQueue = &(*(m_queue.begin())) == &entry;
#if defined(COMMAND_QUEUE_ENTRY_LOGGING)
if (!entryIsTopOfQueue && m_queue.size() == savedQueueSize)
{
REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_INVALID: Entry does not match top of queue!\n"));
Object const * const target = NetworkIdManager::getObjectById(entryCopy.m_targetId);
bool const targetIsAuthoritative = target && target->isAuthoritative();
REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_COMMAND: commandName=[%s] commandHash=[%lu] owner=[%s][%s][%s] target=[%s][%s][%s] sequenceId=[%lu] params=[%s] clearable=[%s] priority=[%d]\n",
entryCopy.m_command ? entryCopy.m_command->m_commandName.c_str() : "NULL",
entryCopy.m_command ? entryCopy.m_command->m_commandHash : 0,
NameManager::getInstance().getPlayerName(getOwner().getNetworkId()).c_str(),
getOwner().getNetworkId().getValueString().c_str(),
getOwner().isAuthoritative() ? "auth" : "proxy",
NameManager::getInstance().getPlayerName(entryCopy.m_targetId).c_str(),
entryCopy.m_targetId.getValueString().c_str(),
targetIsAuthoritative ? "auth" : "proxy",
entryCopy.m_sequenceId,
Unicode::wideToNarrow(entryCopy.m_params).c_str(),
entryCopy.m_clearable ? "true" : "false",
entryCopy.m_priority)
);
REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: state=State_Waiting queueSize=%d\n", m_queue.size()));
EntryList::const_iterator itEntry = m_queue.begin();
for (; itEntry != m_queue.end(); ++itEntry)
{
REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: commandName=[%s]\n", itEntry->m_command ? itEntry->m_command->m_commandName.c_str() : "NULL"));
}
}
#endif
}
else
entryIsTopOfQueue = false;
//Check the size of the queue. If it has shrunk then it means the entry was popped off the queue by cancelCurrentCommand,
//most likely because the command failed. If this is the case, do not perform the following actions.
if (m_queue.size() == savedQueueSize && entryIsTopOfQueue)
{
m_state = State_Waiting;
// set the cooldown timer for this command group
m_cooldowns.set( entry.m_command->m_coolGroup, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown ] ) );
m_cooldowns.set( entry.m_command->m_coolGroup2, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown2 ] ) );
// if the cool down value is large enough, persist it across
// server restarts and character unloading and reloading from the DB
if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() )
{
persistCooldown( entry.m_command->m_coolGroup, static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) );
}
if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() )
{
persistCooldown( entry.m_command->m_coolGroup2, static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) );
}
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Waiting->Waiting all the way around : m_nextEventTime=%f m_commandTime=%f m_execTime=%f\n",
m_nextEventTime.get(),
m_commandTimes[ TimerClass_Execute ],
entry.m_command->m_execTime ) );
handleEntryRemoved(entry, true);
m_queue.pop();
}
}
else
{
// here we skip the warmup state if the default warmup timer is 0
m_state = State_Execute;
m_nextEventTime = s_currentTime + entry.m_command->m_execTime;
m_commandTimes.set( TimerClass_Warmup, 0.f );
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Waiting->Execute\n" ) );
}
}
else
{
// otherwise we set up the warmup time
m_state = State_Warmup;
// set the command time state
// m_commandTimes[ TimerClass_Warmup ] = entry.m_command->m_warmTime;
m_commandTimes.set( TimerClass_Warmup, entry.m_command->m_warmTime );
// update the next event time value
m_nextEventTime = s_currentTime + entry.m_command->m_warmTime;
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Waiting->Warmup\n" ) );
}
break;
case State_Warmup:
if(entry.m_command->m_execTime < FLT_EPSILON)
{
m_nextEventTime = s_currentTime;
doExecute(entry );
bool entryIsTopOfQueue = true;
if (!m_queue.empty())
{
entryIsTopOfQueue = &(*(m_queue.begin())) == &entry;
#if defined(COMMAND_QUEUE_ENTRY_LOGGING)
if (!entryIsTopOfQueue && m_queue.size() == savedQueueSize)
{
REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_INVALID: Entry does not match top of queue!\n"));
Object const * const target = NetworkIdManager::getObjectById(entryCopy.m_targetId);
bool const targetIsAuthoritative = target && target->isAuthoritative();
REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_COMMAND: commandName=[%s] commandHash=[%lu] owner=[%s][%s][%s] target=[%s][%s][%s] sequenceId=[%lu] params=[%s] clearable=[%s] priority=[%d]\n",
entryCopy.m_command ? entryCopy.m_command->m_commandName.c_str() : "NULL",
entryCopy.m_command ? entryCopy.m_command->m_commandHash : 0,
NameManager::getInstance().getPlayerName(getOwner().getNetworkId()).c_str(),
getOwner().getNetworkId().getValueString().c_str(),
getOwner().isAuthoritative() ? "auth" : "proxy",
NameManager::getInstance().getPlayerName(entryCopy.m_targetId).c_str(),
entryCopy.m_targetId.getValueString().c_str(),
targetIsAuthoritative ? "auth" : "proxy",
entryCopy.m_sequenceId,
Unicode::wideToNarrow(entryCopy.m_params).c_str(),
entryCopy.m_clearable ? "true" : "false",
entryCopy.m_priority)
);
REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: state=State_Warmup queueSize=%d\n", m_queue.size()));
EntryList::const_iterator itEntry = m_queue.begin();
for (; itEntry != m_queue.end(); ++itEntry)
{
REPORT_LOG(true, ("CommandQueue::switchState():QUEUE_ENTRY_QUEUE: commandName=[%s]\n", itEntry->m_command ? itEntry->m_command->m_commandName.c_str() : "NULL"));
}
}
#endif
}
else
entryIsTopOfQueue = false;
//Check the size of the queue. If it has shrunk then it means the entry was popped off the queue by cancelCurrentCommand,
//most likely because the command failed. If this is the case, do not perform the following actions.
if (m_queue.size() == savedQueueSize && entryIsTopOfQueue)
{
m_state = State_Waiting;
// set the cooldown timer for this command group
m_cooldowns.set( entry.m_command->m_coolGroup, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown ] ) );
m_cooldowns.set( entry.m_command->m_coolGroup2, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown2 ] ) );
// if the cool down value is large enough, persist it across
// server restarts and character unloading and reloading from the DB
if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() )
{
persistCooldown( entry.m_command->m_coolGroup, static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) );
}
if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() )
{
persistCooldown( entry.m_command->m_coolGroup2, static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) );
}
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Warmup->Waiting m_nextEventTime=%f m_commandTime=%f m_execTime=%f\n",
m_nextEventTime.get(),
m_commandTimes[ TimerClass_Execute ],
entry.m_command->m_execTime ) );
}
}
else
{
m_state = State_Execute;
m_nextEventTime = s_currentTime + entry.m_command->m_execTime;
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Warmup->Execute m_nextEventTime=%f m_commandTime=%f m_execTime=%f\n",
m_nextEventTime.get(),
m_commandTimes[ TimerClass_Execute ],
entry.m_command->m_execTime ) );
}
break;
case State_Execute:
m_state = State_Waiting;
// set the cooldown timer for this command group
m_cooldowns.set( entry.m_command->m_coolGroup, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown ] ) );
m_cooldowns.set( entry.m_command->m_coolGroup2, std::make_pair( s_currentTime, s_currentTime + m_commandTimes[ TimerClass_Cooldown2 ] ) );
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::switchState(): Execute->%s\n", getStateAsString( (State)m_state.get() ) ) );
// if the cool down value is large enough, persist it across
// server restarts and character unloading and reloading from the DB
if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() )
{
persistCooldown( entry.m_command->m_coolGroup, static_cast<int>( m_commandTimes[ TimerClass_Cooldown ] ) );
}
if ( static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) >= ConfigServerGame::getCoolDownPersistThresholdSeconds() )
{
persistCooldown( entry.m_command->m_coolGroup2, static_cast<int>( m_commandTimes[ TimerClass_Cooldown2 ] ) );
}
break;
default:
WARNING( true, ( "CommandQueue::switchState(): queue is in an invalid state!\n" ) );
break;
}
}
// ----------------------------------------------------------------------
void CommandQueue::clearPendingCombatCommands()
{
DEBUG_REPORT_LOG( cs_debug, ( "%s: attempting to cancel pending commands (queueSize=%d)\n", Unicode::wideToNarrow( getServerOwner().getObjectName() ).c_str(), m_queue.size() ) );
for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); )
{
EntryList::iterator j = it++;
const CommandQueueEntry &entry = *j;
// if ( command is combat command )
// {
// if ( ( command is at the top and is not executing ) or ( command is not at the top )
// {
// remove command
// }
// }
if ( entry.m_command->m_addToCombatQueue && ( j != m_queue.begin() || m_state.get() != State_Execute ) )
{
handleEntryRemoved(entry );
if ( j == m_queue.begin() )
{
cancelCurrentCommand();
}
else
{
m_queue.erase( j );
}
}
}
}
// ----------------------------------------------------------------------
void CommandQueue::persistCooldown(uint32 cooldownGroupCrc, int cooldownTimeSeconds)
{
if (cooldownTimeSeconds <= 0)
return;
CreatureObject * const creatureOwner = getServerOwner().asCreatureObject();
if (!creatureOwner)
return;
int const currentGameTime = static_cast<int>(ServerClock::getInstance().getGameTimeSeconds());
char buffer[256];
snprintf(buffer, sizeof(buffer)-1, "commandCooldown.beginTime.%lu", cooldownGroupCrc);
buffer[sizeof(buffer)-1] = '\0';
std::string const coolDownBeginTime = buffer;
snprintf(buffer, sizeof(buffer)-1, "commandCooldown.endTime.%lu", cooldownGroupCrc);
buffer[sizeof(buffer)-1] = '\0';
std::string const coolDownEndTime = buffer;
IGNORE_RETURN(creatureOwner->setObjVarItem(coolDownBeginTime, currentGameTime));
IGNORE_RETURN(creatureOwner->setObjVarItem(coolDownEndTime, (currentGameTime + cooldownTimeSeconds)));
}
// ----------------------------------------------------------------------
void CommandQueue::depersistCooldown()
{
CreatureObject * const creatureOwner = getServerOwner().asCreatureObject();
if (!creatureOwner)
return;
DynamicVariableList const & objvars = creatureOwner->getObjVars();
std::map<uint32, std::pair<int, int> > commandCooldownTimers;
for (DynamicVariableList::MapType::const_iterator iterObjVar = objvars.begin(); iterObjVar != objvars.end(); ++iterObjVar)
{
if (iterObjVar->first.find("commandCooldown.beginTime.") == 0)
{
uint32 cooldownGroupCrc = 0;
if (1 == sscanf(iterObjVar->first.c_str(), "commandCooldown.beginTime.%lu", &cooldownGroupCrc))
{
int beginTime = 0;
if (iterObjVar->second.get(beginTime))
{
std::map<uint32, std::pair<int, int> >::iterator iterFind = commandCooldownTimers.find(cooldownGroupCrc);
if (iterFind == commandCooldownTimers.end())
{
commandCooldownTimers[cooldownGroupCrc] = std::make_pair(beginTime, 0);
}
else
{
iterFind->second.first = beginTime;
}
}
}
}
else if (iterObjVar->first.find("commandCooldown.endTime.") == 0)
{
uint32 cooldownGroupCrc = 0;
if (1 == sscanf(iterObjVar->first.c_str(), "commandCooldown.endTime.%lu", &cooldownGroupCrc))
{
int endTime = 0;
if (iterObjVar->second.get(endTime))
{
std::map<uint32, std::pair<int, int> >::iterator iterFind = commandCooldownTimers.find(cooldownGroupCrc);
if (iterFind == commandCooldownTimers.end())
{
commandCooldownTimers[cooldownGroupCrc] = std::make_pair(0, endTime);
}
else
{
iterFind->second.second = endTime;
}
}
}
}
}
char buffer[256];
int const currentGameTime = static_cast<int>(ServerClock::getInstance().getGameTimeSeconds());
double const currentTime = Clock::getCurrentTime();
for (std::map<uint32, std::pair<int, int> >::const_iterator iterCooldown = commandCooldownTimers.begin(); iterCooldown != commandCooldownTimers.end(); ++iterCooldown)
{
// update the command queue with any unexpired cooldowns
if ((iterCooldown->second.first > 0) && (iterCooldown->second.second > 0) && (iterCooldown->second.first <= currentGameTime) && (currentGameTime < iterCooldown->second.second))
{
m_cooldowns.set(iterCooldown->first, std::make_pair(currentTime - static_cast<double>(currentGameTime - iterCooldown->second.first), currentTime + static_cast<double>(iterCooldown->second.second - currentGameTime)));
}
else
{
// cleanup the objvars for any expired/invalid cooldowns
snprintf(buffer, sizeof(buffer)-1, "commandCooldown.beginTime.%lu", iterCooldown->first);
buffer[sizeof(buffer)-1] = '\0';
creatureOwner->removeObjVarItem(buffer);
snprintf(buffer, sizeof(buffer)-1, "commandCooldown.endTime.%lu", iterCooldown->first);
buffer[sizeof(buffer)-1] = '\0';
creatureOwner->removeObjVarItem(buffer);
}
}
}
// ----------------------------------------------------------------------
bool CommandQueue::hasCommandFromGroup(uint32 groupHash) const
{
for (EntryList::const_iterator i = m_queue.begin(); i != m_queue.end(); ++i)
if ((*i).m_command->m_commandGroup == groupHash)
return true;
return false;
}
// ----------------------------------------------------------------------
void CommandQueue::clearCommandsFromGroup(uint32 groupHash, bool force)
{
// iterate over each command in the queue
for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); /* nil */ )
{
EntryList::iterator j = it++;
const CommandQueueEntry &entry = *j;
if ( entry.m_command->m_commandGroup == groupHash && ( force || entry.m_clearable ) )
{
// decrement the combat entry count if this is a combat command
// and update client
handleEntryRemoved(entry );
// if this is the top of the queue, we need to put the queue into a waiting state
if ( j == m_queue.begin() )
{
cancelCurrentCommand();
}
else
{
// remove item from queue
m_queue.erase( j );
}
}
}
}
// ----------------------------------------------------------------------
void CommandQueue::handleEntryRemoved(CommandQueueEntry const &entry, bool notifyClient)
{
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::handleEntryRemoved(%s, %d)\n", entry.m_command->m_commandName.c_str(), notifyClient ? 1 : 0 ) );
ServerObject const & serverOwner = getServerOwner();
if ( entry.m_command->m_addToCombatQueue && ( m_combatCount.get() > 0 ) )
{
m_combatCount = m_combatCount.get() - 1;
}
// If we have a sequenceId, then the owner's client is interested in
// hearing about the removal of that command.
if (serverOwner.isAuthoritative() && notifyClient)
{
notifyClientOfCommandRemoval(entry.m_sequenceId, 0.0f, m_status, m_statusDetail);
}
}
// ----------------------------------------------------------------------
void CommandQueue::notifyClientOfCommandRemoval(uint32 sequenceId, float waitTime, Command::ErrorCode status, int statusDetail)
{
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::notifyClientOfCommandRemoval(%d, %f, %d, %d)\n", static_cast<int>(sequenceId), waitTime, status, statusDetail ) );
CreatureObject * const creatureOwner = getServerOwner().asCreatureObject();
if ( (creatureOwner != NULL)
&& creatureOwner->getClient()
&& (sequenceId != 0))
{
WARNING(status < 0 || status >= Command::CEC_Max, ("CommandQueue::notifyClientOfCommandRemoval received invalid status %d", static_cast<int>(status)));
creatureOwner->getController()->appendMessage(
static_cast<int>(CM_commandQueueRemove),
0.0f,
new MessageQueueCommandQueueRemove(sequenceId, waitTime, static_cast<int>(status), statusDetail),
GameControllerMessageFlags::SEND |
GameControllerMessageFlags::RELIABLE |
GameControllerMessageFlags::DEST_AUTH_CLIENT);
}
}
// ----------------------------------------------------------------------
const char *CommandQueue::getStateAsString( State state )
{
static const char * states[] =
{
"waiting",
"warmup",
"execute",
"?unknown?"
};
if ( state > State_MAX )
{
state = State_MAX;
}
return states[ state ];
}
// ----------------------------------------------------------------------
bool CommandQueue::setCommandTimerValue(TimerClass timerClass, float newValue )
{
FATAL( timerClass >= (int)m_commandTimes.size(), ( "CommandQueue::setCommandTimerValue(): invalid timer class %d\n", timerClass ) );
FATAL( fabsf( newValue ) > cs_secondsPerDay, ( "tried to set a command timer outside allowed range. (value=%f)\n", newValue ) );
if ( m_state.get() == State_Waiting )
{
return false;
}
if ( ( timerClass == TimerClass_Warmup && m_state.get() == State_Warmup ) || ( timerClass == TimerClass_Execute && m_state.get() == State_Execute ) )
{
m_nextEventTime = m_eventStartTime.get() + newValue;
}
m_commandTimes.set( timerClass, newValue );
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::setCommandTimerValue() timerClass=%d m_nextEventTime=%f newValue=%f\n", timerClass, m_nextEventTime.get(), newValue ) );
updateClient(timerClass );
return true;
}
// ----------------------------------------------------------------------
void CommandQueue::cancelCurrentCommand()
{
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::cancelCurrentCommand()\n" ) );
WARNING( m_queue.empty(), ( "queue was empty.\n " ) );
if ( !m_queue.empty() )
{
const CommandQueueEntry &entry = *(m_queue.begin());
m_nextEventTime = 0.f;
m_status = Command::CEC_Cancelled;
m_state = State_Waiting;
handleEntryRemoved(entry, true);
m_queue.pop();
}
}
// ----------------------------------------------------------------------
CommandQueue::State CommandQueue::getCurrentCommandState() const
{
return (State)m_state.get();
}
// ----------------------------------------------------------------------
void CommandQueue::addToPackage(Archive::AutoDeltaByteStream &bs)
{
bs.addVariable(m_queue);
bs.addVariable(m_state);
bs.addVariable(m_nextEventTime);
bs.addVariable(m_combatCount);
bs.addVariable(m_eventStartTime);
bs.addVariable(m_cooldowns);
bs.addVariable(m_commandTimes);
}
// ----------------------------------------------------------------------
float CommandQueue::getCooldownTimeLeft( uint32 cooldownId ) const
{
CooldownMapType::const_iterator it = m_cooldowns.find( cooldownId );
float result = 0.f;
if ( it != m_cooldowns.end() )
{
result = static_cast< float > ( (*it).second.second - Clock::getCurrentTime() );
}
return result;
}
// ----------------------------------------------------------------------
float CommandQueue::getCooldownTimeLeft( const std::string &name ) const
{
return getCooldownTimeLeft( Crc::normalizeAndCalculate( name.c_str() ) );
}
//-----------------------------------------------------------------------
void CommandQueue::executeCommand(Command const &command, NetworkId const &targetId, Unicode::String const ¶ms, Command::ErrorCode &status, int &statusDetail, bool commandIsFromCommandQueue)
{
DEBUG_REPORT_LOG( cs_debug, ( "%f: CommandQueue::executeCommand(%s, %s, %s, %d, %d)\n",
Clock::getCurrentTime(),
command.m_commandName.c_str(),
targetId.getValueString().c_str(),
Unicode::wideToNarrow(params).c_str(),
status,
statusDetail));
status = Command::CEC_Success;
static bool s_tradeAllowedCommandsInit = false;
typedef stdvector<uint32>::fwd Uint32Vector;
static Uint32Vector s_tradeAllowedCommands;
if (!s_tradeAllowedCommandsInit)
{
s_tradeAllowedCommandsInit = true;
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("addFriend"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("addIgnore"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("closeContainer"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("combatSpam"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("find"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("gc"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("getAttributes"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("getAttributesBatch"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("getFriendList"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("getIgnoreList"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("groupChat"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("groupChat"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("gsay"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("gtell"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("guildsay"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("kneel"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("maskscent"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("meditate"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("newbiehelper"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("openContainer"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("prose"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("removeFriend"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("removeIgnore"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestBiography"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestCharacterMatch"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestDraftSlots"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestManfSchematicSlots"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("requestResourceWeights"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setMatchMakingCharacterId"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setMatchMakingPersonalId"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setMood"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setMoodInternal"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("setSpokenLanguage"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("sitServer"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("social"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("socialInternal"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("spatialChat"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("spatialChatInternal"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("stand"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("synchronizedUiListen"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("synchronizedUiStopListening"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("target"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("tip"));
s_tradeAllowedCommands.push_back (Crc::normalizeAndCalculate("waypoint"));
s_tradeAllowedCommands.push_back (CommandTable::getNullCommand().m_commandHash);
std::sort (s_tradeAllowedCommands.begin (), s_tradeAllowedCommands.end ());
}
CreatureObject * const creatureOwner = getServerOwner().asCreatureObject();
if (creatureOwner != NULL)
{
CreatureController * const creatureController = creatureOwner->getCreatureController();
if (creatureController && creatureController->getSecureTrade())
{
if (!std::binary_search (s_tradeAllowedCommands.begin (), s_tradeAllowedCommands.end (), command.m_commandHash))
{
LOG ("Command", ("CreatureObject [%s] trade canceled by [%s] command", creatureOwner->getNetworkId ().getValueString ().c_str (), command.m_commandName.c_str ()));
creatureController->getSecureTrade()->cancelTrade(*creatureOwner);
}
}
// posture and ability verification - don't execute the command
// if we're in a posture for which the command is not valid, or
// we do not have the ability required for the command (if any)
creatureOwner->doWarmupChecks( command, targetId, params, status, statusDetail );
if (status == Command::CEC_Success && command.m_godLevel > 0)
{
Client const *client = creatureOwner->getClient();
if (!client)
{
status = Command::CEC_GodLevel;
LOGU("CustomerService", ("Avatar:%s tried to execute command %s >%s with no client", PlayerObject::getAccountDescription(creatureOwner).c_str(), command.m_commandName.c_str(), targetId.getValueString().c_str()), params);
}
else if (client->getGodLevel() < command.m_godLevel)
{
status = Command::CEC_GodLevel;
LOGU("CustomerService", ("Avatar:%s doesn't have adequate level for command %s >%s", PlayerObject::getAccountDescription(creatureOwner).c_str(), command.m_commandName.c_str(), targetId.getValueString().c_str()), params);
}
else
{
LOGU("CustomerService", ("Avatar:%s has executed command %s >%s", PlayerObject::getAccountDescription(creatureOwner).c_str(), command.m_commandName.c_str(), targetId.getValueString().c_str()), params);
}
}
}
TangibleObject * const tangibleOwner = getServerOwner().asTangibleObject();
if (tangibleOwner != NULL)
{
// Really execute the command - swap targets if necessary, and call
// forceExecuteCommand (which will handle messaging if not authoritative)
if (status == Command::CEC_Success)
{
if (!command.m_callOnTarget)
{
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::executeCommand(): tangibleOwner->forceExecuteCommand(%s, %s, %s, %d)\n",
command.m_commandName.c_str(),
targetId.getValueString().c_str(),
Unicode::wideToNarrow(params).c_str(),
status));
tangibleOwner->forceExecuteCommand(command, targetId, params, status, commandIsFromCommandQueue);
}
else
{
TangibleObject * const tangibleTarget = TangibleObject::getTangibleObject(targetId);
if (tangibleTarget)
{
DEBUG_REPORT_LOG( cs_debug, ( "CommandQueue::executeCommand(): tangibleTarget->forceExecuteCommand(%s, %s, %s, %d)\n",
command.m_commandName.c_str(),
tangibleOwner->getNetworkId().getValueString().c_str(),
Unicode::wideToNarrow(params).c_str(),
status));
tangibleTarget->forceExecuteCommand(command, tangibleOwner->getNetworkId(), params, status, commandIsFromCommandQueue);
}
}
}
}
}
// ----------------------------------------------------------------------
CommandQueue * CommandQueue::getCommandQueue(Object & object)
{
Property * const property = object.getProperty(getClassPropertyId());
return (property != NULL) ? (static_cast<CommandQueue *>(property)) : NULL;
}
// ----------------------------------------------------------------------
ServerObject & CommandQueue::getServerOwner()
{
return *getOwner().asServerObject();
}
// ----------------------------------------------------------------------
ServerObject const & CommandQueue::getServerOwner() const
{
return *getOwner().asServerObject();
}
// ----------------------------------------------------------------------
float CommandQueue::getCooldownTime(Command const &command)
{
if(command.isPrimaryCommand())
{
CreatureObject * const creature = getServerOwner().asCreatureObject();
if(creature)
{
WeaponObject *weapon = creature->getCurrentWeapon();
if(weapon)
return weapon->getAttackTime();
}
}
return command.m_coolTime;
}
// ----------------------------------------------------------------------
void CommandQueue::resetCooldowns()
{
m_commandTimes.set( TimerClass_Cooldown, 0.0f );
updateClient( TimerClass_Cooldown );
for (CooldownMapType::const_iterator iterCooldown = m_cooldowns.begin(); iterCooldown != m_cooldowns.end(); ++iterCooldown)
{
//has not expired
if((*iterCooldown).second.second > (Clock::getCurrentTime() + FLT_EPSILON))
{
//Reset the end of the cooldown to be right now
m_cooldowns.set( (*iterCooldown).first, std::make_pair( (*iterCooldown).second.first, Clock::getCurrentTime() ) );
//notify client
MessageQueueCommandTimer *msg = new MessageQueueCommandTimer(
0,
(*iterCooldown).first,
-1,
0 );
msg->setCurrentTime(MessageQueueCommandTimer::F_cooldown, 1.0f);
msg->setMaxTime (MessageQueueCommandTimer::F_cooldown, 1.0f);
CreatureObject * const creature = getServerOwner().asCreatureObject();
if(creature)
{
creature->getController()->appendMessage(
static_cast< int >( CM_commandTimer ),
0.0f,
msg,
GameControllerMessageFlags::SEND |
GameControllerMessageFlags::RELIABLE |
GameControllerMessageFlags::DEST_AUTH_CLIENT);
}
}
}
}
// ----------------------------------------------------------------------
void CommandQueue::spew(std::string * output)
{
CreatureObject * const creature = getServerOwner().asCreatureObject();
if(creature)
{
FormattedString<1024> fsOutput;
char const * fsSprintfOutput;
double const currentTime = Clock::getCurrentTime();
fsSprintfOutput = fsOutput.sprintf("%s current time [%.10f], m_queue size [%d], m_cooldowns size [%d], m_combatCount [%u]", creature->getNetworkId().getValueString().c_str(), currentTime, m_queue.size(), m_cooldowns.size(), m_combatCount.get());
if (output)
{
*output += fsSprintfOutput;
*output += "\n";
}
else
{
LOG("CommandQueueSpew", ("%s", fsSprintfOutput));
}
for ( EntryList::iterator it = m_queue.begin(); it != m_queue.end(); )
{
EntryList::iterator j = it++;
const CommandQueueEntry &entry = *j;
fsSprintfOutput = fsOutput.sprintf("%s commandName [%s] hash[%lu] cd1[%lu] cd2[%lu]",
creature->getNetworkId().getValueString().c_str(),
entry.m_command->m_commandName.c_str(),
entry.m_command->m_commandHash,
entry.m_command->m_coolGroup,
entry.m_command->m_coolGroup2);
if (output)
{
*output += fsSprintfOutput;
*output += "\n";
}
else
{
LOG("CommandQueueSpew", ("%s", fsSprintfOutput));
}
}
for (CooldownMapType::const_iterator iterCooldown = m_cooldowns.begin(); iterCooldown != m_cooldowns.end(); ++iterCooldown)
{
fsSprintfOutput = fsOutput.sprintf("%s cooldown key [%lu] value1[%.10f] value2[%.10f] duration[%.10f] remaining[%.10f]",
creature->getNetworkId().getValueString().c_str(),
iterCooldown->first,
iterCooldown->second.first,
iterCooldown->second.second,
iterCooldown->second.second - iterCooldown->second.first,
iterCooldown->second.second - currentTime);
if (output)
{
*output += fsSprintfOutput;
*output += "\n";
}
else
{
LOG("CommandQueueSpew", ("%s", fsSprintfOutput));
}
}
fsSprintfOutput = fsOutput.sprintf("%s m_commandTimes Warmup[%.10f] Execute[%.10f] Cooldown[%.10f] Cooldown2[%.10f]",
creature->getNetworkId().getValueString().c_str(),
m_commandTimes[TimerClass_Warmup],
m_commandTimes[TimerClass_Execute],
m_commandTimes[TimerClass_Cooldown],
m_commandTimes[TimerClass_Cooldown2]);
if (output)
{
*output += fsSprintfOutput;
*output += "\n";
}
else
{
LOG("CommandQueueSpew", ("%s", fsSprintfOutput));
}
}
}
// ======================================================================
| [
"lightlordmh@hotmail.com"
] | lightlordmh@hotmail.com |
daba678609848f35e837db30825e75b51624993c | c05238c76e2d1dff1bca000c1893d49fef58c963 | /base/component/exception.cpp | 0856c004ba9022a43711920a6ff7109c1978ae79 | [] | no_license | firejh/server | 949d371223abbd6890e7b4171a55417fbac7bb23 | 3a5beaf0890db6975e24eebda2fb9029d7ef61f6 | refs/heads/master | 2021-06-18T04:54:44.251910 | 2017-07-06T06:04:43 | 2017-07-06T06:04:43 | 95,762,205 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,289 | cpp | #include "exception.h"
#include <iostream>
#include <sstream>
#include <string.h>
#include <stdlib.h>
namespace base{
namespace component{
ExceptionBase::ExceptionBase(const std::string& msg,
const std::string& file,
const std::string& func,
int32_t line,
int32_t sysErrno) noexcept
: m_msg(msg), m_file(file), m_func(func), m_line(line), m_sysErrno(sysErrno)
{
}
ExceptionBase::~ExceptionBase() noexcept
{
}
std::string ExceptionBase::exceptionName() const noexcept
{
return "ExceptionBase";
}
std::string ExceptionBase::msg() const noexcept
{
return m_msg;
}
const char* ExceptionBase::what() const noexcept
{
if (!m_what.empty())
return m_what.c_str();
if(m_sysErrno != 0)
m_what = format("[{execptionName}], msg:[{m_msg}], file:[{m_file}+{m_line}], fun:[{m_func}], errno:[{m_sysErrno} {strerr}]",
exceptionName(), m_msg, m_file, m_line, m_func, m_sysErrno, ::strerror(m_sysErrno));
else
m_what = format("[{execptionName}], msg:[{m_msg}], file:[{m_file}+{m_line}], fun:[{m_func}]",
exceptionName(), m_msg, m_file, m_line, m_func);
return m_what.c_str();
}
}}
| [
"centos@localhost.localdomain"
] | centos@localhost.localdomain |
8421bd189ced236256f3be76fdc339ae7bdbfc86 | 74af32d04639d5c442f0e94b425beb68a2544b3c | /LeetCode/Normal/1400-1499/1431.cpp | 228c14d475eea3e1b864489ef4375205c5454dc0 | [] | no_license | dlvguo/NoobOJCollection | 4e4bd570aa2744dfaa2924bacc34467a9eae8c9d | 596f6c578d18c7beebdb00fa3ce6d6d329647360 | refs/heads/master | 2023-05-01T07:42:33.479091 | 2023-04-20T11:09:15 | 2023-04-20T11:09:15 | 181,868,933 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | #include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<bool> kidsWithCandies(vector<int> &candies, int extraCandies)
{
int n = candies.size();
int maxCandies = *max_element(candies.begin(), candies.end());
vector<bool> ret;
for (int i = 0; i < n; ++i)
{
ret.push_back(candies[i] + extraCandies >= maxCandies);
}
return ret;
}
}; | [
"dlvguo@qq.com"
] | dlvguo@qq.com |
c6936387cf0bd8b26139ea46d938f1643fbf610a | 34e11b37fada3d5290509b50d1f9c312225f613b | /InsertionSort.cpp | 7d82977bfd96056b99248dd78d004f8d2b187551 | [] | no_license | MiladEsp/cpp-algorithms | 282ee498829ac0f048874f729a52aaaa16d9f6ec | f20ee6669d95b8ba3f87eeaa35c6fee7d39e985b | refs/heads/master | 2022-12-25T12:18:55.639870 | 2020-10-05T02:05:56 | 2020-10-05T02:05:56 | 295,762,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | cpp | #include <iostream>
#include <vector>
template <typename T>
void insertionSort(std::vector<T> &vec, bool ascending)
{
int i, j;
T key;
for (j = 1; j < vec.size(); j++)
{
key = vec[j];
i = j - 1;
if (ascending)
{
while (i >= 0 && vec[i] > key)
{
vec[i + 1] = vec[i];
i = i - 1;
}
}
else
{
while (i >= 0 && vec[i] < key)
{
vec[i + 1] = vec[i];
i = i - 1;
}
}
vec[i + 1] = key;
}
}
int main()
{
std::vector<int> vec{5, 2, 4, 7, 1, 3, 2, 6, -5, 10, 0};
insertionSort(vec, true);
for (auto item : vec)
{
std::cout << item << " ";
}
std::cout << std::endl;
/////////////////////////
std::vector<double> vec1{-2.3, 0.5, 1.6, -10.5, 13.69};
insertionSort(vec1, true);
for (auto item : vec1)
{
std::cout << item << " ";
}
std::cout << std::endl;
return 0;
} | [
"32962296+MiladEsp@users.noreply.github.com"
] | 32962296+MiladEsp@users.noreply.github.com |
e806a2fa13a3b535b0b1363fc49aa2bf0d7de57f | 16a022f0ff5c3dbe6e4e1009014e452c4af62e74 | /src/qt/mintingview.cpp | 9a227e8565e14d4cdc0edf4ff2b53823c3696911 | [
"MIT"
] | permissive | likecoin-script/novacoin | bc51b2d34cb224463f688402a7133a221c07236a | 3ee4915dfcd6f53516c9d649063c69ff1d61ca2e | refs/heads/master | 2021-01-17T11:42:00.846171 | 2014-11-29T23:47:31 | 2014-11-29T23:47:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,957 | cpp | #include "mintingview.h"
#include "mintingfilterproxy.h"
#include "transactionrecord.h"
#include "mintingtablemodel.h"
#include "walletmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "csvmodelwriter.h"
#include <QHBoxLayout>
#include <QHeaderView>
#include <QVBoxLayout>
#include <QTableView>
#include <QScrollBar>
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QMessageBox>
#include <QMenu>
MintingView::MintingView(QWidget *parent) :
QWidget(parent), model(0), mintingView(0)
{
QHBoxLayout *hlayout = new QHBoxLayout();
hlayout->setContentsMargins(0,0,0,0);
QString legendBoxStyle = "background-color: rgb(%1,%2,%3); border: 1px solid black;";
QLabel *youngColor = new QLabel(" ");
youngColor->setMaximumHeight(15);
youngColor->setMaximumWidth(10);
youngColor->setStyleSheet(legendBoxStyle.arg(COLOR_MINT_YOUNG.red()).arg(COLOR_MINT_YOUNG.green()).arg(COLOR_MINT_YOUNG.blue()));
QLabel *youngLegend = new QLabel(tr("transaction is too young"));
youngLegend->setContentsMargins(5,0,15,0);
QLabel *matureColor = new QLabel(" ");
matureColor->setMaximumHeight(15);
matureColor->setMaximumWidth(10);
matureColor->setStyleSheet(legendBoxStyle.arg(COLOR_MINT_MATURE.red()).arg(COLOR_MINT_MATURE.green()).arg(COLOR_MINT_MATURE.blue()));
QLabel *matureLegend = new QLabel(tr("transaction is mature"));
matureLegend->setContentsMargins(5,0,15,0);
QLabel *oldColor = new QLabel(" ");
oldColor->setMaximumHeight(15);
oldColor->setMaximumWidth(10);
oldColor->setStyleSheet(legendBoxStyle.arg(COLOR_MINT_OLD.red()).arg(COLOR_MINT_OLD.green()).arg(COLOR_MINT_OLD.blue()));
QLabel *oldLegend = new QLabel(tr("transaction has reached maximum probability"));
oldLegend->setContentsMargins(5,0,15,0);
QHBoxLayout *legendLayout = new QHBoxLayout();
legendLayout->setContentsMargins(10,10,0,0);
legendLayout->addWidget(youngColor);
legendLayout->addWidget(youngLegend);
legendLayout->addWidget(matureColor);
legendLayout->addWidget(matureLegend);
legendLayout->addWidget(oldColor);
legendLayout->addWidget(oldLegend);
legendLayout->insertStretch(-1);
QLabel *mintingLabel = new QLabel(tr("Display minting probability within : "));
mintingCombo = new QComboBox();
mintingCombo->addItem(tr("10 min"), Minting10min);
mintingCombo->addItem(tr("24 hours"), Minting1day);
mintingCombo->addItem(tr("7 days"), Minting7days);
mintingCombo->addItem(tr("30 days"), Minting30days);
mintingCombo->addItem(tr("60 days"), Minting60days);
mintingCombo->addItem(tr("90 days"), Minting90days);
mintingCombo->setFixedWidth(120);
hlayout->insertStretch(0);
hlayout->addWidget(mintingLabel);
hlayout->addWidget(mintingCombo);
QVBoxLayout *vlayout = new QVBoxLayout(this);
vlayout->setContentsMargins(0,0,0,0);
vlayout->setSpacing(0);
QTableView *view = new QTableView(this);
vlayout->addLayout(hlayout);
vlayout->addWidget(view);
vlayout->addLayout(legendLayout);
vlayout->setSpacing(0);
int width = view->verticalScrollBar()->sizeHint().width();
// Cover scroll bar width with spacing
#ifdef Q_WS_MAC
hlayout->addSpacing(width+2);
#else
hlayout->addSpacing(width);
#endif
// Always show scroll bar
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
view->setTabKeyNavigation(false);
view->setContextMenuPolicy(Qt::CustomContextMenu);
mintingView = view;
connect(mintingCombo, SIGNAL(activated(int)), this, SLOT(chooseMintingInterval(int)));
// Actions
QAction *copyTxIDAction = new QAction(tr("Copy transaction ID of input"), this);
QAction *copyAddressAction = new QAction(tr("Copy address of input"), this);
QAction *showHideAddressAction = new QAction(tr("Show/hide 'Address' column"), this);
QAction *showHideTxIDAction = new QAction(tr("Show/hide 'Transaction' column"), this);
contextMenu = new QMenu();
contextMenu->addAction(copyAddressAction);
contextMenu->addAction(copyTxIDAction);
contextMenu->addAction(showHideAddressAction);
contextMenu->addAction(showHideTxIDAction);
connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress()));
connect(copyTxIDAction, SIGNAL(triggered()), this, SLOT(copyTxID()));
connect(showHideAddressAction, SIGNAL(triggered()), this, SLOT(showHideAddress()));
connect(showHideTxIDAction, SIGNAL(triggered()), this, SLOT(showHideTxID()));
connect(view, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint)));
}
void MintingView::setModel(WalletModel *model)
{
this->model = model;
if(model)
{
mintingProxyModel = new MintingFilterProxy(this);
mintingProxyModel->setSourceModel(model->getMintingTableModel());
mintingProxyModel->setDynamicSortFilter(true);
mintingProxyModel->setSortRole(Qt::EditRole);
mintingView->setModel(mintingProxyModel);
mintingView->setAlternatingRowColors(true);
mintingView->setSelectionBehavior(QAbstractItemView::SelectRows);
mintingView->setSelectionMode(QAbstractItemView::ExtendedSelection);
mintingView->setSortingEnabled(true);
mintingView->sortByColumn(MintingTableModel::CoinDay, Qt::DescendingOrder);
mintingView->verticalHeader()->hide();
mintingView->horizontalHeader()->resizeSection(
MintingTableModel::Age, 60);
mintingView->horizontalHeader()->resizeSection(
MintingTableModel::Balance, 80);
mintingView->horizontalHeader()->resizeSection(
MintingTableModel::CoinDay,60);
mintingView->horizontalHeader()->resizeSection(
MintingTableModel::MintProbability, 105);
#if QT_VERSION < 0x050000
mintingView->horizontalHeader()->setResizeMode(
MintingTableModel::MintReward, QHeaderView::Stretch);
#else
mintingView->horizontalHeader()->setSectionResizeMode(
MintingTableModel::MintReward, QHeaderView::Stretch);
#endif
mintingView->horizontalHeader()->resizeSection(
MintingTableModel::Address, 245);
mintingView->horizontalHeader()->resizeSection(
MintingTableModel::TxHash, 75);
}
}
void MintingView::chooseMintingInterval(int idx)
{
int interval = 10;
switch(mintingCombo->itemData(idx).toInt())
{
case Minting10min:
interval = 10;
break;
case Minting1day:
interval = 60*24;
break;
case Minting7days:
interval = 60*24*7;
break;
case Minting30days:
interval = 60*24*30;
break;
case Minting60days:
interval = 60*24*60;
break;
case Minting90days:
interval = 60*24*90;
break;
}
model->getMintingTableModel()->setMintingInterval(interval);
mintingProxyModel->invalidate();
}
void MintingView::exportClicked()
{
// CSV is currently the only supported format
QString filename = GUIUtil::getSaveFileName(
this,
tr("Export Minting Data"), QString(),
tr("Comma separated file (*.csv)"));
if (filename.isNull()) return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(mintingProxyModel);
writer.addColumn(tr("Address"),MintingTableModel::Address,0);
writer.addColumn(tr("Transaction"),MintingTableModel::TxHash,0);
writer.addColumn(tr("Age"), MintingTableModel::Age,0);
writer.addColumn(tr("CoinDay"), MintingTableModel::CoinDay,0);
writer.addColumn(tr("Balance"), MintingTableModel::Balance,0);
writer.addColumn(tr("MintingProbability"), MintingTableModel::MintProbability,0);
writer.addColumn(tr("MintingReward"), MintingTableModel::MintReward,0);
if(!writer.write())
{
QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename),
QMessageBox::Abort, QMessageBox::Abort);
}
}
void MintingView::copyTxID()
{
GUIUtil::copyEntryData(mintingView, MintingTableModel::TxHash, 0);
}
void MintingView::copyAddress()
{
GUIUtil::copyEntryData(mintingView, MintingTableModel::Address, 0 );
}
void MintingView::showHideAddress()
{
mintingView->horizontalHeader()->setSectionHidden(MintingTableModel::Address,
!(mintingView->horizontalHeader()->isSectionHidden(MintingTableModel::Address)));
}
void MintingView::showHideTxID()
{
mintingView->horizontalHeader()->setSectionHidden(MintingTableModel::TxHash,
!(mintingView->horizontalHeader()->isSectionHidden(MintingTableModel::TxHash)));
}
void MintingView::contextualMenu(const QPoint &point)
{
QModelIndex index = mintingView->indexAt(point);
if(index.isValid())
{
contextMenu->exec(QCursor::pos());
}
} | [
"fsb4000@yandex.ru"
] | fsb4000@yandex.ru |
769f486f9eaea63e238ccf9611d4d47453dd6995 | 44b2b74338fd359e6535b216319799a1af2ec83c | /communect/searchuser.cpp | 2ecafed1eb302d7b447f980bd778bd8a4fbf6939 | [] | no_license | nozberkaryaindonesia/public | b0cb38f125012d6e931d46266d480729d422705e | 528104029b7f8ebe5734ae6cc4374b5b84d6ef62 | refs/heads/master | 2022-06-05T16:02:33.100468 | 2014-04-07T06:27:34 | 2014-04-07T06:27:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | cpp | /*#include "searchuser.h"
#include "ui_searchuser.h"
searchuser::searchuser(QWidget *parent) :
QDialog(parent),
ui(new Ui::searchuser)
{
ui->setupUi(this);
}
searchuser::~searchuser()
{
delete ui;
}
*/
| [
"festinsalazarsison@gmail.com"
] | festinsalazarsison@gmail.com |
cfcdaf92ae1a9e6512a390c6755aed5288ccb417 | 2ca36f1406d6e6acad6e4f3663d1a1da4fe1ba25 | /main/chase_value.h | 60b4b1d38c7975b218a78574d9d02e49925e8410 | [] | no_license | je-pu-pu/hand | ce24eacdfaa551a85ff2e2ad7e98b82b62d29541 | bdbc33d5e4912972e0af8ab3cb529be06c9cfb88 | refs/heads/master | 2020-03-11T11:30:12.162397 | 2018-05-06T15:48:30 | 2018-05-06T15:48:30 | 129,971,200 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,123 | h | #ifndef COMMON_CHASE_VALUE_H
#define COMMON_CHASE_VALUE_H
#include "math.h"
namespace common
{
template< typename Type >
class chase_value
{
private:
Type value_;
Type target_value_;
Type speed_;
public:
chase_value( Type value, Type target_value, Type speed )
: value_( value )
, target_value_( target_value )
, speed_( speed )
{
}
void chase()
{
value_ = math::chase( value_, target_value_, speed_ );
}
void chase( Type speed )
{
value_ = math::chase( value_, target_value_, speed );
}
void fit_to_target()
{
value_ = target_value_;
}
void fit( Type v )
{
value_ = v;
target_value_ = v;
}
Type& value() { return value_; }
Type value() const { return value_; }
Type& target_value() { return target_value_; }
Type target_value() const { return target_value_; }
Type& speed() { return speed_; }
Type speed() const { return speed_; }
// Type operator Type () { return value_; }
// Type operator Type () const { return value_; }
}; // class chase_value
} // namespace common
#endif // COMMON_SERIALIZE_H
| [
"je@je-pu-pu.jp"
] | je@je-pu-pu.jp |
9458a17564ceb99412ab938caf4f18fe654636ef | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/xdktools/Producer/StyleDesigner/TabPatternPattern.cpp | e032a8bb3ada599c58ae1105cfff41338c332049 | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,271 | cpp | // TabPatternPattern.cpp : implementation file
//
#include "stdafx.h"
#include "StyleDesignerDLL.h"
#include "Style.h"
#include "Pattern.h"
#include "PatternLengthDlg.h"
#include "TimeSignatureDlg.h"
#include "RhythmDlg.h"
#include "TabPatternPattern.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern property page
CTabPatternPattern::CTabPatternPattern( CPatternPropPageManager* pPatternPropPageManager ) : CPropertyPage(CTabPatternPattern::IDD)
{
//{{AFX_DATA_INIT(CTabPatternPattern)
//}}AFX_DATA_INIT
ASSERT( pPatternPropPageManager != NULL );
m_pPattern = NULL;
m_pPageManager = pPatternPropPageManager;
m_fNeedToDetach = FALSE;
}
CTabPatternPattern::~CTabPatternPattern()
{
// Work around 27331
m_pPattern = NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::RefreshTab
void CTabPatternPattern::RefreshTab( IDMUSProdPropPageObject* pIPropPageObject )
{
PPGPattern ppgPattern;
PPGPattern* pPPGPattern = &ppgPattern;
if( pIPropPageObject
&& ( SUCCEEDED ( pIPropPageObject->GetData((void **)&pPPGPattern ) ) ) )
{
m_pPattern = ppgPattern.pPattern;
}
else
{
m_pPattern = NULL;
}
UpdateControls();
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::EnableControls
void CTabPatternPattern::EnableControls( BOOL fEnable )
{
m_editName.EnableWindow( fEnable );
m_btnLength.EnableWindow( fEnable );
m_editGrooveBottom.EnableWindow( fEnable );
m_spinGrooveBottom.EnableWindow( fEnable );
m_editGrooveTop.EnableWindow( fEnable );
m_spinGrooveTop.EnableWindow( fEnable );
m_editDestBottom.EnableWindow( fEnable );
m_spinDestBottom.EnableWindow( fEnable );
m_editDestTop.EnableWindow( fEnable );
m_spinDestTop.EnableWindow( fEnable );
m_btnIntro.EnableWindow( fEnable );
m_btnFill.EnableWindow( fEnable );
m_btnBreak.EnableWindow( fEnable );
m_btnEnd.EnableWindow( fEnable );
m_btnCustom.EnableWindow( fEnable );
m_editCustomId.EnableWindow( fEnable );
m_spinCustomId.EnableWindow( fEnable );
m_btnTimeSignature.EnableWindow( fEnable );
m_btnCustomDlg.EnableWindow( fEnable );
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::UpdateControls
void CTabPatternPattern::UpdateControls()
{
// Make sure controls have been created
if( ::IsWindow(m_editName.m_hWnd) == FALSE )
{
return;
}
// Update controls
m_editName.LimitText( DMUS_MAX_NAME );
m_editGrooveBottom.LimitText( 3 );
m_editGrooveTop.LimitText( 3 );
m_editDestBottom.LimitText( 3 );
m_editDestTop.LimitText( 3 );
m_editCustomId.LimitText( 3 );
if( m_pPattern )
{
EnableControls( TRUE );
// Set name
m_editName.SetWindowText( m_pPattern->m_strName );
// Set length
CString strLength;
strLength.Format( "%d", m_pPattern->m_wNbrMeasures );
m_btnLength.SetWindowText( strLength );
// Set Bottom Groove
m_spinGrooveBottom.SetRange( MIN_GROOVE, MAX_GROOVE );
m_spinGrooveBottom.SetPos( m_pPattern->m_bGrooveBottom );
// Set Top Groove
m_spinGrooveTop.SetRange( MIN_GROOVE, MAX_GROOVE );
m_spinGrooveTop.SetPos( m_pPattern->m_bGrooveTop );
// Set Destination Bottom Groove
m_spinDestBottom.SetRange( MIN_GROOVE, MAX_GROOVE );
m_spinDestBottom.SetPos( m_pPattern->m_bDestGrooveBottom );
// Set Destination Top Groove
m_spinDestTop.SetRange( MIN_GROOVE, MAX_GROOVE );
m_spinDestTop.SetPos( m_pPattern->m_bDestGrooveTop );
// Set Embellishments
m_btnIntro.SetCheck( (m_pPattern->m_wEmbellishment & EMB_INTRO) ? TRUE : FALSE );
m_btnFill.SetCheck( (m_pPattern->m_wEmbellishment & EMB_FILL) ? TRUE : FALSE );
m_btnBreak.SetCheck( (m_pPattern->m_wEmbellishment & EMB_BREAK) ? TRUE : FALSE );
m_btnEnd.SetCheck( (m_pPattern->m_wEmbellishment & EMB_END) ? TRUE : FALSE );
// Set User-defined Embellishment
BOOL fCustomEmbellishment = FALSE;
if( HIBYTE(m_pPattern->m_wEmbellishment) >= MIN_EMB_CUSTOM_ID
&& HIBYTE(m_pPattern->m_wEmbellishment) <= MAX_EMB_CUSTOM_ID )
{
fCustomEmbellishment = TRUE;
ASSERT( LOBYTE(m_pPattern->m_wEmbellishment) == 0 );
}
m_btnCustom.SetCheck( fCustomEmbellishment );
m_spinCustomId.SetRange( MIN_EMB_CUSTOM_ID, MAX_EMB_CUSTOM_ID );
if( fCustomEmbellishment )
{
m_editCustomId.EnableWindow( TRUE );
m_spinCustomId.EnableWindow( TRUE );
m_spinCustomId.SetPos( HIBYTE(m_pPattern->m_wEmbellishment) );
}
else
{
m_spinCustomId.SetPos( m_pPattern->m_nLastCustomId );
m_editCustomId.EnableWindow( FALSE );
m_spinCustomId.EnableWindow( FALSE );
}
// Draw rhythm map
m_btnRhythmMap.Invalidate();
// Update bitmap on time signature button
SetTimeSignatureBitmap();
}
else
{
m_editName.SetWindowText( _T("") );
m_btnLength.SetWindowText( _T("") );
m_spinGrooveBottom.SetRange( MIN_GROOVE, MAX_GROOVE );
m_spinGrooveBottom.SetPos( MIN_GROOVE );
m_spinGrooveTop.SetRange( MIN_GROOVE, MAX_GROOVE );
m_spinGrooveTop.SetPos( MAX_GROOVE );
m_spinDestBottom.SetRange( MIN_GROOVE, MAX_GROOVE );
m_spinDestBottom.SetPos( MIN_GROOVE );
m_spinDestTop.SetRange( MIN_GROOVE, MAX_GROOVE );
m_spinDestTop.SetPos( MAX_GROOVE );
m_btnIntro.SetCheck( 0 );
m_btnFill.SetCheck( 0 );
m_btnBreak.SetCheck( 0 );
m_btnEnd.SetCheck( 0 );
m_btnCustom.SetCheck( 0 );
m_spinCustomId.SetRange( MIN_EMB_CUSTOM_ID, MAX_EMB_CUSTOM_ID );
m_spinCustomId.SetPos( MIN_EMB_CUSTOM_ID );
m_btnRhythmMap.Invalidate();
EnableControls( FALSE );
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::SetTimeSignatureBitmap
void CTabPatternPattern::SetTimeSignatureBitmap( void )
{
if( !::IsWindow( m_btnTimeSignature.m_hWnd ) )
{
return;
}
HBITMAP hNewBits = NULL;
ASSERT( m_pPattern != NULL );
RECT rect;
m_btnTimeSignature.GetClientRect( &rect );
// Create a DC for the new bitmap
// a DC for the 'Grids Per Beat' bitmap
// a Bitmap for the new bits
CDC cdcDest;
CDC cdcGridsPerBeat;
CBitmap bmpNewBits;
CBitmap bmpGridsPerBeat;
CDC* pDC = m_btnTimeSignature.GetDC();
if( pDC )
{
if( cdcDest.CreateCompatibleDC( pDC ) == FALSE
|| cdcGridsPerBeat.CreateCompatibleDC( pDC ) == FALSE
|| bmpNewBits.CreateCompatibleBitmap( pDC, rect.right, rect.bottom ) == FALSE )
{
m_btnTimeSignature.ReleaseDC( pDC );
return;
}
m_btnTimeSignature.ReleaseDC( pDC );
}
// Create the new bitmap
CBitmap* pbmpOldMem = cdcDest.SelectObject( &bmpNewBits );
// Fill Rect with button color
cdcDest.SetBkColor( ::GetSysColor(COLOR_BTNFACE) );
cdcDest.ExtTextOut( 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
// Write text
CString strTimeSignature;
CFont font;
CFont* pfontOld = NULL;
if( font.CreateFont( 10, 0, 0, 0, FW_NORMAL, 0, 0, 0,
DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "MS Sans Serif" ) )
{
pfontOld = cdcDest.SelectObject( &font );
}
strTimeSignature.Format( "%d/%d",
m_pPattern->m_TimeSignature.m_bBeatsPerMeasure,
m_pPattern->m_TimeSignature.m_bBeat );
rect.left += 6;
cdcDest.SetTextColor( COLOR_BTNTEXT );
cdcDest.DrawText( strTimeSignature, -1, &rect, (DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_NOPREFIX) );
rect.left -= 6;
if( pfontOld )
{
cdcDest.SelectObject( pfontOld );
font.DeleteObject();
}
// Set x coord for 'Grids Per Beat' image
CSize sizeText = cdcDest.GetTextExtent( strTimeSignature );
int nX = max( 48, (sizeText.cx + 8) );
// Draw "splitter"
{
CPen pen1;
CPen pen2;
CPen* ppenOld;
int nPlace = nX - 6;
int nModeOld = cdcDest.SetROP2( R2_COPYPEN );
// Highlight
if( pen1.CreatePen( PS_SOLID, 1, ::GetSysColor(COLOR_BTNSHADOW) ) )
{
ppenOld = cdcDest.SelectObject( &pen1 );
cdcDest.MoveTo( nPlace, (rect.top + 3) );
cdcDest.LineTo( nPlace, (rect.bottom - 3) );
cdcDest.SelectObject( ppenOld );
}
// Shadow
if( pen2.CreatePen( PS_SOLID, 1, ::GetSysColor(COLOR_BTNHIGHLIGHT) ) )
{
ppenOld = cdcDest.SelectObject( &pen2 );
cdcDest.MoveTo( ++nPlace, (rect.top + 3) );
cdcDest.LineTo( nPlace, (rect.bottom - 3) );
cdcDest.SelectObject( ppenOld );
}
if( nModeOld )
{
cdcDest.SetROP2( nModeOld );
}
}
// Add 'Grids Per Beat' bitmap
{
int nResourceID = m_pPattern->m_TimeSignature.m_wGridsPerBeat - 1;
if( m_pPattern->m_TimeSignature.m_bBeat != 4 ) // 4 = quarter note gets the beat
{
nResourceID += MAX_GRIDS_PER_BEAT;
}
ASSERT( (nResourceID >= 0) && (nResourceID <= MAX_GRIDS_PER_BEAT_ENTRIES) );
if( bmpGridsPerBeat.LoadBitmap( g_nGridsPerBeatBitmaps[nResourceID] ) )
{
BITMAP bm;
bmpGridsPerBeat.GetBitmap( &bm );
int nY = ((rect.bottom - rect.top) - bm.bmHeight) >> 1;
CBitmap* pbmpOld = cdcGridsPerBeat.SelectObject( &bmpGridsPerBeat );
{
CDC cdcMono;
CBitmap bmpMono;
if( cdcMono.CreateCompatibleDC( &cdcDest )
&& bmpMono.CreateBitmap( bm.bmWidth, bm.bmHeight, 1, 1, NULL ) )
{
CBitmap* pbmpOldMono = cdcMono.SelectObject( &bmpMono );
cdcGridsPerBeat.SetBkColor( RGB(255,255,255) );
cdcDest.SetBkColor( RGB(255,255,255) );
cdcMono.BitBlt( 0, 0, bm.bmWidth, bm.bmHeight,
&cdcGridsPerBeat, 0, 0, SRCCOPY);
cdcDest.BitBlt( nX, nY, bm.bmWidth, bm.bmHeight,
&cdcGridsPerBeat, 0, 0, SRCINVERT ) ;
cdcDest.BitBlt( nX, nY, bm.bmWidth, bm.bmHeight,
&cdcMono, 0, 0, SRCAND ) ;
cdcDest.BitBlt( nX, nY, bm.bmWidth, bm.bmHeight,
&cdcGridsPerBeat, 0, 0, SRCINVERT ) ;
cdcMono.SelectObject( pbmpOldMono ) ;
}
}
cdcGridsPerBeat.SelectObject( pbmpOld );
}
}
cdcDest.SelectObject( pbmpOldMem );
// Set the new bitmap
hNewBits = (HBITMAP)bmpNewBits.Detach();
if( hNewBits )
{
HBITMAP hBitmapOld = m_btnTimeSignature.SetBitmap( hNewBits );
if( hBitmapOld )
{
::DeleteObject( hBitmapOld );
}
}
}
void CTabPatternPattern::DoDataExchange(CDataExchange* pDX)
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTabPatternPattern)
DDX_Control(pDX, IDC_EMB_CUSTOM, m_btnCustom);
DDX_Control(pDX, IDC_CUSTOM_ID, m_editCustomId);
DDX_Control(pDX, IDC_CUSTOM_ID_SPIN, m_spinCustomId);
DDX_Control(pDX, IDC_DEST_TOP_SPIN, m_spinDestTop);
DDX_Control(pDX, IDC_DEST_BOTTOM_SPIN, m_spinDestBottom);
DDX_Control(pDX, IDC_DEST_TOP, m_editDestTop);
DDX_Control(pDX, IDC_DEST_BOTTOM, m_editDestBottom);
DDX_Control(pDX, IDC_TIME_SIGNATURE, m_btnTimeSignature);
DDX_Control(pDX, IDC_RHYTHM_MAP, m_btnRhythmMap);
DDX_Control(pDX, IDC_CUSTOM_DLG, m_btnCustomDlg);
DDX_Control(pDX, IDC_EMB_INTRO, m_btnIntro);
DDX_Control(pDX, IDC_EMB_FILL, m_btnFill);
DDX_Control(pDX, IDC_EMB_END, m_btnEnd);
DDX_Control(pDX, IDC_EMB_BREAK, m_btnBreak);
DDX_Control(pDX, IDC_GROOVE_TOP_SPIN, m_spinGrooveTop);
DDX_Control(pDX, IDC_GROOVE_TOP, m_editGrooveTop);
DDX_Control(pDX, IDC_GROOVE_BOTTOM_SPIN, m_spinGrooveBottom);
DDX_Control(pDX, IDC_GROOVE_BOTTOM, m_editGrooveBottom);
DDX_Control(pDX, IDC_NAME, m_editName);
DDX_Control(pDX, IDC_LENGTH, m_btnLength);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTabPatternPattern, CPropertyPage)
//{{AFX_MSG_MAP(CTabPatternPattern)
ON_WM_CREATE()
ON_WM_DESTROY()
ON_EN_KILLFOCUS(IDC_NAME, OnKillFocusName)
ON_BN_CLICKED(IDC_LENGTH, OnLength)
ON_EN_KILLFOCUS(IDC_GROOVE_BOTTOM, OnKillFocusGrooveBottom)
ON_NOTIFY(UDN_DELTAPOS, IDC_GROOVE_BOTTOM_SPIN, OnDeltaPosGrooveBottomSpin)
ON_EN_KILLFOCUS(IDC_GROOVE_TOP, OnKillFocusGrooveTop)
ON_NOTIFY(UDN_DELTAPOS, IDC_GROOVE_TOP_SPIN, OnDeltaPosGrooveTopSpin)
ON_BN_CLICKED(IDC_EMB_INTRO, OnEmbIntro)
ON_BN_CLICKED(IDC_EMB_FILL, OnEmbFill)
ON_BN_CLICKED(IDC_EMB_BREAK, OnEmbBreak)
ON_BN_CLICKED(IDC_EMB_END, OnEmbEnd)
ON_BN_CLICKED(IDC_CUSTOM_DLG, OnCustomDlg)
ON_WM_DRAWITEM()
ON_BN_CLICKED(IDC_TIME_SIGNATURE, OnTimeSignature)
ON_EN_KILLFOCUS(IDC_DEST_BOTTOM, OnKillFocusDestBottom)
ON_NOTIFY(UDN_DELTAPOS, IDC_DEST_BOTTOM_SPIN, OnDeltaPosDestBottomSpin)
ON_EN_KILLFOCUS(IDC_DEST_TOP, OnKillFocusDestTop)
ON_NOTIFY(UDN_DELTAPOS, IDC_DEST_TOP_SPIN, OnDeltaPosDestTopSpin)
ON_BN_CLICKED(IDC_EMB_CUSTOM, OnEmbCustom)
ON_EN_KILLFOCUS(IDC_CUSTOM_ID, OnKillFocusCustomId)
ON_NOTIFY(UDN_DELTAPOS, IDC_CUSTOM_ID_SPIN, OnDeltaPosCustomIdSpin)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern message handlers
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnSetActive
BOOL CTabPatternPattern::OnSetActive()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
UpdateControls();
return CPropertyPage::OnSetActive();
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnCreate
int CTabPatternPattern::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
// Attach the window to the property page structure.
// This has been done once already in the main application
// since the main application owns the property sheet.
// It needs to be done here so that the window handle can
if( !FromHandlePermanent( m_hWnd ) )
{
HWND hWnd = m_hWnd;
m_hWnd = NULL;
Attach( hWnd );
m_fNeedToDetach = TRUE;
}
if( CPropertyPage::OnCreate(lpCreateStruct) == -1 )
{
return -1;
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnDestroy
void CTabPatternPattern::OnDestroy()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
// Delete the time signature button's bitmap
HBITMAP hBitmap = m_btnTimeSignature.GetBitmap();
if( hBitmap )
{
::DeleteObject( hBitmap );
}
// Detach the window from the property page structure.
// This will be done again by the main application since
// it owns the property sheet. It needs o be done here
// so that the window handle can be removed from the
// DLLs handle map.
if( m_fNeedToDetach && m_hWnd )
{
HWND hWnd = m_hWnd;
Detach();
m_hWnd = hWnd;
}
CPropertyPage::OnDestroy();
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnKillFocusName
void CTabPatternPattern::OnKillFocusName()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
ASSERT( theApp.m_pStyleComponent != NULL );
ASSERT( theApp.m_pStyleComponent->m_pIFramework != NULL );
if( m_pPattern )
{
CString strName;
m_editName.GetWindowText( strName );
// Strip leading and trailing spaces
strName.TrimRight();
strName.TrimLeft();
if( strName.IsEmpty() )
{
m_editName.SetWindowText( m_pPattern->m_strName );
}
else
{
if( strName.Compare( m_pPattern->m_strName ) != 0 )
{
BSTR bstrName = strName.AllocSysString();
m_pPattern->SetNodeName( bstrName );
theApp.m_pStyleComponent->m_pIFramework->RefreshNode( m_pPattern );
}
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnLength
void CTabPatternPattern::OnLength()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
CPatternLengthDlg plDlg( m_pPattern );
if( plDlg.DoModal() == IDOK )
{
CString strLength;
if( ::IsWindow( m_btnLength.m_hWnd ) )
{
strLength.Format( "%d", m_pPattern->m_wNbrMeasures );
m_btnLength.SetWindowText( strLength );
}
// Redraw rhythm map
if( ::IsWindow( m_btnRhythmMap.m_hWnd ) )
{
m_btnRhythmMap.Invalidate();
m_btnRhythmMap.UpdateWindow();
}
}
if( ::IsWindow( m_btnLength.m_hWnd ) )
{
m_btnLength.SetFocus();
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnKillFocusGrooveBottom
void CTabPatternPattern::OnKillFocusGrooveBottom()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
CString strNewGrooveBottom;
m_editGrooveBottom.GetWindowText( strNewGrooveBottom );
// Strip leading and trailing spaces
strNewGrooveBottom.TrimRight();
strNewGrooveBottom.TrimLeft();
if( strNewGrooveBottom.IsEmpty() )
{
m_spinGrooveBottom.SetPos( m_pPattern->m_bGrooveBottom );
}
else
{
int nNewGrooveBottom = _ttoi( strNewGrooveBottom );
int nNewGrooveTop = m_pPattern->m_bGrooveTop;
if( nNewGrooveBottom < MIN_GROOVE)
{
nNewGrooveBottom = MIN_GROOVE;
}
if( nNewGrooveBottom > MAX_GROOVE)
{
nNewGrooveBottom = MAX_GROOVE;
}
m_spinGrooveBottom.SetPos( nNewGrooveBottom );
if( nNewGrooveBottom > nNewGrooveTop )
{
nNewGrooveTop = nNewGrooveBottom;
m_spinGrooveTop.SetPos( nNewGrooveTop );
}
m_pPattern->SetGrooveRange( (BYTE)nNewGrooveBottom, (BYTE)nNewGrooveTop );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnDeltaPosGrooveBottomSpin
void CTabPatternPattern::OnDeltaPosGrooveBottomSpin( NMHDR* pNMHDR, LRESULT* pResult )
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
int nGrooveBottom = m_spinGrooveBottom.GetPos();
if( HIWORD(nGrooveBottom) == 0 )
{
int nNewGrooveBottom = LOWORD(nGrooveBottom) + pNMUpDown->iDelta;
int nNewGrooveTop = m_pPattern->m_bGrooveTop;
if( nNewGrooveBottom < MIN_GROOVE)
{
nNewGrooveBottom = MIN_GROOVE;
}
if( nNewGrooveBottom > MAX_GROOVE)
{
nNewGrooveBottom = MAX_GROOVE;
}
m_spinGrooveBottom.SetPos( nNewGrooveBottom );
if( nNewGrooveBottom > nNewGrooveTop )
{
nNewGrooveTop = nNewGrooveBottom;
m_spinGrooveTop.SetPos( nNewGrooveTop );
}
m_pPattern->SetGrooveRange( (BYTE)nNewGrooveBottom, (BYTE)nNewGrooveTop );
}
}
*pResult = 1;
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnKillFocusGrooveTop
void CTabPatternPattern::OnKillFocusGrooveTop()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
CString strNewGrooveTop;
m_editGrooveTop.GetWindowText( strNewGrooveTop );
// Strip leading and trailing spaces
strNewGrooveTop.TrimRight();
strNewGrooveTop.TrimLeft();
if( strNewGrooveTop.IsEmpty() )
{
m_spinGrooveTop.SetPos( m_pPattern->m_bGrooveTop );
}
else
{
int nNewGrooveTop = _ttoi( strNewGrooveTop );
int nNewGrooveBottom = m_pPattern->m_bGrooveBottom;
if( nNewGrooveTop < MIN_GROOVE)
{
nNewGrooveTop = MIN_GROOVE;
}
if( nNewGrooveTop > MAX_GROOVE)
{
nNewGrooveTop = MAX_GROOVE;
}
m_spinGrooveTop.SetPos( nNewGrooveTop );
if( nNewGrooveTop < nNewGrooveBottom )
{
nNewGrooveBottom = nNewGrooveTop;
m_spinGrooveBottom.SetPos( nNewGrooveBottom );
}
m_pPattern->SetGrooveRange( (BYTE)nNewGrooveBottom, (BYTE)nNewGrooveTop );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnDeltaPosGrooveTopSpin
void CTabPatternPattern::OnDeltaPosGrooveTopSpin( NMHDR* pNMHDR, LRESULT* pResult )
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
int nGrooveTop = m_spinGrooveTop.GetPos();
if( HIWORD(nGrooveTop) == 0 )
{
int nNewGrooveTop = LOWORD(nGrooveTop) + pNMUpDown->iDelta;
int nNewGrooveBottom = m_pPattern->m_bGrooveBottom;
if( nNewGrooveTop < MIN_GROOVE)
{
nNewGrooveTop = MIN_GROOVE;
}
if( nNewGrooveTop > MAX_GROOVE)
{
nNewGrooveTop = MAX_GROOVE;
}
m_spinGrooveTop.SetPos( nNewGrooveTop );
if( nNewGrooveTop < nNewGrooveBottom )
{
nNewGrooveBottom = nNewGrooveTop;
m_spinGrooveBottom.SetPos( nNewGrooveBottom );
}
m_pPattern->SetGrooveRange( (BYTE)nNewGrooveBottom, (BYTE)nNewGrooveTop );
}
}
*pResult = 1;
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnEmbIntro
void CTabPatternPattern::OnEmbIntro()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
if( m_btnIntro.GetCheck() )
{
m_pPattern->SetEmbellishment( EMB_INTRO, 0, 0 );
}
else
{
m_pPattern->SetEmbellishment( 0, EMB_INTRO, 0 );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnEmbFill
void CTabPatternPattern::OnEmbFill()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
if( m_btnFill.GetCheck() )
{
m_pPattern->SetEmbellishment( EMB_FILL, 0, 0 );
}
else
{
m_pPattern->SetEmbellishment( 0, EMB_FILL, 0 );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnEmbBreak
void CTabPatternPattern::OnEmbBreak()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
if( m_btnBreak.GetCheck() )
{
m_pPattern->SetEmbellishment( EMB_BREAK, 0, 0 );
}
else
{
m_pPattern->SetEmbellishment( 0, EMB_BREAK, 0 );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnEmbEnd
void CTabPatternPattern::OnEmbEnd()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
if( m_btnEnd.GetCheck() )
{
m_pPattern->SetEmbellishment( EMB_END, 0, 0 );
}
else
{
m_pPattern->SetEmbellishment( 0, EMB_END, 0 );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnCustomDlg
void CTabPatternPattern::OnCustomDlg()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
// Display rhythmDlg
CRhythmDlg rhythmDlg;
rhythmDlg.m_TimeSignature = m_pPattern->m_TimeSignature;
rhythmDlg.m_wNbrMeasures = m_pPattern->m_wNbrMeasures;
rhythmDlg.m_pRhythmMap = new DWORD[m_pPattern->m_wNbrMeasures];
if( rhythmDlg.m_pRhythmMap )
{
for( int i = 0 ; i < m_pPattern->m_wNbrMeasures ; ++i )
{
rhythmDlg.m_pRhythmMap[i] = m_pPattern->m_pRhythmMap[i];
}
if( rhythmDlg.DoModal() == IDOK )
{
// Update rhythm map
m_pPattern->SetRhythmMap( rhythmDlg.m_pRhythmMap );
// Redraw rhythm map
if( ::IsWindow( m_btnRhythmMap.m_hWnd ) )
{
m_btnRhythmMap.Invalidate();
m_btnRhythmMap.UpdateWindow();
}
}
}
if( ::IsWindow( m_btnCustomDlg.m_hWnd ) )
{
m_btnCustomDlg.SetFocus();
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnDrawItem
void CTabPatternPattern::OnDrawItem( int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct )
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern == NULL )
{
CPropertyPage::OnDrawItem( nIDCtl, lpDrawItemStruct );
return;
}
switch( nIDCtl )
{
case IDC_RHYTHM_MAP:
{
if( lpDrawItemStruct->itemID == -1 )
{
return;
}
CDC* pDC = CDC::FromHandle( lpDrawItemStruct->hDC );
if( pDC == NULL )
{
return;
}
if( lpDrawItemStruct->itemAction & ODA_DRAWENTIRE
|| lpDrawItemStruct->itemAction & ODA_SELECT )
{
int i, j;
int nMaxRight = lpDrawItemStruct->rcItem.right - 4;
CRect rect( lpDrawItemStruct->rcItem );
rect.right = rect.left;
rect.InflateRect( 0, -3 );
int nTickHeight = (rect.Height() >> 1) - 1;
for( i = 0 ; i < m_pPattern->m_wNbrMeasures ; i++ )
{
for( j = 0 ; j < 32 ; j++ )
{
if( j >= m_pPattern->m_TimeSignature.m_bBeatsPerMeasure )
{
break;
}
rect.left = rect.right + 2;
rect.right = rect.left + 1;
if( rect.left >= nMaxRight )
{
break;
}
if( m_pPattern->m_pRhythmMap[i] & (1 << j) )
{
pDC->FillSolidRect( &rect, RGB(0,0,0) );
}
else
{
rect.InflateRect( 0, -nTickHeight );
pDC->FillSolidRect( &rect, RGB(0,0,0) );
rect.InflateRect( 0, nTickHeight );
}
}
rect.left += 3;
rect.right += 3;
if( rect.left >= nMaxRight )
{
break;
}
}
rect.InflateRect( 0, 3 );
}
return;
}
}
CPropertyPage::OnDrawItem( nIDCtl, lpDrawItemStruct );
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnTimeSignature
void CTabPatternPattern::OnTimeSignature()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
CTimeSignatureDlg tsDlg;
tsDlg.m_TimeSignature = m_pPattern->m_TimeSignature;
tsDlg.m_nContext = IDS_PATTERN_TEXT;
if( tsDlg.DoModal() == IDOK )
{
// Update time signature
AfxMessageBox( "Not yet implemented." );
// AMC?? m_pPattern->SetTimeSignature( tsDlg.m_TimeSignature, FALSE );
// Update bitmap on time signature button
SetTimeSignatureBitmap();
}
if( ::IsWindow( m_btnTimeSignature.m_hWnd ) )
{
m_btnTimeSignature.SetFocus();
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnKillFocusDestBottom
void CTabPatternPattern::OnKillFocusDestBottom()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
CString strNewDestBottom;
m_editDestBottom.GetWindowText( strNewDestBottom );
// Strip leading and trailing spaces
strNewDestBottom.TrimRight();
strNewDestBottom.TrimLeft();
if( strNewDestBottom.IsEmpty() )
{
m_spinDestBottom.SetPos( m_pPattern->m_bDestGrooveBottom );
}
else
{
int nNewDestBottom = _ttoi( strNewDestBottom );
int nNewDestTop = m_pPattern->m_bDestGrooveTop;
if( nNewDestBottom < MIN_GROOVE)
{
nNewDestBottom = MIN_GROOVE;
}
if( nNewDestBottom > MAX_GROOVE)
{
nNewDestBottom = MAX_GROOVE;
}
m_spinDestBottom.SetPos( nNewDestBottom );
if( nNewDestBottom > nNewDestTop )
{
nNewDestTop = nNewDestBottom;
m_spinDestTop.SetPos( nNewDestTop );
}
m_pPattern->SetDestGrooveRange( (BYTE)nNewDestBottom, (BYTE)nNewDestTop );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnDeltaPosDestBottomSpin
void CTabPatternPattern::OnDeltaPosDestBottomSpin( NMHDR* pNMHDR, LRESULT* pResult )
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
int nDestBottom = m_spinDestBottom.GetPos();
int nNewDestTop = m_pPattern->m_bDestGrooveTop;
if( HIWORD(nDestBottom) == 0 )
{
int nNewDestBottom = LOWORD(nDestBottom) + pNMUpDown->iDelta;
if( nNewDestBottom < MIN_GROOVE)
{
nNewDestBottom = MIN_GROOVE;
}
if( nNewDestBottom > MAX_GROOVE)
{
nNewDestBottom = MAX_GROOVE;
}
m_spinDestBottom.SetPos( nNewDestBottom );
if( nNewDestBottom > nNewDestTop )
{
nNewDestTop = nNewDestBottom;
m_spinDestTop.SetPos( nNewDestTop );
}
m_pPattern->SetDestGrooveRange( (BYTE)nNewDestBottom, (BYTE)nNewDestTop );
}
}
*pResult = 1;
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnKillFocusDestTop
void CTabPatternPattern::OnKillFocusDestTop()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
CString strNewDestTop;
m_editDestTop.GetWindowText( strNewDestTop );
// Strip leading and trailing spaces
strNewDestTop.TrimRight();
strNewDestTop.TrimLeft();
if( strNewDestTop.IsEmpty() )
{
m_spinDestTop.SetPos( m_pPattern->m_bDestGrooveTop );
}
else
{
int nNewDestTop = _ttoi( strNewDestTop );
int nNewDestBottom = m_pPattern->m_bDestGrooveBottom;
if( nNewDestTop < MIN_GROOVE)
{
nNewDestTop = MIN_GROOVE;
}
if( nNewDestTop > MAX_GROOVE)
{
nNewDestTop = MAX_GROOVE;
}
m_spinDestTop.SetPos( nNewDestTop );
if( nNewDestTop < nNewDestBottom )
{
nNewDestBottom = nNewDestTop;
m_spinDestBottom.SetPos( nNewDestBottom );
}
m_pPattern->SetDestGrooveRange( (BYTE)nNewDestBottom, (BYTE)nNewDestTop );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnDeltaPosDestTopSpin
void CTabPatternPattern::OnDeltaPosDestTopSpin( NMHDR* pNMHDR, LRESULT* pResult )
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
int nDestTop = m_spinDestTop.GetPos();
if( HIWORD(nDestTop) == 0 )
{
int nNewDestTop = LOWORD(nDestTop) + pNMUpDown->iDelta;
int nNewDestBottom = m_pPattern->m_bDestGrooveBottom;
if( nNewDestTop < MIN_GROOVE)
{
nNewDestTop = MIN_GROOVE;
}
if( nNewDestTop > MAX_GROOVE)
{
nNewDestTop = MAX_GROOVE;
}
m_spinDestTop.SetPos( nNewDestTop );
if( nNewDestTop < nNewDestBottom )
{
nNewDestBottom = nNewDestTop;
m_spinDestBottom.SetPos( nNewDestBottom );
}
m_pPattern->SetDestGrooveRange( (BYTE)nNewDestBottom, (BYTE)nNewDestTop );
}
}
*pResult = 1;
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnEmbCustom
void CTabPatternPattern::OnEmbCustom()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
if( m_btnCustom.GetCheck() )
{
m_pPattern->SetEmbellishment( 0, EMB_ALL, m_pPattern->m_nLastCustomId );
}
else
{
m_pPattern->SetEmbellishment( 0, EMB_ALL, 0 );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnKillFocusCustomId
void CTabPatternPattern::OnKillFocusCustomId()
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
CString strNewCustomId;
m_editCustomId.GetWindowText( strNewCustomId );
// Strip leading and trailing spaces
strNewCustomId.TrimRight();
strNewCustomId.TrimLeft();
if( strNewCustomId.IsEmpty() )
{
ASSERT( HIBYTE(m_pPattern->m_wEmbellishment) >= MIN_EMB_CUSTOM_ID
&& HIBYTE(m_pPattern->m_wEmbellishment) <= MAX_EMB_CUSTOM_ID );
m_spinCustomId.SetPos( HIBYTE(m_pPattern->m_wEmbellishment) );
}
else
{
int nNewCustomId = _ttoi( strNewCustomId );
if( nNewCustomId < MIN_EMB_CUSTOM_ID)
{
nNewCustomId = MIN_EMB_CUSTOM_ID;
}
if( nNewCustomId > MAX_EMB_CUSTOM_ID)
{
nNewCustomId = MAX_EMB_CUSTOM_ID;
}
m_spinCustomId.SetPos( nNewCustomId );
m_pPattern->SetEmbellishment( 0, EMB_ALL, (BYTE)nNewCustomId );
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CTabPatternPattern::OnDeltaPosCustomIdSpin
void CTabPatternPattern::OnDeltaPosCustomIdSpin( NMHDR* pNMHDR, LRESULT* pResult )
{
AFX_MANAGE_STATE(_afxModuleAddrThis);
if( m_pPattern )
{
NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;
int nCustomId = m_spinCustomId.GetPos();
if( HIWORD(nCustomId) == 0 )
{
int nNewCustomId = LOWORD(nCustomId) + pNMUpDown->iDelta;
if( nNewCustomId < MIN_EMB_CUSTOM_ID)
{
nNewCustomId = MIN_EMB_CUSTOM_ID;
}
if( nNewCustomId > MAX_EMB_CUSTOM_ID)
{
nNewCustomId = MAX_EMB_CUSTOM_ID;
}
m_spinCustomId.SetPos( nNewCustomId );
m_pPattern->SetEmbellishment( 0, EMB_ALL, (BYTE)nNewCustomId );
}
}
*pResult = 1;
}
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
b31b67909a500246f4c3e972b4947bf2aea749ff | 961f6147855cb608eefd2ccb7927e65311133efa | /library/binsaver/ut/binsaver_ut.cpp | 20e4b45044a65ae5fd4efc22db00fcd35b755f8a | [
"Apache-2.0"
] | permissive | kyper999/catboost_yandex | 55a79890be28d46748cb4f55dd7a8ad24ab7b354 | 91c41df3d4997dbab57fc1b8a990017270da47c6 | refs/heads/master | 2022-10-31T11:21:22.438222 | 2017-07-18T10:25:29 | 2017-07-18T10:25:29 | 97,590,200 | 0 | 1 | NOASSERTION | 2022-10-23T09:35:09 | 2017-07-18T11:27:38 | C | UTF-8 | C++ | false | false | 5,563 | cpp | #include <library/binsaver/bin_saver.h>
#include <library/binsaver/util_stream_io.h>
#include <library/unittest/registar.h>
#include <util/stream/buffer.h>
#include <util/generic/map.h>
struct TBinarySerializable {
ui32 Data = 0;
};
struct TNonBinarySerializable {
ui32 Data = 0;
TString StrData;
};
struct TCustomSerializer {
ui32 Data = 0;
TString StrData;
SAVELOAD(StrData, Data);
};
struct TCustomOuterSerializer {
ui32 Data = 0;
TString StrData;
};
void operator & (TCustomOuterSerializer& s, IBinSaver& f);
struct TCustomOuterSerializerTmpl {
ui32 Data = 0;
TString StrData;
};
struct TCustomOuterSerializerTmplDerived : public TCustomOuterSerializerTmpl {
ui32 Data = 0;
TString StrData;
};
struct TMoveOnlyType {
ui32 Data = 0;
TMoveOnlyType() = default;
TMoveOnlyType(TMoveOnlyType&&) = default;
bool operator ==(const TMoveOnlyType& obj) const {
return Data == obj.Data;
}
};
struct TTypeWithArray {
ui32 Data = 1;
TString Array[2][2]{{"test", "data"}, {"and", "more"}};
SAVELOAD(Data, Array);
bool operator ==(const TTypeWithArray& obj) const {
return Data == obj.Data
&& std::equal(std::begin(Array[0]), std::end(Array[0]), obj.Array[0])
&& std::equal(std::begin(Array[1]), std::end(Array[1]), obj.Array[1]);
}
};
template<typename T, typename = std::enable_if_t<std::is_base_of<TCustomOuterSerializerTmpl, T>::value>>
int operator & (T& s, IBinSaver& f);
static bool operator==(const TBlob& l, const TBlob& r) {
return TStringBuf(~l, +l) == TStringBuf(~r, +r);
}
SIMPLE_UNIT_TEST_SUITE(BinSaver) {
SIMPLE_UNIT_TEST(HasTrivialSerializer) {
UNIT_ASSERT( !IBinSaver::HasNonTrivialSerializer<TBinarySerializable>(0u) );
UNIT_ASSERT( !IBinSaver::HasNonTrivialSerializer<TNonBinarySerializable>(0u) );
UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<TCustomSerializer>(0u) );
UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<TCustomOuterSerializer>(0u) );
UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<TCustomOuterSerializerTmpl>(0u) );
UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<TCustomOuterSerializerTmplDerived>(0u) );
UNIT_ASSERT( IBinSaver::HasNonTrivialSerializer<yvector<TCustomSerializer>>(0u) );
}
template<typename T>
void TestSerialization(const T& original) {
TBufferOutput out;
{
TYaStreamOutput yaOut(out);
IBinSaver f(yaOut, false, false);
f.Add(0, const_cast<T*>(&original));
}
TBufferInput in(out.Buffer());
T restored;
{
TYaStreamInput yaIn(in);
IBinSaver f(yaIn, true, false);
f.Add(0, &restored);
}
UNIT_ASSERT_EQUAL(original, restored);
}
SIMPLE_UNIT_TEST(TestStroka) {
TestSerialization(TString("QWERTY"));
}
SIMPLE_UNIT_TEST(TestMoveOnlyType) {
TestSerialization(TMoveOnlyType());
}
SIMPLE_UNIT_TEST(TestVectorStrok) {
TestSerialization(yvector<TString>{"A", "B", "C"});
}
SIMPLE_UNIT_TEST(TestCArray) {
TestSerialization(TTypeWithArray());
}
SIMPLE_UNIT_TEST(TestSets) {
TestSerialization(yhash_set<TString>{"A", "B", "C"});
TestSerialization(yset<TString>{"A", "B", "C"});
}
SIMPLE_UNIT_TEST(TestMaps) {
TestSerialization(yhash<TString, ui32>{{"A", 1}, {"B", 2}, {"C", 3}});
TestSerialization(ymap<TString, ui32>{{"A", 1}, {"B", 2}, {"C", 3}});
}
SIMPLE_UNIT_TEST(TestBlob) {
TestSerialization(TBlob::FromStringSingleThreaded("qwerty"));
}
SIMPLE_UNIT_TEST(TestPod) {
struct TPod {
ui32 A = 5;
ui64 B = 7;
bool operator == (const TPod& other) const {
return A == other.A && B == other.B;
}
};
TestSerialization(TPod());
TPod custom;
custom.A = 25;
custom.B = 37;
TestSerialization(custom);
TestSerialization(yvector<TPod>{ custom });
}
SIMPLE_UNIT_TEST(TestSubPod) {
struct TPod {
struct TSub {
ui32 X = 10;
bool operator == (const TSub& other) const {
return X == other.X;
}
};
yvector<TSub> B;
int operator & (IBinSaver& f) {
f.Add(0, &B);
return 0;
}
bool operator == (const TPod& other) const {
return B == other.B;
}
};
TestSerialization(TPod());
TPod::TSub sub;
sub.X = 1;
TPod custom;
custom.B = { sub };
TestSerialization(yvector<TPod>{ custom });
}
SIMPLE_UNIT_TEST(TestMemberAndOpIsMain) {
struct TBase {
TString S;
virtual int operator & (IBinSaver& f) {
f.Add(0, &S);
return 0;
}
virtual ~TBase() = default;
};
struct TDerived : public TBase {
int A = 0;
int operator & (IBinSaver& f) override {
f.Add(0, static_cast<TBase*>(this));
f.Add(0, &A);
return 0;
}
bool operator == (const TDerived& other) const {
return A == other.A && S == other.S;
}
};
TDerived obj;
obj.S = "TString";
obj.A = 42;
TestSerialization(obj);
}
};
| [
"exprmntr@pepe.search.yandex.net"
] | exprmntr@pepe.search.yandex.net |
3f0b05fa48c45733ac1251a4a7b2c9c5011829ff | 470f1ea0c29e3c2b3e039dd390ff308e2a3d64b6 | /homework/points2.cpp | 92057a46218063fb5f148fb77bbbc7201dec0e77 | [] | no_license | HOSHICHEN7267/1092CP2 | 655f81efd9281eb522d1c33f4168c855593a3b8c | c8cae852279269949141ba16ac714656ed5c24ac | refs/heads/master | 2023-06-07T18:54:29.435412 | 2021-06-22T06:22:42 | 2021-06-22T06:22:42 | 344,451,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp | #include <iostream>
#include <algorithm>
#define SIZE 10000
using namespace std;
int main(){
int num = 0;
int ans = 0;
float slope[SIZE] = {};
int points[SIZE][2] = {};
cin >> num;
for(int i = 0 ; i < num ; ++i){
cin >> points[i][0] >> points[i][1];
}
for(int i = 0 ; i < num ; ++i){
int cnt = 0;
int sum = 1;
for(int j = i + 1 ; j < num ; ++j){
if(i != j){
slope[cnt++] = (float)(points[i][1] - points[j][1]) / (float)(points[i][0] - points[j][0]);
}
}
sort(slope, slope + cnt);
for(int j = 0 ; j < cnt - 1 ; ++j){
if(slope[j] == slope[j+1]){
++sum;
}
else{
ans = max(ans, sum);
sum = 1;
}
}
}
cout << ans + 1 << '\n';
return 0;
}
| [
"antonychen5ds2@gmail.com"
] | antonychen5ds2@gmail.com |
58493d8bed5ecc0ae128aa4b5b0a1e1dec31af9b | 4da66ea2be83b62a46d77bf53f690b5146ac996d | /modules/assimp/assimp/code/CreateAnimMesh.cpp | 1a052849bb705597fcfab64c71d2d4430556b78a | [
"BSD-3-Clause",
"Zlib"
] | permissive | blitz-research/monkey2 | 620855b08b6f41b40ff328da71d2e0d05d943855 | 3f6be81d73388b800a39ee53acaa7f4a0c6a9f42 | refs/heads/develop | 2021-04-09T17:13:34.240441 | 2020-06-28T04:26:30 | 2020-06-28T04:26:30 | 53,753,109 | 146 | 76 | Zlib | 2019-09-07T21:28:05 | 2016-03-12T20:59:51 | Monkey | UTF-8 | C++ | false | false | 3,731 | cpp | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (C) 2016 The Qt Company Ltd.
Copyright (c) 2006-2012, assimp team
All rights reserved.
Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
---------------------------------------------------------------------------
*/
#include <assimp/CreateAnimMesh.h>
namespace Assimp {
aiAnimMesh *aiCreateAnimMesh(const aiMesh *mesh)
{
aiAnimMesh *animesh = new aiAnimMesh;
animesh->mVertices = NULL;
animesh->mNormals = NULL;
animesh->mTangents = NULL;
animesh->mBitangents = NULL;
animesh->mNumVertices = mesh->mNumVertices;
if (mesh->mVertices) {
animesh->mVertices = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mVertices, mesh->mVertices, mesh->mNumVertices * sizeof(aiVector3D));
}
if (mesh->mNormals) {
animesh->mNormals = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mNormals, mesh->mNormals, mesh->mNumVertices * sizeof(aiVector3D));
}
if (mesh->mTangents) {
animesh->mTangents = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mTangents, mesh->mTangents, mesh->mNumVertices * sizeof(aiVector3D));
}
if (mesh->mBitangents) {
animesh->mBitangents = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mBitangents, mesh->mBitangents, mesh->mNumVertices * sizeof(aiVector3D));
}
for (int i = 0; i < AI_MAX_NUMBER_OF_COLOR_SETS; ++i) {
if (mesh->mColors[i]) {
animesh->mColors[i] = new aiColor4D[animesh->mNumVertices];
std::memcpy(animesh->mColors[i], mesh->mColors[i], mesh->mNumVertices * sizeof(aiColor4D));
} else {
animesh->mColors[i] = NULL;
}
}
for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
if (mesh->mTextureCoords[i]) {
animesh->mTextureCoords[i] = new aiVector3D[animesh->mNumVertices];
std::memcpy(animesh->mTextureCoords[i], mesh->mTextureCoords[i], mesh->mNumVertices * sizeof(aiVector3D));
} else {
animesh->mTextureCoords[i] = NULL;
}
}
return animesh;
}
} // end of namespace Assimp
| [
"blitzmunter@gmail.com"
] | blitzmunter@gmail.com |
3e3f20f3a22598e0dd694d6fdc5fa0408a2c0552 | f2ae99a0fa0e73188f68e0b6d9d6e0c30a24367d | /기초알고리즘/2283_boj(동전1).cpp | 05d59ec23688faf139e06a20bf8e15687ebe9c91 | [] | no_license | kiseop91/Algorithm | 69181d57acfe7a3e7e4696eb215c693b53ef5bec | 4a62e85cce7db04c17c936bae2e885e8c237bc66 | refs/heads/master | 2020-04-10T03:13:17.389509 | 2019-07-18T08:36:21 | 2019-07-18T08:36:21 | 160,764,342 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | cpp | #include <cstdio>
int main() {
int n, k;
int coins[101];
int d[10001] = { 0 };
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; i++) {
scanf("%d", &coins[i]);
}
d[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
if (j >= coins[i]) {
d[j] += d[j - coins[i]];
}
}
}
printf("%d\n", d[k]);
return 0;
} | [
"kiseop91@naver.com"
] | kiseop91@naver.com |
455514f11af827e6fc36ff4b1e28c6611fd9521c | a3b3b096fc709a4519a8fc143ad864f936e72d06 | /examples/sqlite3_webquery/sqlite3_webquery.ino | 7180e291061be26964724400f4227da4214601e3 | [
"Apache-2.0"
] | permissive | minimum-necessary-change/esp_arduino_sqlite3_lib | baaf9712d6a6904abb61abf08c692f50d614226d | 2b94d624fdc43fe49e868a2d0932c88d914b9553 | refs/heads/master | 2020-04-25T10:37:35.241016 | 2019-06-24T08:11:08 | 2019-06-24T08:11:08 | 172,715,844 | 0 | 0 | Apache-2.0 | 2019-06-24T08:11:10 | 2019-02-26T13:22:43 | C | UTF-8 | C++ | false | false | 8,523 | ino | /*
This example shows how to retrieve data from Sqlite3 databases from SD Card
through the Web Server and display in the form of HTML page.
It also demonstrates query filtering by parameter passing and chunked encoding.
Before running please copy following files to SD Card:
examples/sqlite3_small_db/data/babyname.db
This database contains around 30000 baby names and corresponding data.
Also need to increase stack size in cores/esp8266/cont.h
to atleast 6144 (from 4096)
Please see https://github.com/siara-cc/esp_arduino_sqlite3_lib/
for more inforemation.
Copyright (c) 2018, Siara Logics (cc)
*/
/*
* Copyright (c) 2015, Majenko Technologies
* 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 Majenko Technologies nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <sqlite3.h>
#include <vfs.h>
#include <SPI.h>
const char *ssid = "Nokia1";
const char *password = "nokiafour";
ESP8266WebServer server ( 80 );
const int led = 13;
void handleRoot() {
digitalWrite ( led, 1 );
String temp;
int sec = millis() / 1000;
int min = sec / 60;
int hr = min / 60;
temp = "<html><head>\
<title>ESP8266 Demo</title>\
<style>\
body { font-family: Arial, Helvetica, Sans-Serif; font-size: large; Color: #000088; }\
</style>\
</head>\
<body>\
<h1>Hello from ESP8266!</h1>\
<h2>Query gendered names database</h2>\
<form name='params' method='GET' action='query_db'>\
Enter from: <input type=text style='font-size: large' value='Bob' name='from'/> \
<br>to: <input type=text style='font-size: large' value='Bobby' name='to'/> \
<br><br><input type=submit style='font-size: large' value='Query database'/>\
</form>\
</body>\
</html>";
server.send ( 200, "text/html", temp.c_str() );
digitalWrite ( led, 0 );
}
void handleNotFound() {
digitalWrite ( led, 1 );
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for ( uint8_t i = 0; i < server.args(); i++ ) {
message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
}
server.send ( 404, "text/plain", message );
digitalWrite ( led, 0 );
}
sqlite3 *db1;
int rc;
sqlite3_stmt *res;
int rec_count = 0;
const char *tail;
int openDb(const char *filename, sqlite3 **db) {
int rc = sqlite3_open(filename, db);
if (rc) {
Serial.printf("Can't open database: %s\n", sqlite3_errmsg(*db));
return rc;
} else {
Serial.printf("Opened database successfully\n");
}
return rc;
}
void setup ( void ) {
pinMode ( led, OUTPUT );
digitalWrite ( led, 0 );
Serial.begin ( 74880 );
WiFi.mode ( WIFI_STA );
WiFi.begin ( ssid, password );
Serial.println ( "" );
// Wait for connection
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
Serial.println ( "" );
Serial.print ( "Connected to " );
Serial.println ( ssid );
Serial.print ( "IP address: " );
Serial.println ( WiFi.localIP() );
if ( MDNS.begin ( "esp8266" ) ) {
Serial.println ( "MDNS responder started" );
}
SPI.begin();
vfs_mount("/SD0", SS);
sqlite3_initialize();
// Open database
if (openDb("/SD0/babyname.db", &db1))
return;
server.on ( "/", handleRoot );
server.on ( "/query_db", []() {
String sql = "Select count(*) from gendered_names where name between '";
sql += server.arg("from");
sql += "' and '";
sql += server.arg("to");
sql += "'";
rc = sqlite3_prepare_v2(db1, sql.c_str(), 1000, &res, &tail);
if (rc != SQLITE_OK) {
String resp = "Failed to fetch data: ";
resp += sqlite3_errmsg(db1);
resp += ".<br><br><input type=button onclick='location.href=\"/\"' value='back'/>";
server.send ( 200, "text/html", resp.c_str());
Serial.println(resp.c_str());
return;
}
while (sqlite3_step(res) == SQLITE_ROW) {
rec_count = sqlite3_column_int(res, 0);
if (rec_count > 5000) {
String resp = "Too many records: ";
resp += rec_count;
resp += ". Please select different range";
resp += ".<br><br><input type=button onclick='location.href=\"/\"' value='back'/>";
server.send ( 200, "text/html", resp.c_str());
Serial.println(resp.c_str());
sqlite3_finalize(res);
return;
}
}
sqlite3_finalize(res);
sql = "Select year, state, name, total_babies, primary_sex, primary_sex_ratio, per_100k_in_state from gendered_names where name between '";
sql += server.arg("from");
sql += "' and '";
sql += server.arg("to");
sql += "'";
rc = sqlite3_prepare_v2(db1, sql.c_str(), 1000, &res, &tail);
if (rc != SQLITE_OK) {
String resp = "Failed to fetch data: ";
resp += sqlite3_errmsg(db1);
resp += "<br><br><a href='/'>back</a>";
server.send ( 200, "text/html", resp.c_str());
Serial.println(resp.c_str());
return;
}
rec_count = 0;
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
String resp = "<html><head><title>ESP8266 Database query through web server</title>\
<style>\
body { font-family: Arial, Helvetica, Sans-Serif; font-size: large; Color: #000088; }\
</style><head><body><h1>ESP8266 Database query through web server</h1><h3>";
resp += sql;
resp += "</h3><table cellspacing='1' cellpadding='1' border='1'><tr><td>Year</td><td>State</td><td>Name</td><td>Total babies</td><td>Primary Sex</td><td>Ratio</td><td>Per 100k</td></tr>";
server.send ( 200, "text/html", resp.c_str());
while (sqlite3_step(res) == SQLITE_ROW) {
resp = "<tr><td>";
resp += sqlite3_column_int(res, 0);
resp += "</td><td>";
resp += (const char *) sqlite3_column_text(res, 1);
resp += "</td><td>";
resp += (const char *) sqlite3_column_text(res, 2);
resp += "</td><td>";
resp += sqlite3_column_int(res, 3);
resp += "</td><td>";
resp += (const char *) sqlite3_column_text(res, 4);
resp += "</td><td>";
resp += sqlite3_column_double(res, 5);
resp += "</td><td>";
resp += sqlite3_column_double(res, 6);
resp += "</td></tr>";
server.sendContent(resp);
rec_count++;
}
resp = "</table><br>Number of records: ";
resp += rec_count;
resp += ".<br><br><input type=button onclick='location.href=\"/\"' value='back'/>";
server.sendContent(resp);
sqlite3_finalize(res);
} );
server.onNotFound ( handleNotFound );
server.begin();
Serial.println ( "HTTP server started" );
}
void loop ( void ) {
server.handleClient();
} | [
"arun@siara.cc"
] | arun@siara.cc |
96d2a3d2f6c921b8d477df7390e7338e9a5deda9 | 106023d31ce8cd8db977b8f624a2c3fa1a2e0b25 | /src/rpc/mining.cpp | ff1d9afb999f63020345909a45f9a1c082e06b1b | [
"MIT"
] | permissive | aissty/rockcoin | 06345dc0d8b9056740692601300261a605345e71 | 75e15231d3b8cbf7532741f26f6f0e5a13c223e7 | refs/heads/master | 2021-01-25T09:53:59.781189 | 2018-03-04T19:25:28 | 2018-03-04T19:25:28 | 123,329,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,932 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "consensus/consensus.h"
#include "consensus/params.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "init.h"
#include "validation.h"
#include "miner.h"
#include "net.h"
#include "pow.h"
#include "rpc/server.h"
#include "txmempool.h"
#include "util.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#include <memory>
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include <boost/shared_ptr.hpp>
#include <univalue.h>
using namespace std;
/**
* Return average network hashes per second based on the last 'lookup' blocks,
* or from the last difficulty change if 'lookup' is nonpositive.
* If 'height' is nonnegative, compute the estimate at the time when a given block was found.
*/
UniValue GetNetworkHashPS(int lookup, int height) {
CBlockIndex *pb = chainActive.Tip();
if (height >= 0 && height < chainActive.Height())
pb = chainActive[height];
if (pb == NULL || !pb->nHeight)
return 0;
// If lookup is -1, then use blocks since last difficulty change.
if (lookup <= 0)
lookup = pb->nHeight % Params().GetConsensus().DifficultyAdjustmentInterval() + 1;
// If lookup is larger than chain, then set it to chain length.
if (lookup > pb->nHeight)
lookup = pb->nHeight;
CBlockIndex *pb0 = pb;
int64_t minTime = pb0->GetBlockTime();
int64_t maxTime = minTime;
for (int i = 0; i < lookup; i++) {
pb0 = pb0->pprev;
int64_t time = pb0->GetBlockTime();
minTime = std::min(time, minTime);
maxTime = std::max(time, maxTime);
}
// In case there's a situation where minTime == maxTime, we don't want a divide by zero exception.
if (minTime == maxTime)
return 0;
arith_uint256 workDiff = pb->nChainWork - pb0->nChainWork;
int64_t timeDiff = maxTime - minTime;
return workDiff.getdouble() / timeDiff;
}
UniValue getnetworkhashps(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 2)
throw runtime_error(
"getnetworkhashps ( nblocks height )\n"
"\nReturns the estimated network hashes per second based on the last n blocks.\n"
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n"
"Pass in [height] to estimate the network speed at the time when a certain block was found.\n"
"\nArguments:\n"
"1. nblocks (numeric, optional, default=120) The number of blocks, or -1 for blocks since last difficulty change.\n"
"2. height (numeric, optional, default=-1) To estimate at the time of the given height.\n"
"\nResult:\n"
"x (numeric) Hashes per second estimated\n"
"\nExamples:\n"
+ HelpExampleCli("getnetworkhashps", "")
+ HelpExampleRpc("getnetworkhashps", "")
);
LOCK(cs_main);
return GetNetworkHashPS(request.params.size() > 0 ? request.params[0].get_int() : 120, request.params.size() > 1 ? request.params[1].get_int() : -1);
}
UniValue generateBlocks(boost::shared_ptr<CReserveScript> coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
{
static const int nInnerLoopCount = 0x10000;
int nHeightStart = 0;
int nHeightEnd = 0;
int nHeight = 0;
{ // Don't keep cs_main locked
LOCK(cs_main);
nHeightStart = chainActive.Height();
nHeight = nHeightStart;
nHeightEnd = nHeightStart+nGenerate;
}
unsigned int nExtraNonce = 0;
UniValue blockHashes(UniValue::VARR);
while (nHeight < nHeightEnd)
{
std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript));
if (!pblocktemplate.get())
throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block");
CBlock *pblock = &pblocktemplate->block;
{
LOCK(cs_main);
IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce);
}
while (nMaxTries > 0 && pblock->nNonce < nInnerLoopCount && !CheckProofOfWork(pblock->GetPoWHash(), pblock->nBits, Params().GetConsensus())) {
++pblock->nNonce;
--nMaxTries;
}
if (nMaxTries == 0) {
break;
}
if (pblock->nNonce == nInnerLoopCount) {
continue;
}
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock);
if (!ProcessNewBlock(Params(), shared_pblock, true, NULL))
throw JSONRPCError(RPC_INTERNAL_ERROR, "ProcessNewBlock, block not accepted");
++nHeight;
blockHashes.push_back(pblock->GetHash().GetHex());
//mark script as important because it was used at least for one coinbase output if the script came from the wallet
if (keepScript)
{
coinbaseScript->KeepScript();
}
}
return blockHashes;
}
UniValue generate(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw runtime_error(
"generate nblocks ( maxtries )\n"
"\nMine up to nblocks blocks immediately (before the RPC call returns)\n"
"\nArguments:\n"
"1. nblocks (numeric, required) How many blocks are generated immediately.\n"
"2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
"\nResult:\n"
"[ blockhashes ] (array) hashes of blocks generated\n"
"\nExamples:\n"
"\nGenerate 11 blocks\n"
+ HelpExampleCli("generate", "11")
);
int nGenerate = request.params[0].get_int();
uint64_t nMaxTries = 1000000;
if (request.params.size() > 1) {
nMaxTries = request.params[1].get_int();
}
boost::shared_ptr<CReserveScript> coinbaseScript;
GetMainSignals().ScriptForMining(coinbaseScript);
// If the keypool is exhausted, no script is returned at all. Catch this.
if (!coinbaseScript)
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
//throw an error if no script was provided
if (coinbaseScript->reserveScript.empty())
throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available (mining requires a wallet)");
return generateBlocks(coinbaseScript, nGenerate, nMaxTries, true);
}
UniValue generatetoaddress(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
throw runtime_error(
"generatetoaddress nblocks address (maxtries)\n"
"\nMine blocks immediately to a specified address (before the RPC call returns)\n"
"\nArguments:\n"
"1. nblocks (numeric, required) How many blocks are generated immediately.\n"
"2. address (string, required) The address to send the newly generated rockcoin to.\n"
"3. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
"\nResult:\n"
"[ blockhashes ] (array) hashes of blocks generated\n"
"\nExamples:\n"
"\nGenerate 11 blocks to myaddress\n"
+ HelpExampleCli("generatetoaddress", "11 \"myaddress\"")
);
int nGenerate = request.params[0].get_int();
uint64_t nMaxTries = 1000000;
if (request.params.size() > 2) {
nMaxTries = request.params[2].get_int();
}
CBitcoinAddress address(request.params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address");
boost::shared_ptr<CReserveScript> coinbaseScript(new CReserveScript());
coinbaseScript->reserveScript = GetScriptForDestination(address.Get());
return generateBlocks(coinbaseScript, nGenerate, nMaxTries, false);
}
UniValue getmininginfo(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"\nReturns a json object containing mining-related information."
"\nResult:\n"
"{\n"
" \"blocks\": nnn, (numeric) The current block\n"
" \"currentblocksize\": nnn, (numeric) The last block size\n"
" \"currentblockweight\": nnn, (numeric) The last block weight\n"
" \"currentblocktx\": nnn, (numeric) The last block transaction\n"
" \"difficulty\": xxx.xxxxx (numeric) The current difficulty\n"
" \"errors\": \"...\" (string) Current errors\n"
" \"networkhashps\": nnn, (numeric) The network hashes per second\n"
" \"pooledtx\": n (numeric) The size of the mempool\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmininginfo", "")
+ HelpExampleRpc("getmininginfo", "")
);
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblockweight", (uint64_t)nLastBlockWeight));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("networkhashps", getnetworkhashps(request)));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("chain", Params().NetworkIDString()));
return obj;
}
// NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
UniValue prioritisetransaction(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 3)
throw runtime_error(
"prioritisetransaction <txid> <priority delta> <fee delta>\n"
"Accepts the transaction into mined blocks at a higher (or lower) priority\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id.\n"
"2. priority_delta (numeric, required) The priority to add or subtract.\n"
" The transaction selection algorithm considers the tx as it would have a higher priority.\n"
" (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n"
"3. fee_delta (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
" The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
" considers the transaction as it would have paid a higher (or lower) fee.\n"
"\nResult:\n"
"true (boolean) Returns true\n"
"\nExamples:\n"
+ HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
+ HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
);
LOCK(cs_main);
uint256 hash = ParseHashStr(request.params[0].get_str(), "txid");
CAmount nAmount = request.params[2].get_int64();
mempool.PrioritiseTransaction(hash, request.params[0].get_str(), request.params[1].get_real(), nAmount);
return true;
}
// NOTE: Assumes a conclusive result; if result is inconclusive, it must be handled by caller
static UniValue BIP22ValidationResult(const CValidationState& state)
{
if (state.IsValid())
return NullUniValue;
std::string strRejectReason = state.GetRejectReason();
if (state.IsError())
throw JSONRPCError(RPC_VERIFY_ERROR, strRejectReason);
if (state.IsInvalid())
{
if (strRejectReason.empty())
return "rejected";
return strRejectReason;
}
// Should be impossible
return "valid?";
}
std::string gbt_vb_name(const Consensus::DeploymentPos pos) {
const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
std::string s = vbinfo.name;
if (!vbinfo.gbt_force) {
s.insert(s.begin(), '!');
}
return s;
}
UniValue getblocktemplate(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() > 1)
throw runtime_error(
"getblocktemplate ( TemplateRequest )\n"
"\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n"
"It returns data needed to construct a block to work on.\n"
"For full specification, see BIPs 22, 23, 9, and 145:\n"
" https://github.com/bitcoin/bips/blob/master/bip-0022.mediawiki\n"
" https://github.com/bitcoin/bips/blob/master/bip-0023.mediawiki\n"
" https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n"
" https://github.com/bitcoin/bips/blob/master/bip-0145.mediawiki\n"
"\nArguments:\n"
"1. template_request (json object, optional) A json object in the following spec\n"
" {\n"
" \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n"
" \"capabilities\":[ (array, optional) A list of strings\n"
" \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n"
" ,...\n"
" ],\n"
" \"rules\":[ (array, optional) A list of strings\n"
" \"support\" (string) client side supported softfork deployment\n"
" ,...\n"
" ]\n"
" }\n"
"\n"
"\nResult:\n"
"{\n"
" \"version\" : n, (numeric) The preferred block version\n"
" \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n"
" \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n"
" \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n"
" ,...\n"
" },\n"
" \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n"
" \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n"
" \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n"
" {\n"
" \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n"
" \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n"
" \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n"
" \"depends\" : [ (array) array of numbers \n"
" n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n"
" ,...\n"
" ],\n"
" \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in Satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n"
" \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n"
" \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n"
" \"required\" : true|false (boolean) if provided and true, this transaction must be in the final block\n"
" }\n"
" ,...\n"
" ],\n"
" \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n"
" \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n"
" },\n"
" \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in Satoshis)\n"
" \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n"
" \"target\" : \"xxxx\", (string) The hash target\n"
" \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mutable\" : [ (array of string) list of ways the block template may be changed \n"
" \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n"
" ,...\n"
" ],\n"
" \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n"
" \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n"
" \"sizelimit\" : n, (numeric) limit of block size\n"
" \"weightlimit\" : n, (numeric) limit of block weight\n"
" \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n"
" \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n"
" \"height\" : n (numeric) The height of the next block\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblocktemplate", "")
+ HelpExampleRpc("getblocktemplate", "")
);
LOCK(cs_main);
std::string strMode = "template";
UniValue lpval = NullUniValue;
std::set<std::string> setClientRules;
int64_t nMaxVersionPreVB = -1;
if (request.params.size() > 0)
{
const UniValue& oparam = request.params[0].get_obj();
const UniValue& modeval = find_value(oparam, "mode");
if (modeval.isStr())
strMode = modeval.get_str();
else if (modeval.isNull())
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
lpval = find_value(oparam, "longpollid");
if (strMode == "proposal")
{
const UniValue& dataval = find_value(oparam, "data");
if (!dataval.isStr())
throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal");
CBlock block;
if (!DecodeHexBlk(block, dataval.get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
uint256 hash = block.GetHash();
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) {
CBlockIndex *pindex = mi->second;
if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
return "duplicate";
if (pindex->nStatus & BLOCK_FAILED_MASK)
return "duplicate-invalid";
return "duplicate-inconclusive";
}
CBlockIndex* const pindexPrev = chainActive.Tip();
// TestBlockValidity only supports blocks built on the current Tip
if (block.hashPrevBlock != pindexPrev->GetBlockHash())
return "inconclusive-not-best-prevblk";
CValidationState state;
TestBlockValidity(state, Params(), block, pindexPrev, false, true);
return BIP22ValidationResult(state);
}
const UniValue& aClientRules = find_value(oparam, "rules");
if (aClientRules.isArray()) {
for (unsigned int i = 0; i < aClientRules.size(); ++i) {
const UniValue& v = aClientRules[i];
setClientRules.insert(v.get_str());
}
} else {
// NOTE: It is important that this NOT be read if versionbits is supported
const UniValue& uvMaxVersion = find_value(oparam, "maxversion");
if (uvMaxVersion.isNum()) {
nMaxVersionPreVB = uvMaxVersion.get_int64();
}
}
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if(!g_connman)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0)
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "RockCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "RockCoin is downloading blocks...");
static unsigned int nTransactionsUpdatedLast;
if (!lpval.isNull())
{
// Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
uint256 hashWatchedChain;
boost::system_time checktxtime;
unsigned int nTransactionsUpdatedLastLP;
if (lpval.isStr())
{
// Format: <hashBestChain><nTransactionsUpdatedLast>
std::string lpstr = lpval.get_str();
hashWatchedChain.SetHex(lpstr.substr(0, 64));
nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
}
else
{
// NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
hashWatchedChain = chainActive.Tip()->GetBlockHash();
nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
}
// Release the wallet and main lock while waiting
LEAVE_CRITICAL_SECTION(cs_main);
{
checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);
boost::unique_lock<boost::mutex> lock(csBestBlock);
while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning())
{
if (!cvBlockChange.timed_wait(lock, checktxtime))
{
// Timeout: Check transactions for update
if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
break;
checktxtime += boost::posix_time::seconds(10);
}
}
}
ENTER_CRITICAL_SECTION(cs_main);
if (!IsRPCRunning())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
// TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
}
const struct BIP9DeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT];
// If the caller is indicating segwit support, then allow CreateNewBlock()
// to select witness transactions, after segwit activates (otherwise
// don't).
bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end();
// Update block
static CBlockIndex* pindexPrev;
static int64_t nStart;
static std::unique_ptr<CBlockTemplate> pblocktemplate;
// Cache whether the last invocation was with segwit support, to avoid returning
// a segwit-block to a non-segwit caller.
static bool fLastTemplateSupportsSegwit = true;
if (pindexPrev != chainActive.Tip() ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) ||
fLastTemplateSupportsSegwit != fSupportsSegwit)
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = nullptr;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = chainActive.Tip();
nStart = GetTime();
fLastTemplateSupportsSegwit = fSupportsSegwit;
// Create new block
CScript scriptDummy = CScript() << OP_TRUE;
pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, fSupportsSegwit);
if (!pblocktemplate)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
const Consensus::Params& consensusParams = Params().GetConsensus();
// Update nTime
UpdateTime(pblock, consensusParams, pindexPrev);
pblock->nNonce = 0;
// NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration
const bool fPreSegWit = (THRESHOLD_ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache));
UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal");
UniValue transactions(UniValue::VARR);
map<uint256, int64_t> setTxIndex;
int i = 0;
for (const auto& it : pblock->vtx) {
const CTransaction& tx = *it;
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase())
continue;
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("data", EncodeHexTx(tx)));
entry.push_back(Pair("txid", txHash.GetHex()));
entry.push_back(Pair("hash", tx.GetWitnessHash().GetHex()));
UniValue deps(UniValue::VARR);
BOOST_FOREACH (const CTxIn &in, tx.vin)
{
if (setTxIndex.count(in.prevout.hash))
deps.push_back(setTxIndex[in.prevout.hash]);
}
entry.push_back(Pair("depends", deps));
int index_in_template = i - 1;
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template];
if (fPreSegWit) {
assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0);
nTxSigOps /= WITNESS_SCALE_FACTOR;
}
entry.push_back(Pair("sigops", nTxSigOps));
entry.push_back(Pair("weight", GetTransactionWeight(tx)));
transactions.push_back(entry);
}
UniValue aux(UniValue::VOBJ);
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits);
UniValue aMutable(UniValue::VARR);
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
UniValue result(UniValue::VOBJ);
result.push_back(Pair("capabilities", aCaps));
UniValue aRules(UniValue::VARR);
UniValue vbavailable(UniValue::VOBJ);
for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) {
Consensus::DeploymentPos pos = Consensus::DeploymentPos(j);
ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache);
switch (state) {
case THRESHOLD_DEFINED:
case THRESHOLD_FAILED:
// Not exposed to GBT at all
break;
case THRESHOLD_LOCKED_IN:
// Ensure bit is set in block version
pblock->nVersion |= VersionBitsMask(consensusParams, pos);
// FALL THROUGH to get vbavailable set...
case THRESHOLD_STARTED:
{
const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
vbavailable.push_back(Pair(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit));
if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
if (!vbinfo.gbt_force) {
// If the client doesn't support this, don't indicate it in the [default] version
pblock->nVersion &= ~VersionBitsMask(consensusParams, pos);
}
}
break;
}
case THRESHOLD_ACTIVE:
{
// Add to rules only
const struct BIP9DeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos];
aRules.push_back(gbt_vb_name(pos));
if (setClientRules.find(vbinfo.name) == setClientRules.end()) {
// Not supported by the client; make sure it's safe to proceed
if (!vbinfo.gbt_force) {
// If we do anything other than throw an exception here, be sure version/force isn't sent to old clients
throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name));
}
}
break;
}
}
}
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("rules", aRules));
result.push_back(Pair("vbavailable", vbavailable));
result.push_back(Pair("vbrequired", int(0)));
if (nMaxVersionPreVB >= 2) {
// If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here
// Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks
// This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated
// Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated
aMutable.push_back("version/force");
}
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue));
result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST;
if (fPreSegWit) {
assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0);
nSigOpLimit /= WITNESS_SCALE_FACTOR;
}
result.push_back(Pair("sigoplimit", nSigOpLimit));
if (fPreSegWit) {
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_BASE_SIZE));
} else {
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SERIALIZED_SIZE));
result.push_back(Pair("weightlimit", (int64_t)MAX_BLOCK_WEIGHT));
}
result.push_back(Pair("curtime", pblock->GetBlockTime()));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) {
result.push_back(Pair("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())));
}
return result;
}
class submitblock_StateCatcher : public CValidationInterface
{
public:
uint256 hash;
bool found;
CValidationState state;
submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
protected:
virtual void BlockChecked(const CBlock& block, const CValidationState& stateIn) {
if (block.GetHash() != hash)
return;
found = true;
state = stateIn;
}
};
UniValue submitblock(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw runtime_error(
"submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
"\nAttempts to submit new block to network.\n"
"The 'jsonparametersobject' parameter is currently ignored.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"
"\nArguments\n"
"1. \"hexdata\" (string, required) the hex-encoded block data to submit\n"
"2. \"parameters\" (string, optional) object of optional parameters\n"
" {\n"
" \"workid\" : \"id\" (string, optional) if the server provided a workid, it MUST be included with submissions\n"
" }\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("submitblock", "\"mydata\"")
+ HelpExampleRpc("submitblock", "\"mydata\"")
);
std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
CBlock& block = *blockptr;
if (!DecodeHexBlk(block, request.params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
}
uint256 hash = block.GetHash();
bool fBlockPresent = false;
{
LOCK(cs_main);
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) {
CBlockIndex *pindex = mi->second;
if (pindex->IsValid(BLOCK_VALID_SCRIPTS))
return "duplicate";
if (pindex->nStatus & BLOCK_FAILED_MASK)
return "duplicate-invalid";
// Otherwise, we might only have the header - process the block before returning
fBlockPresent = true;
}
}
{
LOCK(cs_main);
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi != mapBlockIndex.end()) {
UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
}
}
submitblock_StateCatcher sc(block.GetHash());
RegisterValidationInterface(&sc);
bool fAccepted = ProcessNewBlock(Params(), blockptr, true, NULL);
UnregisterValidationInterface(&sc);
if (fBlockPresent)
{
if (fAccepted && !sc.found)
return "duplicate-inconclusive";
return "duplicate";
}
if (!sc.found)
return "inconclusive";
return BIP22ValidationResult(sc.state);
}
UniValue estimatefee(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"estimatefee nblocks\n"
"\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
"confirmation within nblocks blocks. Uses virtual transaction size of transaction\n"
"as defined in BIP 141 (witness data is discounted).\n"
"\nArguments:\n"
"1. nblocks (numeric, required)\n"
"\nResult:\n"
"n (numeric) estimated fee-per-kilobyte\n"
"\n"
"A negative value is returned if not enough transactions and blocks\n"
"have been observed to make an estimate.\n"
"-1 is always returned for nblocks == 1 as it is impossible to calculate\n"
"a fee that is high enough to get reliably included in the next block.\n"
"\nExample:\n"
+ HelpExampleCli("estimatefee", "6")
);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM));
int nBlocks = request.params[0].get_int();
if (nBlocks < 1)
nBlocks = 1;
CFeeRate feeRate = mempool.estimateFee(nBlocks);
if (feeRate == CFeeRate(0))
return -1.0;
return ValueFromAmount(feeRate.GetFeePerK());
}
UniValue estimatepriority(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"estimatepriority nblocks\n"
"\nDEPRECATED. Estimates the approximate priority a zero-fee transaction needs to begin\n"
"confirmation within nblocks blocks.\n"
"\nArguments:\n"
"1. nblocks (numeric, required)\n"
"\nResult:\n"
"n (numeric) estimated priority\n"
"\n"
"A negative value is returned if not enough transactions and blocks\n"
"have been observed to make an estimate.\n"
"\nExample:\n"
+ HelpExampleCli("estimatepriority", "6")
);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM));
int nBlocks = request.params[0].get_int();
if (nBlocks < 1)
nBlocks = 1;
return mempool.estimatePriority(nBlocks);
}
UniValue estimatesmartfee(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"estimatesmartfee nblocks\n"
"\nWARNING: This interface is unstable and may disappear or change!\n"
"\nEstimates the approximate fee per kilobyte needed for a transaction to begin\n"
"confirmation within nblocks blocks if possible and return the number of blocks\n"
"for which the estimate is valid. Uses virtual transaction size as defined\n"
"in BIP 141 (witness data is discounted).\n"
"\nArguments:\n"
"1. nblocks (numeric)\n"
"\nResult:\n"
"{\n"
" \"feerate\" : x.x, (numeric) estimate fee-per-kilobyte (in RKC)\n"
" \"blocks\" : n (numeric) block number where estimate was found\n"
"}\n"
"\n"
"A negative value is returned if not enough transactions and blocks\n"
"have been observed to make an estimate for any number of blocks.\n"
"However it will not return a value below the mempool reject fee.\n"
"\nExample:\n"
+ HelpExampleCli("estimatesmartfee", "6")
);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM));
int nBlocks = request.params[0].get_int();
UniValue result(UniValue::VOBJ);
int answerFound;
CFeeRate feeRate = mempool.estimateSmartFee(nBlocks, &answerFound);
result.push_back(Pair("feerate", feeRate == CFeeRate(0) ? -1.0 : ValueFromAmount(feeRate.GetFeePerK())));
result.push_back(Pair("blocks", answerFound));
return result;
}
UniValue estimatesmartpriority(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 1)
throw runtime_error(
"estimatesmartpriority nblocks\n"
"\nDEPRECATED. WARNING: This interface is unstable and may disappear or change!\n"
"\nEstimates the approximate priority a zero-fee transaction needs to begin\n"
"confirmation within nblocks blocks if possible and return the number of blocks\n"
"for which the estimate is valid.\n"
"\nArguments:\n"
"1. nblocks (numeric, required)\n"
"\nResult:\n"
"{\n"
" \"priority\" : x.x, (numeric) estimated priority\n"
" \"blocks\" : n (numeric) block number where estimate was found\n"
"}\n"
"\n"
"A negative value is returned if not enough transactions and blocks\n"
"have been observed to make an estimate for any number of blocks.\n"
"However if the mempool reject fee is set it will return 1e9 * MAX_MONEY.\n"
"\nExample:\n"
+ HelpExampleCli("estimatesmartpriority", "6")
);
RPCTypeCheck(request.params, boost::assign::list_of(UniValue::VNUM));
int nBlocks = request.params[0].get_int();
UniValue result(UniValue::VOBJ);
int answerFound;
double priority = mempool.estimateSmartPriority(nBlocks, &answerFound);
result.push_back(Pair("priority", priority));
result.push_back(Pair("blocks", answerFound));
return result;
}
static const CRPCCommand commands[] =
{ // category name actor (function) okSafeMode
// --------------------- ------------------------ ----------------------- ----------
{ "mining", "getnetworkhashps", &getnetworkhashps, true, {"nblocks","height"} },
{ "mining", "getmininginfo", &getmininginfo, true, {} },
{ "mining", "prioritisetransaction", &prioritisetransaction, true, {"txid","priority_delta","fee_delta"} },
{ "mining", "getblocktemplate", &getblocktemplate, true, {"template_request"} },
{ "mining", "submitblock", &submitblock, true, {"hexdata","parameters"} },
{ "generating", "generate", &generate, true, {"nblocks","maxtries"} },
{ "generating", "generatetoaddress", &generatetoaddress, true, {"nblocks","address","maxtries"} },
{ "util", "estimatefee", &estimatefee, true, {"nblocks"} },
{ "util", "estimatepriority", &estimatepriority, true, {"nblocks"} },
{ "util", "estimatesmartfee", &estimatesmartfee, true, {"nblocks"} },
{ "util", "estimatesmartpriority", &estimatesmartpriority, true, {"nblocks"} },
};
void RegisterMiningRPCCommands(CRPCTable &t)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| [
"aissty@qq.com"
] | aissty@qq.com |
47c52f62c32dabd6b2804693f66fdfdd707b6fc7 | c6881dbb2cb0aea8ac39c809aa5d339c9e15ac09 | /Blockchain/nameclaim.cpp | 37a2ae949f27d126a29dd3d7b55cc86da074e52c | [] | no_license | HungMingWu/blockchain-demo | d62afbe6caf41f07b7896f312fd9a2a7e27280c7 | ebe6e079606fe2fe7bf03783d66300df7a94d5be | refs/heads/master | 2020-03-21T22:33:38.664567 | 2018-10-01T10:12:40 | 2018-10-01T10:12:40 | 139,134,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,046 | cpp | #include "nameclaim.h"
#include "hash.h"
#include "util.h"
#include "Log.h"
#include <string>
using namespace std;
std::vector<unsigned char> uint32_t_to_vch(uint32_t n)
{
std::vector<unsigned char> vchN;
vchN.resize(4);
vchN[0] = n >> 24;
vchN[1] = n >> 16;
vchN[2] = n >> 8;
vchN[3] = n;
return vchN;
}
uint32_t vch_to_uint32_t(std::vector<unsigned char>& vchN)
{
uint32_t n;
if (vchN.size() != 4)
{
LOG_INFO("%s() : a vector<unsigned char> with size other than 4 has been given", __func__);
return 0;
}
n = vchN[0] << 24 | vchN[1] << 16 | vchN[2] << 8 | vchN[3];
return n;
}
CScript ClaimNameScript(std::string name, std::string value)
{
std::vector<unsigned char> vchName(name.begin(), name.end());
std::vector<unsigned char> vchValue(value.begin(), value.end());
return CScript() << OP_CLAIM_NAME << vchName << vchValue << OP_2DROP << OP_DROP << OP_TRUE;
}
CScript SupportClaimScript(std::string name, uint160 claimId)
{
std::vector<unsigned char> vchName(name.begin(), name.end());
std::vector<unsigned char> vchClaimId(claimId.begin(),claimId.end());
return CScript() << OP_SUPPORT_CLAIM << vchName << vchClaimId << OP_2DROP << OP_DROP << OP_TRUE;
}
CScript UpdateClaimScript(std::string name, uint160 claimId, std::string value)
{
std::vector<unsigned char> vchName(name.begin(), name.end());
std::vector<unsigned char> vchClaimId(claimId.begin(),claimId.end());
std::vector<unsigned char> vchValue(value.begin(), value.end());
return CScript() << OP_UPDATE_CLAIM << vchName << vchClaimId << vchValue << OP_2DROP << OP_2DROP << OP_TRUE;
}
bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams)
{
CScript::const_iterator pc = scriptIn.begin();
return DecodeClaimScript(scriptIn, op, vvchParams, pc);
}
bool DecodeClaimScript(const CScript& scriptIn, int& op, std::vector<std::vector<unsigned char> >& vvchParams, CScript::const_iterator& pc)
{
opcodetype opcode;
if (!scriptIn.GetOp(pc, opcode))
{
return false;
}
if (opcode != OP_CLAIM_NAME && opcode != OP_SUPPORT_CLAIM && opcode != OP_UPDATE_CLAIM)
{
return false;
}
op = opcode;
std::vector<unsigned char> vchParam1;
std::vector<unsigned char> vchParam2;
std::vector<unsigned char> vchParam3;
// Valid formats:
// OP_CLAIM_NAME vchName vchValue OP_2DROP OP_DROP pubkeyscript
// OP_UPDATE_CLAIM vchName vchClaimId vchValue OP_2DROP OP_2DROP pubkeyscript
// OP_SUPPORT_CLAIM vchName vchClaimId OP_2DROP OP_DROP pubkeyscript
// All others are invalid.
if (!scriptIn.GetOp(pc, opcode, vchParam1) || opcode < 0 || opcode > OP_PUSHDATA4)
{
return false;
}
if (!scriptIn.GetOp(pc, opcode, vchParam2) || opcode < 0 || opcode > OP_PUSHDATA4)
{
return false;
}
if (op == OP_UPDATE_CLAIM || op == OP_SUPPORT_CLAIM)
{
if (vchParam2.size() != 160/8)
{
return false;
}
}
if (op == OP_UPDATE_CLAIM)
{
if (!scriptIn.GetOp(pc, opcode, vchParam3) || opcode < 0 || opcode > OP_PUSHDATA4)
{
return false;
}
}
if (!scriptIn.GetOp(pc, opcode) || opcode != OP_2DROP)
{
return false;
}
if (!scriptIn.GetOp(pc, opcode))
{
return false;
}
if ((op == OP_CLAIM_NAME || op == OP_SUPPORT_CLAIM) && opcode != OP_DROP)
{
return false;
}
else if ((op == OP_UPDATE_CLAIM) && opcode != OP_2DROP)
{
return false;
}
vvchParams.push_back(vchParam1);
vvchParams.push_back(vchParam2);
if (op == OP_UPDATE_CLAIM)
{
vvchParams.push_back(vchParam3);
}
return true;
}
uint160 ClaimIdHash(const uint256& txhash, uint32_t nOut)
{
std::vector<unsigned char> claimToHash(txhash.begin(), txhash.end());
std::vector<unsigned char> vchnOut = uint32_t_to_vch(nOut);
claimToHash.insert(claimToHash.end(), vchnOut.begin(), vchnOut.end());
return Hash160(claimToHash);
}
CScript StripClaimScriptPrefix(const CScript& scriptIn)
{
int op;
return StripClaimScriptPrefix(scriptIn, op);
}
CScript StripClaimScriptPrefix(const CScript& scriptIn, int& op)
{
std::vector<std::vector<unsigned char> > vvchParams;
CScript::const_iterator pc = scriptIn.begin();
if (!DecodeClaimScript(scriptIn, op, vvchParams, pc))
{
return scriptIn;
}
return CScript(pc, scriptIn.end());
}
size_t ClaimScriptSize(const CScript& scriptIn)
{
CScript strippedScript = StripClaimScriptPrefix(scriptIn);
return scriptIn.size() - strippedScript.size();
}
size_t ClaimNameSize(const CScript& scriptIn)
{
std::vector<std::vector<unsigned char> > vvchParams;
CScript::const_iterator pc = scriptIn.begin();
int op;
if (!DecodeClaimScript(scriptIn, op, vvchParams, pc))
{
return 0;
}
else
{
return vvchParams[0].size();
}
}
| [
"u9089000@gmail.com"
] | u9089000@gmail.com |
5b0b66aed7ff6b3f5191221a850fbc4d11ee6035 | 5474747cb6ec8f0fe72b4d6320ff51e04e35946e | /training/Source.cpp | be3ef3091d6f42d6cbb8bbc798b94071b279d9f6 | [] | no_license | SergeyShopik/Cpp_Warehouse_Managament | 50dd84bfe1621f7e5001304afa50a3517693c0a3 | bf9d15c55e00854df9283b2a57aca3c2676dcc11 | refs/heads/master | 2023-01-27T22:56:58.547499 | 2020-12-11T19:36:42 | 2020-12-11T19:36:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,938 | cpp | #include<iostream>
#include<cctype>
#include<cstring>
#include<cstdlib>
const int SIZE = 100;
//warehouse managament
struct inv_type
{
char item[40];
double cost, retail;
int on_hand, lead_time;
} invtry[SIZE];
void init_list();
int menu();
void input(int);
void enter();
void update();
void display();
void find();
void showFound(int);
int main()
{
int n = 0;
//warehouse managament
char choice;
init_list();
for ( ; ; )
{
choice = menu();
switch (choice)
{
case 'e': enter();
break;
case 'd': display();
break;
case 'u': update();
break;
case 'f': find();
break;
case 's': showFound(n);
break;
case 'q': return 0;
}
}
system("pause");
return 0;
}
void init_list()
{
for (int i = 0; i < SIZE; i++) *invtry[i].item = '\0';
}
int menu()
{
char ch;
std::cout << '\n';
do
{
std::cout << "(E)nter\n";
std::cout << "(D)isplay\n";
std::cout << "(U)pdate\n";
std::cout << "(F)ind\n";
std::cout << "(S)how\n";
std::cout << "(Q)uit\n\n";
std::cout << "Choose comand: ";
std::cin >> ch;
} while (!strchr("edufsq", tolower(ch)));
return tolower(ch);
}
void input(int i)
{
std::cout << "Good: ";
std::cin >> invtry[i].item;
std::cout << "Cost: ";
std::cin >> invtry[i].cost;
std::cout << "Price: ";
std::cin >> invtry[i].retail;
std::cout << "Stock: ";
std::cin >> invtry[i].on_hand;
std::cout << "Lead time: ";
std::cin >> invtry[i].lead_time;
}
void enter()
{
int i;
for (i = 0; i < SIZE; i++)
if (!*invtry[i].item) break;
if (i == SIZE)
{
std::cout << "List is full.\n";
return;
}
input(i);
}
void update()
{
int i;
char name[80];
std::cout << "Enter good's name: ";
std::cin >> name;
for (i = 0; i < SIZE; i++)
if (!strcmp(name, invtry[i].item)) break;
if (i == SIZE)
{
std::wcout << "Good is not found.\n";
return;
}
std::cout << "Enter new info.\n";
input(i);
}
void display()
{
int i;
for (i = 0; i < SIZE; i++)
{
if (*invtry[i].item)
{
std::cout << invtry[i].item << '\n';
std::cout << "Cost: $" << invtry[i].cost;
std::cout << "\nPrice: $";
std::cout << invtry[i].retail;
std::cout << "\nStock: " << invtry[i].on_hand;
std::cout << "\nLead time remaining: ";
std::cout << invtry[i].lead_time << " days\n\n";
}
}
}
void find()
{
int i;
char name[80];
std::cout << "Enter good's name: ";
std::cin >> name;
for (i = 0; i < SIZE; i++)
if (!strcmp(name, invtry[i].item)) break;
if (i == SIZE)
{
std::cout << "Good is not found.\n";
return;
}
std::cout << "Enter new info.\n";
showFound(i);
}
void showFound(int i)
{
for (i = 0; i < SIZE; i++)
{
if (*invtry[i].item)
{
std::cout << invtry[i].item << '\n';
std::cout << "Cost: $" << invtry[i].cost;
std::cout << "\nPrice: $";
std::cout << invtry[i].retail;
std::cout << "\nStock: " << invtry[i].on_hand;
std::cout << "\nLead time remaining: ";
std::cout << invtry[i].lead_time << " days\n\n";
}
}
}
| [
"sergey.shopik101@gmail.com"
] | sergey.shopik101@gmail.com |
d6a6819b69fe3a6bb68a0208cf37c4afd9fb06a4 | eef9cdafb7476427d194374cc11a54a068c30325 | /overallControl.cpp | 61bd3e32b26c32e93d61056c0605554b2396ebdb | [] | no_license | geetika016/FindMeAPet | 3988ecbb87fa0c92c2424f8b628d741cf99810b6 | 43a7dcceb1c01a170d3101c30017a541df89b02b | refs/heads/master | 2020-06-20T09:43:33.569960 | 2019-07-15T22:44:58 | 2019-07-15T22:44:58 | 197,078,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,316 | cpp | #include "overallControl.h"
OverAllControl::OverAllControl()
{
proxy = new Proxy;
}
OverAllControl::~OverAllControl()
{
delete proxy;
}
void OverAllControl::launch()
{
dbControl = new DatabaseControl;
if (initializeDB())
proxy->displayRequest();
}
void OverAllControl::initializeHelper(QHash<QString, QString> &hash, QString *fields, QString *data, int size, QString table)
{
for(int i=0; i<size ;i++)
hash[fields[i]] = data[i];
QString errMsg;
DBSettings settings;
settings.table = table;
if (!dbControl->dbRequest(&hash, NULL, &settings, WRITE, &errMsg))
QMessageBox::critical(NULL,
QObject::tr("Database error"),
errMsg);
hash.clear();
}
bool OverAllControl::initializeDB()
{
if (!dbControl->openDB("cuACS_DB"))
return false;
bool hasTable;
DBSettings settings;//dummy, used when setting fields
QHash<QString, QString> input;
input["results"] = "(matching_id integer not null primary key, "
"client_id integer not null, "
"client_name varchar not null,"
"total_score_client_get float not null, "
"animal_id integer not null, "
"animal_name varchar not null, "
"total_score_animal_get float not null,"
"details char(4) default 'More', "
"type_afc varchar,"
"breed_afc varchar,"
"gender_afc varchar, "
"size_afc varchar, "
"age_afc varchar,"
"weight_afc double,"
"expected_life_span_afc varchar,"
"colour_afc varchar,"
"coat_pattern_afc varchar,"
"coat_length_afc varchar, "
"coat_layers_afc varchar,"
"shedding_afc varchar default null,"
"hypoallergenic_afc varchar,"
"good_new_owners_afc varchar,"
"good_with_being_alone_afc varchar,"
"kid_friendly_afc varchar,"
"vocality_afc varchar,"
"trainability_afc varchar,"
"playful_afc varchar,"
"energetic_afc varchar,"
"intelligence_afc varchar,"
"good_other_pets_afc varchar default null,"
"affection_owner_afc varchar,"
"affection_family_afc varchar,"
"affection_stranger_afc varchar,"
"budget_afc double,"
"special_needs_afc varchar,"
"dietary_afc varchar,"
"vet_visits_afc varchar,"
"grooming_afc varchar,"
"weather_afc varchar,"
"attention_afc varchar,"
"exercise_afc varchar,"
"space_afc varchar default null,"
"independent_afc varchar default null,"
"social_afc varchar default null,"
"pair_afc varchar default null,"
"interactive_afc varchar default null,"
"temperament_afc varchar default null,"
"tamed_afc varchar default null,"
"sensitivity_afc varchar default null,"
"nocturnal_afc varchar default null,"
"feeding_afc varchar default null,"
"cleaning_afc varchar default null,"////////
"space_cfa varchar,"
"weather_cfa varchar,"
"at_home_mostly_cfa varchar,"
"allergies_cfa varchar,"
"pair_cfa varchar,"
"first_pet_cfa varchar,"
"kids_cfa varchar,"
"budget_cfa double,"
"breed_cfa varchar,"
"gender_cfa varchar,"
"size_cfa varchar,"
"age_cfa varchar,"
"colour_cfa varchar,"
"shedding_cfa varchar,"
"grooming_cfa varchar,"
"dietary_needs_cfa varchar,"
"special_needs_cfa varchar,"
"vet_visits_cfa varchar,"
"other_pets_cfa varchar,"
"attention_cfa varchar,"
"energetic_cfa varchar,"
"trainability_cfa varchar,"
"intelligence_cfa varchar,"
"exercise_cfa varchar,"
"vocality_cfa varchar,"
"playful_cfa varchar,"
"affection_owner_cfa varchar,"
"affection_family_cfa varchar,"
"affection_stranger_cfa varchar)";
if(!dbControl->dbRequest(&input, NULL, &settings, CREATE_TABLE, NULL))
QMessageBox::critical(NULL, "Database Error", "Fail to create table");
input.clear();
input["users"] = "(id integer not null primary key autoincrement, "
"username varchar not null unique, "
"password varchar not null, "
"role varchar not null)";
if(!dbControl->dbRequest(&input, &hasTable, &settings, CREATE_TABLE, NULL))
QMessageBox::critical(NULL, "Database Error", "Fail to create table");
//hasTable = true;
input.clear();
if(!hasTable)
{
QString usersFields[4] = {"id", "username", "password", "role"};
QString usersData1[4] = {"1","Joe", "joe", "client"};
QString usersData2[4] = {"2","Lars", "lars", "client"};
QString usersData3[4] = {"3","Leo", "leo", "client"};
QString usersData4[4] = {"4","Lora", "lora", "client"};
QString usersData5[4] = {"5","Jacob", "jacob", "client"};
QString usersData6[4] = {"6","Jonathan", "jonathan", "client"};
QString usersData7[4] = {"7","Sam", "sam", "client"};
QString usersData8[4] = {"8","Tony", "tony", "client"};
QString usersData9[4] = {"9","Chandler", "chandler", "client"};
QString usersData10[4] = {"10","Monica", "monica", "client"};
QString usersData11[4] = {"11","Rachel", "rachel", "client"};
QString usersData12[4] = {"12","Phoebe", "phoebe", "client"};
QString usersData13[4] = {"13","Sammie", "sammie", "client"};
QString usersData14[4] = {"14","Charles", "charles", "client"};
QString usersData15[4] = {"15","Chen", "chen", "client"};
QString usersData16[4] = {"16","Jamaica", "jamaica", "client"};
QString usersData17[4] = {"17","Sally", "sally", "client"};
QString usersData18[4] = {"18","Jonas", "jonas", "client"};
QString usersData19[4] = {"19","Joseph", "joseph", "client"};
QString usersData20[4] = {"20","Lily", "lily", "client"};
QString staffData1[4] = {"21","matilda23", "matilda23", "staff"};
initializeHelper(input, usersFields, usersData1, 4, "users");
initializeHelper(input, usersFields, usersData2, 4, "users");
initializeHelper(input, usersFields, usersData3, 4, "users");
initializeHelper(input, usersFields, usersData4, 4, "users");
initializeHelper(input, usersFields, usersData5, 4, "users");
/*initializeHelper(input, usersFields, usersData6, 4, "users");
initializeHelper(input, usersFields, usersData7, 4, "users");
initializeHelper(input, usersFields, usersData8, 4, "users");
initializeHelper(input, usersFields, usersData9, 4, "users");
initializeHelper(input, usersFields, usersData10, 4, "users");
initializeHelper(input, usersFields, usersData11, 4, "users");
initializeHelper(input, usersFields, usersData12, 4, "users");
initializeHelper(input, usersFields, usersData13, 4, "users");
initializeHelper(input, usersFields, usersData14, 4, "users");
initializeHelper(input, usersFields, usersData15, 4, "users");
initializeHelper(input, usersFields, usersData16, 4, "users");
initializeHelper(input, usersFields, usersData17, 4, "users");
initializeHelper(input, usersFields, usersData18, 4, "users");
initializeHelper(input, usersFields, usersData19, 4, "users");
initializeHelper(input, usersFields, usersData20, 4, "users");*/
initializeHelper(input, usersFields, staffData1, 4, "users");
}
input["animals"] = "(id integer primary key ,"
"name varchar not null,"
"type varchar,"
"breed varchar,"
"gender varchar, "
"size integer, "
"age integer,"
"weight double,"
"expected_life_span varchar,"
"colour varchar,"
"coat_pattern varchar,"
"coat_length varchar, "
"coat_layers varchar,"
"shedding varchar default null,"
"hypoallergenic varchar,"
"good_new_owners varchar,"
"good_with_being_alone varchar,"
"kid_friendly varchar,"
"vocality varchar,"
"trainability varchar,"
"playful integer,"
"energetic integer,"
"intelligence integer,"
"good_other_pets varchar default null,"
"affection_owner integer,"
"affection_family integer,"
"affection_stranger integer,"
"budget double,"
"special_needs varchar,"
"dietary varchar,"
"vet_visits varchar,"
"grooming varchar,"
"weather varchar,"
"attention integer,"
"exercise integer,"
"space varchar default null,"
"independent integer default null,"
"social integer default null,"
"pair varchar default null,"
"interactive integer default null,"
"temperament varchar default null,"
"tamed varchar default null,"
"sensitivity integer default null,"
"nocturnal varchar default null,"
"feeding integer default null,"
"cleaning integer default null,"
"details char(4) default 'More')";
if(!dbControl->dbRequest(&input, &hasTable, &settings, CREATE_TABLE, NULL))
hasTable = true;
input.clear();
if(!hasTable)
{
QString dogFields[ATTRIBUTES_NUM_DOG] = {"name","type","breed","gender","size","age","weight","expected_life_span","colour","coat_length",
"coat_layers","shedding","hypoallergenic","good_new_owners","good_with_being_alone","kid_friendly","vocality",
"trainability","playful","energetic","intelligence","good_other_pets","affection_owner","affection_family",
"affection_stranger","budget","special_needs","dietary","vet_visits","grooming","weather","attention","exercise","space"};
QString dog_data1[ATTRIBUTES_NUM_DOG] = {"Pooh","Dog","Beagle","Female","Small","1","15","12-15","Brown","Short(less than 1 inch)",
"1-Layer","Infrequent","No","Yes","No","Yes","Likes to be vocal",
"Trained","4","4","4","DBHRG","5","5",
"3","700","Yes","No","Monthly","Once a week","Hot","3","5","SL"};
QString dog_data2[ATTRIBUTES_NUM_DOG]= {"Bowie","Dog","Siberian","Male","Large","7","89.6","11-14","Brown","Medium(1-3 inches)",
"1-Layer","Frequent","No","Yes","No","Yes","Likes to be vocal",
"Docile(easy to train)","5","5","5","DCBRHG","5","5",
"4","600","No","Yes","Every 2 months","Once a week","Moderate","5","5","L"};
QString dog_data3[ATTRIBUTES_NUM_DOG] = {"QTPie","Dog","Poodle","Female","Large","2","70.3","12-15","Grey","Medium(1-3 inches)",
"1-Layer","Regularly","Yes","No","No","Yes","Infrequent",
"Trained","4","3","4","DBC","5","4",
"4","1100","Yes","Yes","Half-Yearly","Daily","Moderate","4","4","SL"};
QString dog_data4[ATTRIBUTES_NUM_DOG] = {"Peirce","Dog","St. Bernard","Male","Large","3","93.2","13-16","White",
"Medium(1-3 inches)","2-Layer","Seasonal","Yes","No","Yes","Yes",
"Only when necessary","Trained","4","4","5","RD","4","4","3",
"1100","Yes","No","Half-Yearly","Daily","Cold","4","5","L"};
QString dog_data5[ATTRIBUTES_NUM_DOG] = {"Percy","Dog","St. Bernard","Male","Large","2","68.4","12-13","White",
"Medium(1-3 inches)","1-Layer","Regularly","No","No","No","No","Frequent",
"Agreeable","5","5","5","DGCBRH","5","5","3","600","No","Yes","Every 2 months",
"Daily","Moderate","5","5","L"};
QString dog_data6[ATTRIBUTES_NUM_DOG] = {"Jack","Dog","Alaskan Malamute","Male","Large","7","141.06","8-10","Brown",
"Short(less than 1 inch)","1-Layer","Frequent","Yes","Yes","No","Yes",
"Only when necessary","Trained","3","3","4","DC","4","4","4","1250","No",
"No","Monthly","2-3 times/week","Moderate","2","5","SL"};
QString dog_data7[ATTRIBUTES_NUM_DOG] = {"Walley","Dog","Pug","Female","Medium","8","68.4","12-15","White","Short(less than 1 inch",
"2-Layer","Regularly","No","No","Yes","Yes","Only when necessary",
"Trained","3","5","5","BHGC","5","4",
"2","1500","No","Yes","Yearly","Daily","Cold","5","5","L"};
QString dog_data8[ATTRIBUTES_NUM_DOG] = {"Shadow","Dog","German Shepherd","Male","Large","4","89.03","9-13","Black",
"Short(less than 1 inch)","1-Layer","Infrequent","Yes","No","No","Yes",
"Frequent","Trained","3","5","5","B","5","3","1","700","Yes","No",
"Half-Yearly","Once a week","Moderate","2","4","L" };
QString dog_data9[ATTRIBUTES_NUM_DOG] = {"Snowy","Dog","Pomeranian","Female","Small","6","7.8","12-18","White",
"Medium(1-3 inches)","1-Layer","Frequent","Yes","Yes","Yes","Yes",
"Likes to be Vocal","Docile(easy to train)","5","5","3",
"DBCH","5","5","4","900","No","No","Every 2 months","2-3 times/week",
"Moderate","4","4","ASL"};
QString dog_data10[ATTRIBUTES_NUM_DOG] = {"Bosco","Dog","German Shepherd","Female","Small","3","19.6","12-15","White","Short(less than 1 inch)",
"1-Layer","Infrequent","No","No","Yes","Yes","Only when necessary","Trained",
"5","3","2","CDGH","5","5","5","900","No","Yes","Half-Yearly",
"Once a week","Moderate","3","4","ASL"};
initializeHelper(input, dogFields, dog_data1, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data2, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data3, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data4, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data5, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data6, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data7, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data8, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data9, ATTRIBUTES_NUM_DOG, "animals");
initializeHelper(input, dogFields, dog_data10, ATTRIBUTES_NUM_DOG, "animals");
QString catFields[ATTRIBUTES_NUM_CAT] = {"name","type","breed","gender","size","age","weight","expected_life_span","colour","coat_length",
"coat_pattern","shedding","hypoallergenic","good_new_owners","kid_friendly","vocality",
"trainability","independent","playful","energetic","intelligence","good_other_pets","affection_owner","affection_family",
"affection_stranger","budget","special_needs","dietary","vet_visits","grooming","weather","attention","space","social","pair"};
QString cat_data1[ATTRIBUTES_NUM_CAT] = {"Murphy","Cat","Abyssinian","Female","Medium","3","15.0","6-8","White","Short(less than 1 inch)",
"Solid(1-Colour)","Infrequent","No","Yes","Yes","Infrequent",
"Docile","5","3","4","5","C","3","2",
"1","400","No","No","Half-Yearly","Once a week","Moderate","2","I","2","No"};
QString cat_data2[ATTRIBUTES_NUM_CAT] = {"Sky","Cat","American Curl","Female","Medium","3","18","2-8","White","Short(less than 1 inch)",
"Bi-colour","Infrequent","No","No","Yes","Infrequent",
"Independent","5","4","3","5","C","3","3",
"2","410","No","No","Half-Yearly","Once a week","Moderate","2","O","1","No"};
QString cat_data3[ATTRIBUTES_NUM_CAT] = {"Ivy","Cat","Persian","Female","Small","2","19","6-9","Golden Brown","Short(less than 1 inch)",
"Stripped Tabby","Frequent","No","Yes","No","Infrequent",
"Independent","5","5","5","5","C","3","2",
"1","500","No","No","Every 2 months","Once a week","Cold","2","IO","3","No"};
QString cat_data4[ATTRIBUTES_NUM_CAT] = {"Garfield","Cat","Siamese","Male","Medium","1","14","8-10","Grey","Medium(1-3 inches)",
"Solid(1-colour)","Regularly","No","No","Yes","Infrequent",
"Independent","5","2","5","5","C","3","3",
"2","600","No","No","Half-Yearly","Once a week","Hot","3","I","2","No"};
QString cat_data5[ATTRIBUTES_NUM_CAT] = {"Joana","Cat","Highlander","Female","Small","4","10","5-8","Chocolate Brown","Medium(1-3 inches)",
"Calico(3-colour)","Ocassional","No","Yes","No","Infrequent",
"Independent","5","5","5","5","C","3","3",
"2","450","No","No","Every 2 months","Once a week","Moderate","2","I","3","No"};
QString cat_data6[ATTRIBUTES_NUM_CAT] = {"Tom","Cat","Savannah","Male","Medium","2","8","6-9","Black","Medium(1-3 inches)",
"Tortoiseshell","Seasonal","No","No","Yes","Likes to be vocal",
"Independent","5","3","5","5","C","4","3",
"2","430","No","No","Half-Yearly","Once a week","Hot","3","O","2","No"};
initializeHelper(input, catFields, cat_data1, ATTRIBUTES_NUM_CAT, "animals");
initializeHelper(input, catFields, cat_data2, ATTRIBUTES_NUM_CAT, "animals");
initializeHelper(input, catFields, cat_data3, ATTRIBUTES_NUM_CAT, "animals");
initializeHelper(input, catFields, cat_data4, ATTRIBUTES_NUM_CAT, "animals");
initializeHelper(input, catFields, cat_data5, ATTRIBUTES_NUM_CAT, "animals");
initializeHelper(input, catFields, cat_data6, ATTRIBUTES_NUM_CAT, "animals");
QString birdFields[ATTRIBUTES_NUM_BIRD] = {"name","type","breed","gender","size","age","dietary","pair","weather","budget","colour","special_needs",
"vet_visits","expected_life_span","vocality","shedding","interactive","intelligence"};
QString bird_data1[ATTRIBUTES_NUM_BIRD] = {"Nancy","Bird","Dove","Female","Tiny","1","Yes","No","Hot","200","White",
"No","Yearly","4-8","Infrequent","Occationaly","4","3"};
QString bird_data2[ATTRIBUTES_NUM_BIRD] = {"Nona","Bird","Parrot","Female","Medium","2","Yes","No","Hot","150","Green","No",
"Yearly","3-8","Likes to be vocal","Occationaly","5","5"};
QString bird_data3[ATTRIBUTES_NUM_BIRD] = {"Meethu","Bird","Mynah","Female","Tiny","1","Yes","No","Hot","175","Blue","No",
"Yearly","4-7","Frequent","Occationaly","2","4"};
QString bird_data4[ATTRIBUTES_NUM_BIRD] = {"Stella","Bird","Conures","Female","Small","1","Yes","No","Hot","125","Blue","No",
"Yearly","2-6","Frequent","Occationaly","3","3"};
QString bird_data5[ATTRIBUTES_NUM_BIRD] = {"Gypsy","Bird","Canaries","Female","Tiny","2","Yes","No","Moderate","300","Yellow","No",
"Yearly","8-12","Frequent","Occationaly","3","4"};
initializeHelper(input, birdFields, bird_data1, ATTRIBUTES_NUM_BIRD, "animals");
initializeHelper(input, birdFields, bird_data2, ATTRIBUTES_NUM_BIRD, "animals");
initializeHelper(input, birdFields, bird_data3, ATTRIBUTES_NUM_BIRD, "animals");
initializeHelper(input, birdFields, bird_data4, ATTRIBUTES_NUM_BIRD, "animals");
initializeHelper(input, birdFields, bird_data5, ATTRIBUTES_NUM_BIRD, "animals");
QString rabbitFields[ATTRIBUTES_NUM_RABBIT] = {"name","type","gender","breed","colour","temperament","age","budget","expected_life_span","tamed",
"hypoallergenic","good_other_pets","social","sensitivity"};
QString rabbit_data1[ATTRIBUTES_NUM_RABBIT] = {"Stuart","Rabbit","Male","Lionhead","Brown","Docile","1","400","2-4","Yes",
"No","DCBRHG","3","3"};
QString rabbit_data2[ATTRIBUTES_NUM_RABBIT] = {"Ruby","Rabbit","Female","Angora","White","Calm","1","400","2-4","Yes",
"No","DCBRHG","5","5"};
initializeHelper(input, rabbitFields, rabbit_data1, ATTRIBUTES_NUM_RABBIT, "animals");
initializeHelper(input, rabbitFields, rabbit_data2, ATTRIBUTES_NUM_RABBIT, "animals");
QString hamsterFields[ATTRIBUTES_NUM_HAMSTER] = {"name","type","gender","breed","colour","age","budget","hypoallergenic",
"expected_life_span","nocturnal","tamed","social","attention","cleaning","feeding"};
QString hamster_data1[ATTRIBUTES_NUM_HAMSTER] = {"Joe","Hamster","Female","Syrian","Brown","1","200","Yes",
"1-3","Yes","Yes","5","5","4","4"};
initializeHelper(input, hamsterFields, hamster_data1, ATTRIBUTES_NUM_HAMSTER, "animals");
QString guineaPigFields[ATTRIBUTES_NUM_GUINEA_PIGS] = {"name","type","gender","breed","colour","age","budget","hypoallergenic",
"expected_life_span","tamed","social","attention","cleaning","feeding"};
QString guineaPig_data1[ATTRIBUTES_NUM_GUINEA_PIGS] = {"Jim","Guinea Pig","Female","Teddy","Chocolate","3","250","Yes",
"4-8","Yes","4","4","5","5"};
initializeHelper(input, guineaPigFields, guineaPig_data1, ATTRIBUTES_NUM_GUINEA_PIGS, "animals");
}
input["clients"] = "(id integer not null primary key autoincrement,"
"name varchar not null unique, "
"phone_number varchar not null, "
"email varchar not null,"
"animal_type varchar,"
"space varchar,"
"weather varchar,"
"at_home_mostly varchar,"
"allergies varchar,"
"first_pet varchar,"
"kids varchar,"
"budget double,"
"breed varchar,"
"gender varchar,"
"size varchar,"
"age varchar,"
"colour varchar,"
"shedding varchar,"
"grooming varchar,"
"dietary_needs varchar,"
"special_needs varchar,"
"vet_visits varchar,"
"coat_length varchar,"
"other_pets varchar,"
"attention integer,"
"energetic integer,"
"trainability integer,"
"intelligence integer,"
"exercise integer,"
"vocality integer,"
"playful integer,"
"affection_owner integer,"
"affection_family integer,"
"affection_stranger integer,"
"pair varchar,"
"coat_pattern varchar,"
"social integer,"
"independent integer,"
"interactive integer,"
"tamed varchar,"
"temperament integer,"
"sensitivity integer,"
"nocturnal varchar,"
"cleaning integer,"
"feeding integer,"
"details char(4) default 'More')";
if(!dbControl->dbRequest(&input, &hasTable, &settings, CREATE_TABLE, NULL))
hasTable = true;
input.clear();
if(!hasTable)
{
QString clientFields[ATTRIBUTES_NUM_CLIENT] = {"id","name","phone_number","email","animal_type","space",
"weather","at_home_mostly","allergies","first_pet","kids",
"budget","breed","gender","size","age","colour","shedding",
"grooming","dietary_needs","special_needs","vet_visits",
"other_pets","attention","energetic","trainability","intelligence",
"exercise", "vocality","playful","affection_owner",
"affection_family","affection_stranger"};
QString clientData1[ATTRIBUTES_NUM_CLIENT] = {"1","Joe", "3423629617", "joe682@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","Yes","Yes","Yes","600","German Shepherd","Male",
"Small","4","White","Infrequent","Daily",
"Yes","No","Monthly","HGD","4","3","2","4","2","4","3","2","4","2"};
QString clientData2[ATTRIBUTES_NUM_CLIENT] = {"4","Jonathan", "6473629897", "jonathan@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pomeranian","Female",
"Small","2","White","Infrequent","Daily",
"No","No","Monthly","RG","4","3","2","4","2","4","3","2","4","2"};
QString clientData3[ATTRIBUTES_NUM_CLIENT] = {"3","Leo", "3423678997", "samantha@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","Yes","Yes","No","600","Alaskan Malamute","Male",
"Small","1","White","Infrequent","Daily",
"No","Yes","Monthly","CBR","4","3","2","4","2","4","3","2","4","2"};
QString clientData4[ATTRIBUTES_NUM_CLIENT] = {"2","Lars", "3423629897", "jack482@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","6","White","Infrequent","Daily",
"Yes","Yes","Monthly","BC","4","3","2","4","2","4","3","2","4","2"};
QString clientData5[ATTRIBUTES_NUM_CLIENT] = {"5","Jacob", "7899629897", "joey@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","No","600","Alaskan Malamute","Male",
"Small","1","White","Infrequent","Daily",
"Yes","No","Monthly","BR","4","3","2","4","2","4","3","2","4","2"};
QString clientData6[ATTRIBUTES_NUM_CLIENT] = {"6","Lily", "3423629897", "lily@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","5","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData7[ATTRIBUTES_NUM_CLIENT] = {"7","Sam", "2133627897", "sam@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Labrador","Male",
"Small","6","White","Infrequent","Daily",
"Yes","Yes","Monthly","CRBD","4","3","2","4","2","4","3","2","4","2"};
QString clientData8[ATTRIBUTES_NUM_CLIENT] = {"8","Tony", "6893629851", "tony82@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Female",
"Small","3","White","Infrequent","Daily",
"Yes","Yes","Monthly","CBD","4","3","2","4","2","4","3","2","4","2"};
QString clientData9[ATTRIBUTES_NUM_CLIENT] = {"9","Chandler", "3424536298", "chandler16@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","5","White","Infrequent","Daily",
"Yes","Yes","Monthly","C","4","3","2","4","2","4","3","2","4","2"};
QString clientData10[ATTRIBUTES_NUM_CLIENT] = {"10","Monica", "3423629897", "monica2@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Female",
"Small","9","White","Infrequent","Daily",
"Yes","Yes","Monthly","CH","4","3","2","4","2","4","3","2","4","2"};
QString clientData11[ATTRIBUTES_NUM_CLIENT] = {"11","Rachel", "4563629897", "rachel482@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","2","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData12[ATTRIBUTES_NUM_CLIENT] = {"12","Phoebe", "3424536298", "phoebe482@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","4","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData13[ATTRIBUTES_NUM_CLIENT] = {"13","Sammie", "3423629897", "sammie2@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","5","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData14[ATTRIBUTES_NUM_CLIENT] = {"14","Charles", "3423629897", "charles3@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","1","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData15[ATTRIBUTES_NUM_CLIENT] = {"15","Chen", "3423629897", "chen7@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","7","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData16[ATTRIBUTES_NUM_CLIENT] = {"16","Jamaica", "3423629897", "jamaica32@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","7","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData17[ATTRIBUTES_NUM_CLIENT] = {"17","Sally", "3423629897", "sally@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","5","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData18[ATTRIBUTES_NUM_CLIENT] = {"18","Jonas", "3423629897", "jonas21@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","4","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData19[ATTRIBUTES_NUM_CLIENT] = {"19","Joseph", "3423629897", "joseph23@cmail.carleton.ca","Dog",
"Appartment","Hot","Yes","No","Yes","Yes","600","Pug","Male",
"Small","7","White","Infrequent","Daily",
"Yes","Yes","Monthly","CD","4","3","2","4","2","4","3","2","4","2"};
QString clientData20[ATTRIBUTES_NUM_CLIENT] = {"20","Lora", "6457629897", "samuel@cmail.carleton.ca","Cat",
"Appartment","Hot","Yes","No","Yes","No","600","Siamese","Male",
"Small","6","White","Infrequent","Daily",
"No","Yes","Monthly","DCBRHG","4","3","2","4","2","4","3","2","4","2"};
initializeHelper(input, clientFields, clientData1, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData2, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData3, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData4, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData5, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData6, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData7, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData8, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData9, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData10, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData11, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData12, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData13, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData14, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData15, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData16, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData17, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData18, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData19, ATTRIBUTES_NUM_CLIENT, "clients");
initializeHelper(input, clientFields, clientData20, ATTRIBUTES_NUM_CLIENT, "clients");
}
return true;
}
| [
"geetika.shrma16@gmail.com"
] | geetika.shrma16@gmail.com |
7b742403a29b8b88c41698af9d7532552888f0fd | 880b21dd63bd95f69978ac7fc18be59f691c8935 | /src/wallet/rpcnames.cpp | 67c3839101e31f9417ead0cd79a4ec9ec2b23a4d | [
"MIT"
] | permissive | sovr610/xaya | c88f60bb72138180d2df6c630a52c44ccc37f8a6 | a1ba991b476eaa49397e2d054be3241db3727831 | refs/heads/master | 2022-10-01T17:45:38.814386 | 2020-06-05T11:53:03 | 2020-06-08T13:55:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,394 | cpp | // Copyright (c) 2014-2020 Daniel Kraft
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <coins.h>
#include <consensus/validation.h>
#include <init.h>
#include <interfaces/chain.h>
#include <key_io.h>
#include <names/common.h>
#include <names/encoding.h>
#include <names/main.h>
#include <names/mempool.h>
#include <node/context.h>
#include <net.h>
#include <primitives/transaction.h>
#include <random.h>
#include <rpc/blockchain.h>
#include <rpc/names.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <script/names.h>
#include <script/standard.h>
#include <txmempool.h>
#include <util/fees.h>
#include <util/moneystr.h>
#include <util/system.h>
#include <util/translation.h>
#include <validation.h>
#include <wallet/coincontrol.h>
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#include <univalue.h>
#include <algorithm>
#include <memory>
/* ************************************************************************** */
namespace
{
/**
* A simple helper class that handles determination of the address to which
* name outputs should be sent. It handles the CReserveKey reservation
* as well as parsing the explicit options given by the user (if any).
*/
class DestinationAddressHelper
{
private:
/** Reference to the wallet that should be used. */
CWallet& wallet;
/**
* The reserve key that was used if no override is given. When finalising
* (after the sending succeeded), this key needs to be marked as Keep().
*/
std::unique_ptr<ReserveDestination> rdest;
/** Set if a valid override destination was added. */
std::unique_ptr<CTxDestination> overrideDest;
public:
explicit DestinationAddressHelper (CWallet& w)
: wallet(w)
{}
/**
* Processes the given options object to see if it contains an override
* destination. If it does, remembers it.
*/
void setOptions (const UniValue& opt);
/**
* Returns the script that should be used as destination.
*/
CScript getScript ();
/**
* Marks the key as used if one has been reserved. This should be called
* when sending succeeded.
*/
void finalise ();
};
void DestinationAddressHelper::setOptions (const UniValue& opt)
{
RPCTypeCheckObj (opt,
{
{"destAddress", UniValueType (UniValue::VSTR)},
},
true, false);
if (!opt.exists ("destAddress"))
return;
CTxDestination dest = DecodeDestination (opt["destAddress"].get_str ());
if (!IsValidDestination (dest))
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, "invalid address");
overrideDest.reset (new CTxDestination (std::move (dest)));
}
CScript DestinationAddressHelper::getScript ()
{
if (overrideDest != nullptr)
return GetScriptForDestination (*overrideDest);
rdest.reset (new ReserveDestination (&wallet, wallet.m_default_address_type));
CTxDestination dest;
if (!rdest->GetReservedDestination (dest, false))
throw JSONRPCError (RPC_WALLET_KEYPOOL_RAN_OUT,
"Error: Keypool ran out,"
" please call keypoolrefill first");
return GetScriptForDestination (dest);
}
void DestinationAddressHelper::finalise ()
{
if (rdest != nullptr)
rdest->KeepDestination ();
}
/**
* Sends a name output to the given name script. This is the "final" step that
* is common between name_new, name_firstupdate and name_update. This method
* also implements the "sendCoins" option, if included.
*/
CTransactionRef
SendNameOutput (const JSONRPCRequest& request,
CWallet& wallet, const CScript& nameOutScript,
const CTxIn* nameInput, const UniValue& opt)
{
RPCTypeCheckObj (opt,
{
{"sendCoins", UniValueType (UniValue::VOBJ)},
{"burn", UniValueType (UniValue::VOBJ)},
},
true, false);
auto& node = EnsureNodeContext (request.context);
if (wallet.GetBroadcastTransactions () && !node.connman)
throw JSONRPCError (RPC_CLIENT_P2P_DISABLED,
"Error: Peer-to-peer functionality missing"
" or disabled");
std::vector<CRecipient> vecSend;
vecSend.push_back ({nameOutScript, NAME_LOCKED_AMOUNT, false});
if (opt.exists ("sendCoins"))
for (const std::string& addr : opt["sendCoins"].getKeys ())
{
const CTxDestination dest = DecodeDestination (addr);
if (!IsValidDestination (dest))
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY,
"Invalid address: " + addr);
const CAmount nAmount = AmountFromValue (opt["sendCoins"][addr]);
if (nAmount <= 0)
throw JSONRPCError (RPC_TYPE_ERROR, "Invalid amount for send");
vecSend.push_back ({GetScriptForDestination (dest), nAmount, false});
}
if (opt.exists ("burn"))
for (const std::string& data : opt["burn"].getKeys ())
{
/* MAX_OP_RETURN_RELAY contains three extra bytes, for the opcodes
it includes. */
const auto bytes = ToByteVector (data);
if (bytes.size () > MAX_OP_RETURN_RELAY - 3)
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY,
"Burn data is too long: " + data);
const CAmount nAmount = AmountFromValue (opt["burn"][data]);
if (nAmount <= 0)
throw JSONRPCError (RPC_TYPE_ERROR, "Invalid amount for burn");
const CScript scr = CScript () << OP_RETURN << bytes;
vecSend.push_back ({scr, nAmount, false});
}
/* Shuffle the recipient list for privacy. */
std::shuffle (vecSend.begin (), vecSend.end (), FastRandomContext ());
/* Check balance against total amount sent. If we have a name input, we have
to take its value into account. */
const CAmount curBalance = wallet.GetBalance ().m_mine_trusted;
CAmount totalSpend = 0;
for (const auto& recv : vecSend)
totalSpend += recv.nAmount;
CAmount lockedValue = 0;
bilingual_str error;
if (nameInput != nullptr)
{
const CWalletTx* dummyWalletTx;
if (!wallet.FindValueInNameInput (*nameInput, lockedValue,
dummyWalletTx, error))
throw JSONRPCError(RPC_WALLET_ERROR, error.original);
}
if (totalSpend > curBalance + lockedValue)
throw JSONRPCError (RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
/* Create and send the transaction. This code is based on the corresponding
part of SendMoneyToScript and should stay in sync. */
CCoinControl coinControl;
CAmount nFeeRequired;
int nChangePosRet = -1;
CTransactionRef tx;
if (!wallet.CreateTransaction (vecSend, nameInput, tx,
nFeeRequired, nChangePosRet, error,
coinControl))
{
if (totalSpend + nFeeRequired > curBalance)
error = strprintf (Untranslated (
"Error: This transaction requires a transaction"
" fee of at least %s"),
FormatMoney (nFeeRequired));
throw JSONRPCError (RPC_WALLET_ERROR, error.original);
}
wallet.CommitTransaction (tx, {}, {});
return tx;
}
} // anonymous namespace
/* ************************************************************************** */
UniValue
name_list (const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
CWallet* const pwallet = wallet.get ();
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ();
RPCHelpMan ("name_list",
"\nShows the status of all names in the wallet.\n",
{
{"name", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Only include this name"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::ARR, "", "",
{
NameInfoHelp ()
.withHeight ()
.finish ()
}
},
RPCExamples {
HelpExampleCli ("name_list", "")
+ HelpExampleCli ("name_list", "\"myname\"")
+ HelpExampleRpc ("name_list", "")
}
).Check (request);
RPCTypeCheck (request.params, {UniValue::VSTR, UniValue::VOBJ}, true);
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 2)
options = request.params[1].get_obj ();
valtype nameFilter;
if (request.params.size () >= 1 && !request.params[0].isNull ())
nameFilter = DecodeNameFromRPCOrThrow (request.params[0], options);
std::map<valtype, int> mapHeights;
std::map<valtype, UniValue> mapObjects;
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain ();
{
LOCK2 (pwallet->cs_wallet, cs_main);
const int tipHeight = ::ChainActive ().Height ();
for (const auto& item : pwallet->mapWallet)
{
const CWalletTx& tx = item.second;
CNameScript nameOp;
int nOut = -1;
for (unsigned i = 0; i < tx.tx->vout.size (); ++i)
{
const CNameScript cur(tx.tx->vout[i].scriptPubKey);
if (cur.isNameOp ())
{
if (nOut != -1)
LogPrintf ("ERROR: wallet contains tx with multiple"
" name outputs");
else
{
nameOp = cur;
nOut = i;
}
}
}
if (nOut == -1 || !nameOp.isAnyUpdate ())
continue;
const valtype& name = nameOp.getOpName ();
if (!nameFilter.empty () && nameFilter != name)
continue;
const int depth = tx.GetDepthInMainChain ();
if (depth <= 0)
continue;
const int height = tipHeight - depth + 1;
const auto mit = mapHeights.find (name);
if (mit != mapHeights.end () && mit->second > height)
continue;
UniValue obj
= getNameInfo (options, name, nameOp.getOpValue (),
COutPoint (tx.GetHash (), nOut),
nameOp.getAddress ());
addOwnershipInfo (nameOp.getAddress (), pwallet, obj);
addHeightInfo (height, obj);
mapHeights[name] = height;
mapObjects[name] = obj;
}
}
UniValue res(UniValue::VARR);
for (const auto& item : mapObjects)
res.push_back (item.second);
return res;
}
/* ************************************************************************** */
UniValue
name_register (const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
CWallet* const pwallet = wallet.get ();
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ()
.withWriteOptions ();
RPCHelpMan ("name_register",
"\nRegisters a new name."
+ HELP_REQUIRING_PASSPHRASE,
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to register"},
{"value", RPCArg::Type::STR, RPCArg::Optional::NO, "Value for the name"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"},
RPCExamples {
HelpExampleCli ("name_register", "\"myname\", \"new-value\"")
+ HelpExampleRpc ("name_register", "\"myname\", \"new-value\"")
}
).Check (request);
RPCTypeCheck (request.params,
{UniValue::VSTR, UniValue::VSTR, UniValue::VOBJ});
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 3)
options = request.params[2].get_obj ();
const valtype name = DecodeNameFromRPCOrThrow (request.params[0], options);
TxValidationState state;
if (!IsNameValid (name, state))
throw JSONRPCError (RPC_INVALID_PARAMETER, state.GetRejectReason ());
const valtype value = DecodeValueFromRPCOrThrow (request.params[1], options);
if (!IsValueValid (value, state))
throw JSONRPCError (RPC_INVALID_PARAMETER, state.GetRejectReason ());
/* Reject updates to a name for which the mempool already has
a pending registration. This is not a hard rule enforced by network
rules, but it is necessary with the current mempool implementation. */
{
LOCK (mempool.cs);
if (mempool.registersName (name))
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"there is already a pending registration"
" for this name");
}
{
LOCK (cs_main);
CNameData data;
if (::ChainstateActive ().CoinsTip ().GetName (name, data))
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"this name exists already");
}
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain ();
LOCK (pwallet->cs_wallet);
EnsureWalletIsUnlocked (pwallet);
DestinationAddressHelper destHelper(*pwallet);
destHelper.setOptions (options);
const CScript nameScript
= CNameScript::buildNameRegister (destHelper.getScript (), name, value);
CTransactionRef tx
= SendNameOutput (request, *pwallet, nameScript, nullptr, options);
destHelper.finalise ();
return tx->GetHash ().GetHex ();
}
/* ************************************************************************** */
UniValue
name_update (const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
CWallet* const pwallet = wallet.get ();
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
NameOptionsHelp optHelp;
optHelp
.withNameEncoding ()
.withValueEncoding ()
.withWriteOptions ();
RPCHelpMan ("name_update",
"\nUpdates a name and possibly transfers it."
+ HELP_REQUIRING_PASSPHRASE,
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to update"},
{"value", RPCArg::Type::STR, RPCArg::Optional::NO, "Value for the name"},
optHelp.buildRpcArg (),
},
RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"},
RPCExamples {
HelpExampleCli ("name_update", "\"myname\", \"new-value\"")
+ HelpExampleRpc ("name_update", "\"myname\", \"new-value\"")
}
).Check (request);
RPCTypeCheck (request.params,
{UniValue::VSTR, UniValue::VSTR, UniValue::VOBJ});
UniValue options(UniValue::VOBJ);
if (request.params.size () >= 3)
options = request.params[2].get_obj ();
const valtype name = DecodeNameFromRPCOrThrow (request.params[0], options);
TxValidationState state;
if (!IsNameValid (name, state))
throw JSONRPCError (RPC_INVALID_PARAMETER, state.GetRejectReason ());
const valtype value = DecodeValueFromRPCOrThrow (request.params[1], options);
if (!IsValueValid (value, state))
throw JSONRPCError (RPC_INVALID_PARAMETER, state.GetRejectReason ());
/* For finding the name output to spend, we first check if there are
pending operations on the name in the mempool. If there are, then we
build upon the last one to get a valid chain. If there are none, then we
look up the last outpoint from the name database instead. */
const unsigned chainLimit = gArgs.GetArg ("-limitnamechains",
DEFAULT_NAME_CHAIN_LIMIT);
COutPoint outp;
{
LOCK (mempool.cs);
const unsigned pendingOps = mempool.pendingNameChainLength (name);
if (pendingOps >= chainLimit)
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"there are already too many pending operations"
" on this name");
if (pendingOps > 0)
outp = mempool.lastNameOutput (name);
}
if (outp.IsNull ())
{
LOCK (cs_main);
CNameData oldData;
const auto& coinsTip = ::ChainstateActive ().CoinsTip ();
if (!coinsTip.GetName (name, oldData))
throw JSONRPCError (RPC_TRANSACTION_ERROR,
"this name can not be updated");
outp = oldData.getUpdateOutpoint ();
}
assert (!outp.IsNull ());
const CTxIn txIn(outp);
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain ();
LOCK (pwallet->cs_wallet);
EnsureWalletIsUnlocked (pwallet);
DestinationAddressHelper destHelper(*pwallet);
destHelper.setOptions (options);
const CScript nameScript
= CNameScript::buildNameUpdate (destHelper.getScript (), name, value);
CTransactionRef tx
= SendNameOutput (request, *pwallet, nameScript, &txIn, options);
destHelper.finalise ();
return tx->GetHash ().GetHex ();
}
/* ************************************************************************** */
UniValue
sendtoname (const JSONRPCRequest& request)
{
std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest (request);
CWallet* const pwallet = wallet.get ();
if (!EnsureWalletIsAvailable (pwallet, request.fHelp))
return NullUniValue;
RPCHelpMan{"sendtoname",
"\nSend an amount to the owner of a name.\n"
"\nIt is an error if the name is expired."
+ HELP_REQUIRING_PASSPHRASE,
{
{"name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name to send to."},
{"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1"},
{"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment used to store what the transaction is for.\n"
" This is not part of the transaction, just kept in your wallet."},
{"comment_to", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment to store the name of the person or organization\n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet."},
{"subtractfeefromamount", RPCArg::Type::BOOL, /* default */ "false", "The fee will be deducted from the amount being sent.\n"
" The recipient will receive less coins than you enter in the amount field."},
{"replaceable", RPCArg::Type::BOOL, /* default */ "fallback to wallet's default", "Allow this transaction to be replaced by a transaction with higher fees via BIP 125"},
{"conf_target", RPCArg::Type::NUM, /* default */ "fallback to wallet's default", "Confirmation target (in blocks)"},
{"estimate_mode", RPCArg::Type::STR, /* default */ "UNSET", "The fee estimate mode, must be one of:\n"
" \"UNSET\"\n"
" \"ECONOMICAL\"\n"
" \"CONSERVATIVE\""},
},
RPCResult {RPCResult::Type::STR_HEX, "", "the transaction ID"},
RPCExamples{
HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1")
+ HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1 \"donation\" \"seans outpost\"")
+ HelpExampleCli ("sendtoname", "\"id/foobar\" 0.1 \"\" \"\" true")
+ HelpExampleRpc ("sendtoname", "\"id/foobar\", 0.1, \"donation\", \"seans outpost\"")
},
}.Check (request);
RPCTypeCheck (request.params,
{UniValue::VSTR, UniValue::VNUM, UniValue::VSTR,
UniValue::VSTR, UniValue::VBOOL, UniValue::VBOOL,
UniValue::VNUM, UniValue::VSTR});
if (::ChainstateActive ().IsInitialBlockDownload ())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Xaya is downloading blocks...");
/* Make sure the results are valid at least up to the most recent block
the user could have gotten from another RPC command prior to now. */
pwallet->BlockUntilSyncedToCurrentChain();
LOCK(pwallet->cs_wallet);
/* sendtoname does not support an options argument (e.g. to override the
configured name/value encodings). That would just add to the already
long list of rarely used arguments. Also, this function is inofficially
deprecated anyway, see
https://github.com/namecoin/namecoin-core/issues/12. */
const UniValue NO_OPTIONS(UniValue::VOBJ);
const valtype name = DecodeNameFromRPCOrThrow (request.params[0], NO_OPTIONS);
CNameData data;
if (!::ChainstateActive ().CoinsTip ().GetName (name, data))
{
std::ostringstream msg;
msg << "name not found: " << EncodeNameForMessage (name);
throw JSONRPCError (RPC_INVALID_ADDRESS_OR_KEY, msg.str ());
}
/* The code below is strongly based on sendtoaddress. Make sure to
keep it in sync. */
// Amount
CAmount nAmount = AmountFromValue(request.params[1]);
if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
// Wallet comments
mapValue_t mapValue;
if (request.params.size() > 2 && !request.params[2].isNull()
&& !request.params[2].get_str().empty())
mapValue["comment"] = request.params[2].get_str();
if (request.params.size() > 3 && !request.params[3].isNull()
&& !request.params[3].get_str().empty())
mapValue["to"] = request.params[3].get_str();
bool fSubtractFeeFromAmount = false;
if (!request.params[4].isNull())
fSubtractFeeFromAmount = request.params[4].get_bool();
CCoinControl coin_control;
if (!request.params[5].isNull()) {
coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
}
if (!request.params[6].isNull()) {
coin_control.m_confirm_target = ParseConfirmTarget(request.params[6], pwallet->chain().estimateMaxBlocks());
}
if (!request.params[7].isNull()) {
if (!FeeModeFromString(request.params[7].get_str(),
coin_control.m_fee_mode)) {
throw JSONRPCError(RPC_INVALID_PARAMETER,
"Invalid estimate_mode parameter");
}
}
EnsureWalletIsUnlocked(pwallet);
CTransactionRef tx = SendMoneyToScript (pwallet, data.getAddress (), nullptr,
nAmount, fSubtractFeeFromAmount,
coin_control, std::move(mapValue));
return tx->GetHash ().GetHex ();
}
| [
"d@domob.eu"
] | d@domob.eu |
8f56f1db67726fe16f815bb7dcd50cad43c33e15 | db6d5226ad3d8d213e06d59d3998a4ce2e9030bd | /src/addrman.cpp | b27f403849e3d5445adfbe9c30285bc66f89d3b7 | [
"MIT"
] | permissive | Schilling99/SchillingCoin | 9536c00d1bd8eef55482a398f3b5f12429938cb2 | c9d7c4f70341e7ab552131e7e4a018197bc8558a | refs/heads/master | 2022-12-26T14:58:40.917535 | 2020-10-08T12:33:38 | 2020-10-08T12:33:38 | 302,329,522 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 16,094 | cpp | // Copyright (c) 2012 Pieter Wuille
// Copyright (c) 2012-2014 The Bitcoin developers
// Copyright (c) 2017-2019 The PIVX developers
// Copyright (c) 2018-2020 The SchillingCoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addrman.h"
#include "hash.h"
#include "serialize.h"
#include "streams.h"
int CAddrInfo::GetTriedBucket(const uint256& nKey) const
{
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetKey()).GetHash().GetCheapHash();
uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP)).GetHash().GetCheapHash();
return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
}
int CAddrInfo::GetNewBucket(const uint256& nKey, const CNetAddr& src) const
{
std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << GetGroup() << vchSourceGroupKey).GetHash().GetCheapHash();
uint64_t hash2 = (CHashWriter(SER_GETHASH, 0) << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP)).GetHash().GetCheapHash();
return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
}
int CAddrInfo::GetBucketPosition(const uint256& nKey, bool fNew, int nBucket) const
{
uint64_t hash1 = (CHashWriter(SER_GETHASH, 0) << nKey << (fNew ? 'N' : 'K') << nBucket << GetKey()).GetHash().GetCheapHash();
return hash1 % ADDRMAN_BUCKET_SIZE;
}
bool CAddrInfo::IsTerrible(int64_t nNow) const
{
if (nLastTry && nLastTry >= nNow - 60) // never remove things tried in the last minute
return false;
if (nTime > nNow + 10 * 60) // came in a flying DeLorean
return true;
if (nTime == 0 || nNow - nTime > ADDRMAN_HORIZON_DAYS * 24 * 60 * 60) // not seen in recent history
return true;
if (nLastSuccess == 0 && nAttempts >= ADDRMAN_RETRIES) // tried N times and never a success
return true;
if (nNow - nLastSuccess > ADDRMAN_MIN_FAIL_DAYS * 24 * 60 * 60 && nAttempts >= ADDRMAN_MAX_FAILURES) // N successive failures in the last week
return true;
return false;
}
double CAddrInfo::GetChance(int64_t nNow) const
{
double fChance = 1.0;
int64_t nSinceLastSeen = nNow - nTime;
int64_t nSinceLastTry = nNow - nLastTry;
if (nSinceLastSeen < 0)
nSinceLastSeen = 0;
if (nSinceLastTry < 0)
nSinceLastTry = 0;
// deprioritize very recent attempts away
if (nSinceLastTry < 60 * 10)
fChance *= 0.01;
// deprioritize 66% after each failed attempt, but at most 1/28th to avoid the search taking forever or overly penalizing outages.
fChance *= pow(0.66, std::min(nAttempts, 8));
return fChance;
}
CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int* pnId)
{
std::map<CNetAddr, int>::iterator it = mapAddr.find(addr);
if (it == mapAddr.end())
return NULL;
if (pnId)
*pnId = (*it).second;
std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second);
if (it2 != mapInfo.end())
return &(*it2).second;
return NULL;
}
CAddrInfo* CAddrMan::Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId)
{
int nId = nIdCount++;
mapInfo[nId] = CAddrInfo(addr, addrSource);
mapAddr[addr] = nId;
mapInfo[nId].nRandomPos = vRandom.size();
vRandom.push_back(nId);
if (pnId)
*pnId = nId;
return &mapInfo[nId];
}
void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2)
{
if (nRndPos1 == nRndPos2)
return;
assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
int nId1 = vRandom[nRndPos1];
int nId2 = vRandom[nRndPos2];
assert(mapInfo.count(nId1) == 1);
assert(mapInfo.count(nId2) == 1);
mapInfo[nId1].nRandomPos = nRndPos2;
mapInfo[nId2].nRandomPos = nRndPos1;
vRandom[nRndPos1] = nId2;
vRandom[nRndPos2] = nId1;
}
void CAddrMan::Delete(int nId)
{
assert(mapInfo.count(nId) != 0);
CAddrInfo& info = mapInfo[nId];
assert(!info.fInTried);
assert(info.nRefCount == 0);
SwapRandom(info.nRandomPos, vRandom.size() - 1);
vRandom.pop_back();
mapAddr.erase(info);
mapInfo.erase(nId);
nNew--;
}
void CAddrMan::ClearNew(int nUBucket, int nUBucketPos)
{
// if there is an entry in the specified bucket, delete it.
if (vvNew[nUBucket][nUBucketPos] != -1) {
int nIdDelete = vvNew[nUBucket][nUBucketPos];
CAddrInfo& infoDelete = mapInfo[nIdDelete];
assert(infoDelete.nRefCount > 0);
infoDelete.nRefCount--;
vvNew[nUBucket][nUBucketPos] = -1;
if (infoDelete.nRefCount == 0) {
Delete(nIdDelete);
}
}
}
void CAddrMan::MakeTried(CAddrInfo& info, int nId)
{
// remove the entry from all new buckets
for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++) {
int pos = info.GetBucketPosition(nKey, true, bucket);
if (vvNew[bucket][pos] == nId) {
vvNew[bucket][pos] = -1;
info.nRefCount--;
}
}
nNew--;
assert(info.nRefCount == 0);
// which tried bucket to move the entry to
int nKBucket = info.GetTriedBucket(nKey);
int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
// first make space to add it (the existing tried entry there is moved to new, deleting whatever is there).
if (vvTried[nKBucket][nKBucketPos] != -1) {
// find an item to evict
int nIdEvict = vvTried[nKBucket][nKBucketPos];
assert(mapInfo.count(nIdEvict) == 1);
CAddrInfo& infoOld = mapInfo[nIdEvict];
// Remove the to-be-evicted item from the tried set.
infoOld.fInTried = false;
vvTried[nKBucket][nKBucketPos] = -1;
nTried--;
// find which new bucket it belongs to
int nUBucket = infoOld.GetNewBucket(nKey);
int nUBucketPos = infoOld.GetBucketPosition(nKey, true, nUBucket);
ClearNew(nUBucket, nUBucketPos);
assert(vvNew[nUBucket][nUBucketPos] == -1);
// Enter it into the new set again.
infoOld.nRefCount = 1;
vvNew[nUBucket][nUBucketPos] = nIdEvict;
nNew++;
}
assert(vvTried[nKBucket][nKBucketPos] == -1);
vvTried[nKBucket][nKBucketPos] = nId;
nTried++;
info.fInTried = true;
}
void CAddrMan::Good_(const CService& addr, int64_t nTime)
{
int nId;
nLastGood = nTime;
CAddrInfo* pinfo = Find(addr, &nId);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo& info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
info.nLastSuccess = nTime;
info.nLastTry = nTime;
info.nAttempts = 0;
// nTime is not updated here, to avoid leaking information about
// currently-connected peers.
// if it is already in the tried set, don't do anything else
if (info.fInTried)
return;
// find a bucket it is in now
int nRnd = RandomInt(ADDRMAN_NEW_BUCKET_COUNT);
int nUBucket = -1;
for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT;
int nBpos = info.GetBucketPosition(nKey, true, nB);
if (vvNew[nB][nBpos] == nId) {
nUBucket = nB;
break;
}
}
// if no bucket is found, something bad happened;
// TODO: maybe re-add the node, but for now, just bail out
if (nUBucket == -1)
return;
LogPrint("addrman", "Moving %s to tried\n", addr.ToString());
// move nId to the tried tables
MakeTried(info, nId);
}
bool CAddrMan::Add_(const CAddress& addr, const CNetAddr& source, int64_t nTimePenalty)
{
if (!addr.IsRoutable())
return false;
bool fNew = false;
int nId;
CAddrInfo* pinfo = Find(addr, &nId);
if (pinfo) {
// periodically update nTime
bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
int64_t nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
pinfo->nTime = std::max((int64_t)0, addr.nTime - nTimePenalty);
// add services
pinfo->nServices |= addr.nServices;
// do not update if no new information is present
if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime))
return false;
// do not update if the entry was already in the "tried" table
if (pinfo->fInTried)
return false;
// do not update if the max reference count is reached
if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
return false;
// stochastic test: previous nRefCount == N: 2^N times harder to increase it
int nFactor = 1;
for (int n = 0; n < pinfo->nRefCount; n++)
nFactor *= 2;
if (nFactor > 1 && (RandomInt(nFactor) != 0))
return false;
} else {
pinfo = Create(addr, source, &nId);
pinfo->nTime = std::max((int64_t)0, (int64_t)pinfo->nTime - nTimePenalty);
nNew++;
fNew = true;
}
int nUBucket = pinfo->GetNewBucket(nKey, source);
int nUBucketPos = pinfo->GetBucketPosition(nKey, true, nUBucket);
if (vvNew[nUBucket][nUBucketPos] != nId) {
bool fInsert = vvNew[nUBucket][nUBucketPos] == -1;
if (!fInsert) {
CAddrInfo& infoExisting = mapInfo[vvNew[nUBucket][nUBucketPos]];
if (infoExisting.IsTerrible() || (infoExisting.nRefCount > 1 && pinfo->nRefCount == 0)) {
// Overwrite the existing new table entry.
fInsert = true;
}
}
if (fInsert) {
ClearNew(nUBucket, nUBucketPos);
pinfo->nRefCount++;
vvNew[nUBucket][nUBucketPos] = nId;
} else {
if (pinfo->nRefCount == 0) {
Delete(nId);
}
}
}
return fNew;
}
void CAddrMan::Attempt_(const CService& addr, bool fCountFailure, int64_t nTime)
{
CAddrInfo* pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo& info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
info.nLastTry = nTime;
if (fCountFailure && info.nLastCountAttempt < nLastGood) {
info.nLastCountAttempt = nTime;
info.nAttempts++;
}
}
CAddrInfo CAddrMan::Select_(bool newOnly)
{
if (size() == 0)
return CAddrInfo();
if (newOnly && nNew == 0)
return CAddrInfo();
// Use a 50% chance for choosing between tried and new table entries.
if (!newOnly && (nTried > 0 && (nNew == 0 || RandomInt(2) == 0))) {
// use a tried node
double fChanceFactor = 1.0;
while (1) {
int nKBucket = RandomInt(ADDRMAN_TRIED_BUCKET_COUNT);
int nKBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE);
while (vvTried[nKBucket][nKBucketPos] == -1) {
nKBucket = (nKBucket + insecure_rand.randbits(ADDRMAN_TRIED_BUCKET_COUNT_LOG2)) % ADDRMAN_TRIED_BUCKET_COUNT;
nKBucketPos = (nKBucketPos + insecure_rand.randbits(ADDRMAN_BUCKET_SIZE_LOG2)) % ADDRMAN_BUCKET_SIZE;
}
int nId = vvTried[nKBucket][nKBucketPos];
assert(mapInfo.count(nId) == 1);
CAddrInfo& info = mapInfo[nId];
if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30))
return info;
fChanceFactor *= 1.2;
}
} else {
// use a new node
double fChanceFactor = 1.0;
while (1) {
int nUBucket = RandomInt(ADDRMAN_NEW_BUCKET_COUNT);
int nUBucketPos = RandomInt(ADDRMAN_BUCKET_SIZE);
while (vvNew[nUBucket][nUBucketPos] == -1) {
nUBucket = (nUBucket + insecure_rand.randbits(ADDRMAN_NEW_BUCKET_COUNT_LOG2)) % ADDRMAN_NEW_BUCKET_COUNT;
nUBucketPos = (nUBucketPos + insecure_rand.randbits(ADDRMAN_BUCKET_SIZE_LOG2)) % ADDRMAN_BUCKET_SIZE;
}
int nId = vvNew[nUBucket][nUBucketPos];
assert(mapInfo.count(nId) == 1);
CAddrInfo& info = mapInfo[nId];
if (RandomInt(1 << 30) < fChanceFactor * info.GetChance() * (1 << 30))
return info;
fChanceFactor *= 1.2;
}
}
}
#ifdef DEBUG_ADDRMAN
int CAddrMan::Check_()
{
std::set<int> setTried;
std::map<int, int> mapNew;
if (vRandom.size() != nTried + nNew)
return -7;
for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++) {
int n = (*it).first;
CAddrInfo& info = (*it).second;
if (info.fInTried) {
if (!info.nLastSuccess)
return -1;
if (info.nRefCount)
return -2;
setTried.insert(n);
} else {
if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
return -3;
if (!info.nRefCount)
return -4;
mapNew[n] = info.nRefCount;
}
if (mapAddr[info] != n)
return -5;
if (info.nRandomPos < 0 || info.nRandomPos >= vRandom.size() || vRandom[info.nRandomPos] != n)
return -14;
if (info.nLastTry < 0)
return -6;
if (info.nLastSuccess < 0)
return -8;
}
if (setTried.size() != nTried)
return -9;
if (mapNew.size() != nNew)
return -10;
for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
if (vvTried[n][i] != -1) {
if (!setTried.count(vvTried[n][i]))
return -11;
if (mapInfo[vvTried[n][i]].GetTriedBucket(nKey) != n)
return -17;
if (mapInfo[vvTried[n][i]].GetBucketPosition(nKey, false, n) != i)
return -18;
setTried.erase(vvTried[n][i]);
}
}
}
for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
if (vvNew[n][i] != -1) {
if (!mapNew.count(vvNew[n][i]))
return -12;
if (mapInfo[vvNew[n][i]].GetBucketPosition(nKey, true, n) != i)
return -19;
if (--mapNew[vvNew[n][i]] == 0)
mapNew.erase(vvNew[n][i]);
}
}
}
if (setTried.size())
return -13;
if (mapNew.size())
return -15;
if (nKey.IsNull())
return -16;
return 0;
}
#endif
void CAddrMan::GetAddr_(std::vector<CAddress>& vAddr)
{
unsigned int nNodes = ADDRMAN_GETADDR_MAX_PCT * vRandom.size() / 100;
if (nNodes > ADDRMAN_GETADDR_MAX)
nNodes = ADDRMAN_GETADDR_MAX;
// gather a list of random nodes, skipping those of low quality
for (unsigned int n = 0; n < vRandom.size(); n++) {
if (vAddr.size() >= nNodes)
break;
int nRndPos = RandomInt(vRandom.size() - n) + n;
SwapRandom(n, nRndPos);
assert(mapInfo.count(vRandom[n]) == 1);
const CAddrInfo& ai = mapInfo[vRandom[n]];
if (!ai.IsTerrible())
vAddr.push_back(ai);
}
}
void CAddrMan::Connected_(const CService& addr, int64_t nTime)
{
CAddrInfo* pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo& info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
int64_t nUpdateInterval = 20 * 60;
if (nTime - info.nTime > nUpdateInterval)
info.nTime = nTime;
}
int CAddrMan::RandomInt(int nMax){
return GetRandInt(nMax);
} | [
"59433840+Schilling99@users.noreply.github.com"
] | 59433840+Schilling99@users.noreply.github.com |
9af94c742012d2c814f28c61c6fc3989cad7e2ed | c4026d5ff8cdb876ddb9111df22ce0e4ad3058b2 | /codigosC++/testEpp/testEpp/testEpp.cpp | 2a590c14fdd309941ce2aaaf52af096577ad0d7b | [] | no_license | NoelGaspar/WacBoard | c8335c2807c16a1d31216b6be83d69f78b23f088 | 810938cb2543a3f551d024d1c6680947ad6d0f5f | refs/heads/master | 2020-04-13T13:18:38.772225 | 2019-01-03T03:28:56 | 2019-01-03T03:28:56 | 163,226,293 | 0 | 1 | null | null | null | null | ISO-8859-3 | C++ | false | false | 11,339 | cpp | // testEpp.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "dpcdecl.h"
#include "depp.h"
#include "dmgr.h"
#include "dpcutil.h"
#include "dpcdefs.h"
using namespace std;
static HIF hif = hifInvalid;
static HANDLE han = hifInvalid;
static ERC erc=0;
static int val=0;
//static char dato=0x00;
static int test(){
//tratamos de inicializar la comunicacion con el puerto EPP
BYTE data[16];
BYTE data2[16];
int i =0;
BYTE count=0x00;
memset(data2,0x00,16);
for(i=0;i<16;i++){
count=count+1;
data[i]=count;
}
fprintf(stderr,"Iniciando\n");
if(!DpcInit(&erc)) {
printf("No fue posible iniciar...\n");
puts("presione una tecla para cerrar");
getchar();
return 0;
}
//una vez inicializado tratamos de abrir la comuniacion.
fprintf(stderr,"Iniciado\nAbriendo\n");
if(!DpcOpenData(&han, "Nexys2",&erc,NULL)) { // Change to Basys2 for the other board.
printf("DpcOpenData failed (revise si la tarjeta esta conectada)\n");
DpcTerm();
puts("presione una tecla para cerrar");
getchar();
return 0;
}
// ya abierta la comunicación tratamos de enviar un dato al primer registro
fprintf(stderr,"enviando dato de prueba\n");
if(!DpcPutReg(han,0x00, 0x01, &erc, NULL)){
printf("DpcPutReg failed.\n");
puts("presione una tecla para cerrar");
getchar();
return 0;
}
puts("presione una tecla para cerrar");
getchar();
fprintf(stderr,"enviando dato de prueba\n");
if(!DpcPutReg(han, 0x10, 0x02, &erc, NULL)){
printf("DpcPutReg failed.\n");
puts("presione una tecla para cerrar");
char c=getchar();
return 0;
}
puts("presione una tecla para cerrar");
getchar();
//DpcPutReg(HANDLE hif, BYTE bAddr, BYTE bData, ERC* perc, TRID *ptrid)
fprintf(stderr,"enviando dato de prueba\n");
if(!DpcPutReg(han, 0x20, 0x04, &erc, NULL)){
printf("DpcPutReg failed.\n");
puts("presione una tecla para cerrar");
char c=getchar();
return 0;
}
//// TRATAMOS DE ENVIAR UN BLOQUE DE 40 BYTES
//fprintf(stderr,"enviado 16 datos");
//if(!DpcPutRegRepeat(han,0x30, data,16,&erc, NULL)){
// printf("DpcPutRegRepeat failed.\n");
// puts("presione una tecla para cerrar");
// char c=getchar();
//}
// // TRATAMOS DE LEER UN BLOQUE DE 40 BYTES
//fprintf(stderr,"leyendo datos. \n");
//if(!DpcGetRegRepeat(han,0x30,data2,16,&erc, NULL)){
// printf("DpcGetRegRepeat failed.\n");
// puts("presione una tecla para cerrar");
// char c=getchar();
//}
//
//for(int i=0;i<16;i++){
//printf( "datos obtenidos:%x \n",data2[i]);
//}
fprintf(stderr,"dato enviado exitosamente. Cerrando\n");
if( han != hifInvalid ) {
DpcCloseData(han,&erc);
DpcTerm();
puts("presione una tecla para cerrar");
char c=getchar();
return 0;
}
return 1;
}
static int sendAdc(BYTE *datos){
if(!DpcPutReg(han,0x00, 0x59, &erc, NULL)){
printf("DpcPutReg failed.\n");
puts("presione una tecla para cerrar");
getchar();
return 1;
}
if(!DpcPutReg(han,0x10, 0xff, &erc, NULL)){
printf("DpcPutReg failed.\n");
puts("presione una tecla para cerrar");
getchar();
return 1;
}
if(!DpcPutReg(han,0x20, 0x55, &erc, NULL)){
printf("DpcPutReg failed.\n");
puts("presione una tecla para cerrar");
getchar();
return 1;
}
Sleep(20);
fprintf(stderr,"leyendo datos. \n");
if(!DpcGetRegRepeat(han,0x30,datos,20,&erc, NULL)){
printf("DpcGetRegRepeat failed.\n");
puts("presione una tecla para cerrar");
getchar();
return 1;
}
return 0;
}
/*
Esta funcion envia comandos de forma completa. el formato es
1 addr: 0x00 dato: ctrl
2 addr: 0x10 dato: confL
3 addr: 0x20 dato: confH
*/
static int sendComnd(BYTE ctrl, BYTE confH,BYTE confL){
if(!DpcPutReg(han,0x00, ctrl, &erc, NULL)){
printf("DpcPutReg failed sending control word.\n");
puts("presione una tecla para cerrar");
getchar();
return 1;
}
if(!DpcPutReg(han,0x10, confL, &erc, NULL)){
printf("DpcPutReg failed sending config Low word.\n");
puts("presione una tecla para cerrar");
getchar();
return 1;
}
if(!DpcPutReg(han,0x20, confH, &erc, NULL)){
printf("DpcPutReg failed sending config HIGH word.\n");
puts("presione una tecla para cerrar");
getchar();
return 1;
}
return 0;
}
/*
Esta funcion envia una nueva memoria al bloque secuenciador.
Para esto debe enviar 32*2 datos de 8 bits. La memoria en tontal
cuenta con 32 addr de 16 bits. Para esto en el archivo "text_seq.tex"
debe haberse cargado los 64 BYTE a enviar escritos en formato hexadecimal
La funcion carga los 64 BYTE en el buffer data[64] y posteriormente
se envian con la funcion DpcPutRegRepeat, a la dirección 0x40.
*/
static int sendSeq(){
BYTE data[68];
memset(data,0x00,68);
int i =0;
FILE *pFilSeq;
pFilSeq=fopen("tex_output.txt","r");
rewind(pFilSeq);
for(i=0;i<64;i++)
{fscanf(pFilSeq,"%x",&data[i]);}
fclose(pFilSeq);
for( i=0; i<64;i++){ //Mostramos en consola los datos enviados.
fprintf (stderr, "datos a enviar: %d : %x \n",i,data[i]);}
if(!DpcPutRegRepeat(han,0x40, data, 64, &erc, NULL)){
printf("DpcPutRegRepeat failed.\n");
puts("presione una tecla para cerrar");
getchar();
return 1;
}
printf("Datos enviados.\n");
getchar();
return 0;
}
/*
Esta funcion convierte de un numero int en ascii a su representación hexadecimal
*/
static BYTE charintohex(char in1,char in2){
BYTE out=0x00;
BYTE temp1=0x00;
BYTE temp2=0x00;
if(in1=='1'){ temp1=0x01;}
if(in1=='2'){ temp1=0x02;}
if(in1=='3'){ temp1=0x03;}
if(in1=='4'){ temp1=0x04;}
if(in1=='5'){ temp1=0x05;}
if(in1=='6'){ temp1=0x06;}
if(in1=='7'){ temp1=0x07;}
if(in1=='8'){ temp1=0x08;}
if(in1=='9'){ temp1=0x09;}
if(in1=='a'){ temp1=0x0a;}
if(in1=='b'){ temp1=0x0b;}
if(in1=='c'){ temp1=0x0c;}
if(in1=='d'){ temp1=0x0d;}
if(in1=='e'){ temp1=0x0e;}
if(in1=='f'){ temp1=0x0f;}
if(in2=='1'){ temp2=0x10;}
if(in2=='2'){ temp2=0x20;}
if(in2=='3'){ temp2=0x30;}
if(in2=='4'){ temp2=0x40;}
if(in2=='5'){ temp2=0x50;}
if(in2=='6'){ temp2=0x60;}
if(in2=='7'){ temp2=0x70;}
if(in2=='8'){ temp2=0x80;}
if(in2=='9'){ temp2=0x90;}
if(in2=='a'){ temp2=0xa0;}
if(in2=='b'){ temp2=0xb0;}
if(in2=='c'){ temp2=0xc0;}
if(in2=='d'){ temp2=0xd0;}
if(in2=='e'){ temp2=0xe0;}
if(in2=='f'){ temp2=0xf0;}
return out=temp2|temp1;
}
/*
Esta funcion convierte un numeros de 12 bits en
formato complemento de dos a un entero con signo.
El formato de las entradas son
11 10 9 8 7 6 5 4 3 2 1 0
|----msb----| |-------lsb-----|
asi si nuestro numero a convertir es 0xf43 debemos usar
complementoDos2int(0x0f, 0x34);
el serultado será =-204.
*/
static int complementoDos2int(BYTE msb, BYTE lsb){
BYTE carry=0x00;
int d=0;
if((msb&0x08)==0x08){
lsb=lsb^0xff;
msb=msb^0x0f;
if(lsb==0xff){carry=0x01;}
else{carry=0x00;}
lsb=lsb+0x01;
msb=msb+carry;
msb=msb&0x0f;
d=(-1)* (int)(msb << 8 | lsb);
}
else{
d=(int)( msb << 8 | lsb);
}
return d;
}
int main(int cszArg, char * rgszArg[]) {
//definimos funciones locales
char c='p'; //recibir datos
char n='p'; //recibir datos
BYTE ctrl=0x00; //palabra de control a enviar
BYTE confH=0x00; //palabra de configuracion primeros 8 bits
BYTE confL=0x00; //palabra de configuracion ultimos 8 bits
//BYTE dato=0x00; //variable de dato
BYTE max=0x07;
int val=0;
int i=0;
int d[1000];
////creamos una variable FILE para registrar los datos obtenidos
////y un vector de 30 datos de 8 bits a enviar.
FILE * pFile;
pFile = fopen ("prueba.txt","w");
BYTE datos[2000];
memset(datos,0xff,2000);
//Iniciar la comunicación
fprintf(stderr,"Iniciando\n");
if(!DpcInit(&erc)) {
printf("No fue posible iniciar...\n");
puts("presione una tecla para cerrar");
getchar();
return 0;
}
//Una vez inicializado tratamos de abrir la comuniacion.
fprintf(stderr,"Abriendo conexion...\n");
if(!DpcOpenData(&han, "Nexys2",&erc,NULL)) { // Change to Basys2 for the other board.
printf("DpcOpenData failed (revise si la tarjeta esta conectada)\n");
DpcTerm();
puts("presione una tecla para cerrar");
getchar();
return 0;
}
fprintf(stderr,"enviando dato de prueba\n"); //Este dato es para resetear el puntero de direcciones en la memoria de la BRAM
if(!DpcPutReg(han,0x3f, 0xff, &erc, NULL)){
printf("DpcPutReg failed.\n");
puts("presione una tecla para cerrar");
getchar();
}
//--------------------------------------
// Enviar un comando
//--------------------------------------
while(c!='x'){
printf("Ingrese un comando:\n");
n=getchar();
c=getchar();
getchar();
if(n=='x'){break;}
ctrl=charintohex(c,n);
printf("Ingrese un confH:\n");
n=getchar();
c=getchar();
getchar();
if(n=='x'){break;}
confH=charintohex(c,n);
printf("Ingrese un confL:\n");
n=getchar();
c=getchar();
getchar();
if(n=='x'){break;}
confL=charintohex(c,n);
if(ctrl==0x44)
{val=sendSeq();
printf("Enviando una nueva secuencia\n");}
else
{val= sendComnd(ctrl,confH,confL);
printf("Enviando comando\n");}
if(c=='x'){ printf("Saliendo del programa\n"); }
if(val!=0){ printf("problema detectado\n");
break;}
}
//--------------------------------------
//--------------------------------------
fprintf(stderr,"enviando dato de prueba\n"); //Este dato es para resetear el puntero de direcciones en la memoria de la BRAM
if(!DpcPutReg(han,0x3f, 0xff, &erc, NULL)){
printf("DpcPutReg failed.\n");
puts("presione una tecla para cerrar");
getchar();
}
fprintf(stderr,"leyendo datos. \n"); //Leemos de forma continua los 30 direcciones a partir de la direccion 3. y los almacenamos en el vector datos.
if(!DpcGetRegRepeat(han,0x30,datos,2000,&erc, NULL)){
printf("DpcGetRegRepeat failed.\n");
puts("presione una tecla para cerrar");
getchar();
}
fprintf(stderr,"calculando datos\n");
BYTE carry=0x00;
for(i=0;i<1000;i++){
d[i]=complementoDos2int(datos[2*i+1],datos[2*i]);
}
for( i=0; i<30;i++){ //Mostramos en consola los datos enviados.
fprintf (stderr, "datos obtenidos: %d : %d \n",i,d[i]);}
fprintf(stderr,"escribiendo datos\n");
for( i=0; i<1000;i++){ //Mostramos en consola los datos enviados.
fprintf (pFile,"%d\n",d[i]);}
////--------------------------------------------------------------------------
////Este bloque es para probar el dac, hace un barrido de todos los valores
//puts("listos para empezar, presione una tecla para continuar");
//getchar();
//confH=0xe0;
//ctrl=0x01;
//for(int j=0;j<15;j++){
//for(int i=0;i<25;i++){
// confL=confL+0x0a;
// val=(j*25)+i;
// //printf("dato%i:%x %x\n",val,confH,confL);
// sendComnd(ctrl,confH,confL);
//}
//confH=confH+0x01;
//}
////----------------------------------------------------------------------------
printf("Cerrando. presione cualquier tecla para continuar\n"); //cerramos las comunicaciones.
getchar();
if( han != hifInvalid ) {
DpcCloseData(han,&erc);
DpcTerm();
}
DpcCloseData(han,&erc); //terminamos la comunicación
DpcTerm();
fclose (pFile);
return 0;
} | [
"waaraya@uc.cl"
] | waaraya@uc.cl |
f64df2b94f4b1b2a86840084189f9565e180cabf | c81133690291377794e35afc4dcf2763a4b2a12d | /src/proxy_lib.cpp | ce9cdf8f24376dfec86d1575f544a692d7a4f822 | [] | no_license | T-Maxxx/iw3linker_vs | 3666c4646b4ca4e0c8065c1a902350eab4ae97ce | 4fa22fa00bcd4601bf5641199cc336571879a7ef | refs/heads/master | 2021-01-24T04:43:45.438553 | 2020-06-12T13:24:36 | 2020-06-12T13:26:43 | 122,948,449 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,304 | cpp | #include "proxy_lib.hpp"
#include <cstdio>
template<class FP>
FP GetLibFunction(HMODULE hLib_, const char* FunctionName_)
{
return reinterpret_cast<FP>(GetProcAddress(hLib_, FunctionName_));
}
CProxyLib::CProxyLib()
{
char path[MAX_PATH] = { '\0' };
char sysPath[MAX_PATH - 13] = { '\0' };
GetSystemDirectoryA(sysPath, sizeof(sysPath));
sprintf_s(path, "%s\\d3dx9_34.dll", sysPath);
m_hOriginalLib = LoadLibrary(path);
}
CProxyLib::~CProxyLib()
{
if (m_hOriginalLib)
FreeLibrary(m_hOriginalLib);
}
CProxyLib& CProxyLib::Instance()
{
static CProxyLib proxyLib;
return proxyLib;
}
bool CProxyLib::IsReady() const
{
return m_hOriginalLib != NULL;
}
HRESULT CProxyLib::D3DXGetShaderOutputSemantics(const DWORD* pFunction, void* pSemantics, UINT* pCount)
{
using D3DXGetShaderOutputSemantics_t = HRESULT(WINAPI*)(const DWORD*, void*, UINT*);
static D3DXGetShaderOutputSemantics_t fn = nullptr;
if (!fn)
fn = GetLibFunction<D3DXGetShaderOutputSemantics_t>(m_hOriginalLib, "D3DXGetShaderOutputSemantics");
return fn ? fn(pFunction, pSemantics, pCount) : -1;
}
HRESULT CProxyLib::D3DXCreateBuffer(DWORD NumBytes, DWORD ppBuffer)
{
using D3DXCreateBuffer_t = HRESULT(WINAPI*)(DWORD, DWORD);
static D3DXCreateBuffer_t fn = nullptr;
if (!fn)
fn = GetLibFunction<D3DXCreateBuffer_t>(m_hOriginalLib, "D3DXCreateBuffer");
return fn ? fn(NumBytes, ppBuffer) : -1;
}
HRESULT CProxyLib::D3DXGetShaderInputSemantics(const DWORD* pFunction, void* pSemantics, UINT* pCount)
{
using D3DXGetShaderInputSemantics_t = HRESULT(WINAPI*)(const DWORD*, void*, UINT*);
static D3DXGetShaderInputSemantics_t fn = nullptr;
if (!fn)
fn = GetLibFunction<D3DXGetShaderInputSemantics_t>(m_hOriginalLib, "D3DXGetShaderInputSemantics");
return fn ? fn(pFunction, pSemantics, pCount) : -1;
}
HRESULT CProxyLib::D3DXGetShaderConstantTable(const DWORD* pFunction, void* ppConstantTable)
{
using FPD3DXGetShaderConstantTable_t = HRESULT(WINAPI*)(const DWORD*, void*);
static FPD3DXGetShaderConstantTable_t fn = nullptr;
if (!fn)
fn = GetLibFunction<FPD3DXGetShaderConstantTable_t>(m_hOriginalLib, "D3DXGetShaderConstantTable");
return fn ? fn(pFunction, ppConstantTable) : -1;
}
| [
"tmax.tver.95@gmail.com"
] | tmax.tver.95@gmail.com |
a49d62dc597ce3adc898ffcdd354b5273b356e84 | b77b470762df293be67877b484bb53b9d87b346a | /game/editor/EditModeSceneImpl.h | 27efa2967507ce9874804a364d0d14bfd3cdb297 | [
"BSD-3-Clause"
] | permissive | Sheph/af3d | 9b8b8ea41f4e439623116d70d14ce5f1ee1fae25 | 4697fbc5f9a5cfb5d54b06738de9dc44b9f7755f | refs/heads/master | 2023-08-28T16:41:43.989585 | 2021-09-11T19:09:45 | 2021-09-11T19:09:45 | 238,231,399 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,086 | h | /*
* Copyright (c) 2020, Stanislav Vorobiov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _EDITOR_EDITMODE_SCENE_IMPL_H_
#define _EDITOR_EDITMODE_SCENE_IMPL_H_
#include "editor/EditModeScene.h"
#include "editor/EditModeImpl.h"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4250)
#endif
namespace af3d { namespace editor
{
class EditModeSceneImpl : public EditModeImpl,
public EditModeScene
{
public:
explicit EditModeSceneImpl(Workspace* workspace);
~EditModeSceneImpl() = default;
Item rayCast(const Frustum& frustum, const Ray& ray) const override;
bool isValid(const Item& item) const override;
bool isAlive(const Item& item) const override;
};
} }
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
| [
"sheffmail@mail.ru"
] | sheffmail@mail.ru |
b189572e70472c26b01c47daea76cd9caab28501 | 6beb9371bf20461c218a534ea9aabf73727456c0 | /WS06/in-lab/Car.cpp | 826805572ee822c3bfe272d4f466e3698c5ef00a | [] | no_license | minhqto/oopsiestreefourfive | aef9398a45eabfc62b8a8bf8ff8d5c2d21e44ea5 | cb8a5a745dfd50477316337d99522bf54ae07dfe | refs/heads/master | 2022-03-15T01:14:25.639532 | 2020-01-02T04:30:42 | 2020-01-02T04:30:42 | 208,258,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,917 | cpp | // Name: Minh To
// Seneca Student ID: 125526186
// Seneca email: qto@myseneca.ca
// Date of completion: 31 Oct 19
//
// I confirm that the content of this file is created by me,
// with the exception of the parts provided to me by my professor.
#include "Car.h"
namespace sdds
{
Car::Car()
{
maker = "";
carCondition = "";
top_speed = 0;
}
Car::Car(std::istream& src)
{
std::string tempCar;
std::getline(src, tempCar);
//need to erase spaces
while(tempCar.find(' ') != std::string::npos){
// size_t indexer = tempCar.find(' ');
tempCar.erase(tempCar.find(' '), 1);
}
eraseStr(tempCar);
maker = tempCar.substr(0, tempCar.find_first_of(','));
eraseStr(tempCar);
carCondition = tempCar.substr(0, tempCar.find_first_of(','));
if(carCondition == "n"){
carCondition = "new";
}
else if(carCondition == "b"){
carCondition = "broken";
}
eraseStr(tempCar);
top_speed = std::stoi(tempCar);
}
std::string Car::condition() const
{
return carCondition;
}
double Car::topSpeed() const
{
return top_speed;
}
void Car::display(std::ostream& out) const
{
out << "|";
out.width(11);
out << this->maker;
out << " | ";
out.width(6);
out.setf(std::ios::left);
out << this->carCondition;
out.unsetf(std::ios::left);
out << " | ";
out.width(6);
out.setf(std::ios::fixed);
out.precision(2);
out << this->top_speed << " |";
out.unsetf(std::ios::fixed);
out << std::endl;
}
void eraseStr(std::string& src)
{
size_t comma = src.find_first_of(',');
src.erase(0, comma + 1);
}
}
| [
"minhqto3@gmail.com"
] | minhqto3@gmail.com |
c72ab318a1314d7a1d024e8dc7aaa0ca85bdac53 | 98e40260cddd889669396c8328805268346684e7 | /src/mineField.h | c4e6d9275062ba6eac3db4b5f2756858bc5c04ca | [] | no_license | FightingSu/mine_sweeper | 4e7f891bba9cdbe70deaf559df3a11f1ea3fa623 | cc7a538b8870dbdf1bcba0f2a32c5de038c149ec | refs/heads/main | 2023-04-02T12:22:33.118838 | 2021-04-07T07:36:07 | 2021-04-07T07:36:07 | 308,811,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,405 | h | #ifndef _MINE_FIELD_H_
#define _MINE_FIELD_H_
#include "blockWidget.h"
#include <cstdlib>
#include <ctime>
#include <QWidget>
#include <QVector>
#include <QMessageBox>
#include <QMouseEvent>
#include <QDebug>
class mineField :
public QWidget
{
Q_OBJECT
public:
mineField(QWidget* parent = nullptr,
int _width = 9, int _height = 9, int _mineNum = 10);
void getSettingSquare(int _square[3][3], int center, int _xNum);
int getXNum();
int getYNum();
int getMineNum();
void mouseReleaseEvent(QMouseEvent* event);
void resotre();
void showMines();
// reimplement function
QSize sizeHint() const;
public Q_SLOTS:
void getExplode();
void getFlag(int _xPos, int _yPos, bool _flag);
void getEmptyBlock(int _xPos, int _yPos);
Q_SIGNALS:
// true alive
// false dead
void gameOver(bool _lifeStatus);
private:
// 为什么使用 QVector<blockWidget*> 而不是 blockWidget*?
// 因为 这里需要申请多个 blockWidget, 每个 blockWidget 的父对象都是 mineField
// 当释放第一个 blockWidget 的时候, mineField 会将 blockWidget 当作 blockWidget* 释放
// 但是实际上它是一个 blockWidget* []
// 相当于 delete [] 用成了 delete
QVector<blockWidget*> ptrVector;
QVector<int> randomRes;
QVector<int> flagBlocks;
int xNum;
int yNum;
int mineNum;
QVector<int> randomMines(int mineNumber, int _xNum, int _yNum);
};
#endif // _MINE_FIELD_H_ | [
"ww951127.ok@hotmail.com"
] | ww951127.ok@hotmail.com |
e6038e7dcca49ac7daaa4389f6ba0be8e791b711 | f7ff42ef0bb9b9b1223bd7851e31070044a977b2 | /temp/find_address.cpp | 426f38b9902ce64ff7cfcbee084a9ece6a40c1c0 | [] | no_license | yvesmartindestaillades/RRL_pouch_motors_control | 42250c9672c6cf0a678e2535897f58b453a9fa95 | 42b32829e8dc36356c31acb6a1a79056a3cf7bba | refs/heads/master | 2023-04-02T17:31:28.724360 | 2021-04-17T18:09:58 | 2021-04-17T18:09:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,254 | cpp | /**************************************************************************/
/*!
@file read_simple_angle.ino
@author SOSAndroid (E. Ha.)
@license BSD (see license.txt)
read a simple angle from AS5048B over I2C bus
@section HISTORY
v1.0 - First release
*/
/**************************************************************************/
#include <ams_as5048b.h>
//unit consts
#define U_RAW 1
#define U_TRN 2
#define U_DEG 3
#define U_RAD 4
#define U_GRAD 5
#define U_MOA 6
#define U_SOA 7
#define U_MILNATO 8
#define U_MILSE 9
#define U_MILRU 10
AMS_AS5048B mysensor;
void setup() {
//Start serial
Serial.begin(9600);
while (!Serial) ; //wait until Serial ready
//consider the current position as zero
//mysensor.setZeroReg();
for(int i=0x30;i<0xFF;i++){
AMS_AS5048B mysensor(i);
mysensor.begin();
uint8_t adress = mysensor.addressRegR();
if (adress != 255){
Serial.println( "\n ----------------------- \n \n Adress "+ String(i)+" : "+String(adress) + "\n -----------");
delay(2000);
}
delay(5);
}
}
void loop() {
//print to serial the raw angle and degree angle every 2 seconds
//print 2 times the exact same angle - only one measurement
Serial.println("Programme fini");
delay(3000);
}
| [
"yves.mrtn98@gmail.com"
] | yves.mrtn98@gmail.com |
d68d5dc0b28f35dd3d671c078c41659f6288d908 | 3e80a79b455d2c7ab6e5e39d97ec813ff1e8512f | /EditorTextoSln/EditorCPP2015/stdafx.cpp | f592706449921a1cc4ea812ef5a16e620804850e | [
"MIT"
] | permissive | CampioniMan/EditorCPP | 6656691d69888944e316de0423e8c228330c2649 | 41f237a42af8ac5bc89027424c2dd8d8d8536e6f | refs/heads/master | 2021-01-18T18:10:26.158644 | 2016-11-18T20:36:32 | 2016-11-18T20:36:32 | 69,965,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | // stdafx.cpp : source file that includes just the standard includes
// EditorCPP2015.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"campioni.daniel@gmail.com"
] | campioni.daniel@gmail.com |
f2e0a2924468f1e593445878edd0e3318c7fb77e | 5752ccaf99fc23ad5d22e8aa2e7d38b0e06c1ad4 | /test/timer.hpp | 23331a6cbd8b5b6fc5c351f2ca9cb8327a384871 | [] | no_license | EoghanMcGinty/xcelerit_test | 1c43db44db5773f8e7acee625b72a8fe1fbc4316 | 98ec76850c615e523497fd45a12436670f89d0cc | refs/heads/master | 2020-08-09T02:15:46.373115 | 2019-10-09T17:07:13 | 2019-10-09T17:07:13 | 213,975,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | hpp | #include <iostream>
#include <chrono>
class Timer
{
public:
Timer() {
startTime = std::chrono::high_resolution_clock::now();
}
long int stop() {
auto endTime = std::chrono::high_resolution_clock::now();
auto start = std::chrono::time_point_cast<std::chrono::microseconds>(startTime).time_since_epoch().count();
auto end = std::chrono::time_point_cast<std::chrono::microseconds>(endTime).time_since_epoch().count();
auto duration = end - start;
return duration;
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> startTime;
}; | [
"eoghanm19@gmail.com"
] | eoghanm19@gmail.com |
f7a68585d3ca11e6ff92fe2ea4c38c8c7e0e395d | 02099155d15b3d65330abc7276b13c8deff68e94 | /B/B. Petya and Countryside/main.cpp | e2e84479e9c7db2144ca35e695e0c611be158735 | [] | no_license | xUser5000/competitive-programming | d7c760fa6db58956e472dd80e24def0358bbb5a8 | 90337c982dd3663a69f2d19021e692f1edb1b3a5 | refs/heads/master | 2023-06-26T21:56:02.452867 | 2021-07-23T22:39:49 | 2021-07-23T22:39:49 | 288,557,139 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | cpp | #include <iostream>
using namespace std;
int main()
{
int n; cin >> n;
int arr[n];
for (int i = 0; i < n; i++) cin >> arr[i];
int ans = 1;
for (int i = 0; i < n; i++) {
int d = 1;
for (int j = i + 1; j < n; j++) {
if (arr[j] <= arr[j - 1]) d++;
else break;
}
for (int j = i - 1; j >= 0; j--) {
if (arr[j] <= arr[j + 1]) d++;
else break;
}
ans = max(ans, d);
}
cout << ans;
return 0;
}
| [
"abdallahar1974@gmail.com"
] | abdallahar1974@gmail.com |
8177a20561454d860f25fe4dce77c068f6bd7237 | 2d36ac7285664ce798edb27bafa00e0dbc0f25fb | /LSL/liblsl/external/lslboost/date_time/gregorian/greg_month.hpp | e9d3aa485fa1de590c08a9c2d97cf9384e4dc7b5 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | nagarjunvinukonda/Brain-Computer-Interface-for-Bionic-Arm | af1a6241df167e747a7d9426e497f95dda632fda | 839cb0dc798d2bf274d3df7c4db0fef62af3770d | refs/heads/master | 2023-02-13T12:02:36.692225 | 2021-01-14T08:32:35 | 2021-01-14T08:32:35 | 297,540,583 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,508 | hpp | #ifndef GREG_MONTH_HPP___
#define GREG_MONTH_HPP___
/* Copyright (c) 2002,2003 CrystalClear Software, Inc.
* Use, modification and distribution is subject to the
* Boost Software License, Version 1.0. (See accompanying
* file LICENSE_1_0.txt or http://www.lslboost.org/LICENSE_1_0.txt)
* Author: Jeff Garland, Bart Garst
* $Date: 2008-02-27 15:00:24 -0500 (Wed, 27 Feb 2008) $
*/
#include "lslboost/date_time/constrained_value.hpp"
#include "lslboost/date_time/date_defs.hpp"
#include "lslboost/shared_ptr.hpp"
#include "lslboost/date_time/compiler_config.hpp"
#include <stdexcept>
#include <string>
#include <map>
#include <algorithm>
#include <cctype>
namespace lslboost {
namespace gregorian {
typedef date_time::months_of_year months_of_year;
//bring enum values into the namespace
using date_time::Jan;
using date_time::Feb;
using date_time::Mar;
using date_time::Apr;
using date_time::May;
using date_time::Jun;
using date_time::Jul;
using date_time::Aug;
using date_time::Sep;
using date_time::Oct;
using date_time::Nov;
using date_time::Dec;
using date_time::NotAMonth;
using date_time::NumMonths;
//! Exception thrown if a greg_month is constructed with a value out of range
struct bad_month : public std::out_of_range
{
bad_month() : std::out_of_range(std::string("Month number is out of range 1..12")) {}
};
//! Build a policy class for the greg_month_rep
typedef CV::simple_exception_policy<unsigned short, 1, 12, bad_month> greg_month_policies;
//! A constrained range that implements the gregorian_month rules
typedef CV::constrained_value<greg_month_policies> greg_month_rep;
//! Wrapper class to represent months in gregorian based calendar
class BOOST_DATE_TIME_DECL greg_month : public greg_month_rep {
public:
typedef date_time::months_of_year month_enum;
typedef std::map<std::string, unsigned short> month_map_type;
typedef lslboost::shared_ptr<month_map_type> month_map_ptr_type;
//! Construct a month from the months_of_year enumeration
greg_month(month_enum theMonth) :
greg_month_rep(static_cast<greg_month_rep::value_type>(theMonth)) {}
//! Construct from a short value
greg_month(unsigned short theMonth) : greg_month_rep(theMonth) {}
//! Convert the value back to a short
operator unsigned short() const {return value_;}
//! Returns month as number from 1 to 12
unsigned short as_number() const {return value_;}
month_enum as_enum() const {return static_cast<month_enum>(value_);}
const char* as_short_string() const;
const char* as_long_string() const;
#ifndef BOOST_NO_STD_WSTRING
const wchar_t* as_short_wstring() const;
const wchar_t* as_long_wstring() const;
#endif // BOOST_NO_STD_WSTRING
//! Shared pointer to a map of Month strings (Names & Abbrev) & numbers
static month_map_ptr_type get_month_map_ptr();
/* parameterized as_*_string functions are intended to be called
* from a template function: "... as_short_string(charT c='\0');" */
const char* as_short_string(char) const
{
return as_short_string();
}
const char* as_long_string(char) const
{
return as_long_string();
}
#ifndef BOOST_NO_STD_WSTRING
const wchar_t* as_short_string(wchar_t) const
{
return as_short_wstring();
}
const wchar_t* as_long_string(wchar_t) const
{
return as_long_wstring();
}
#endif // BOOST_NO_STD_WSTRING
};
} } //namespace gregorian
#endif
| [
"vinukondanagarjun4@gmail.com"
] | vinukondanagarjun4@gmail.com |
f250189da39de20a4448c28e9ec26ac17563d6ba | 7121e3df80afdc58fdc10c664c08aee411a78181 | /src/chrome/browser/ui/libgtkui/gtk_ui.cc | 6bc83d0bfc97104f65da0c1a78ece232bdcc5b10 | [
"BSD-3-Clause"
] | permissive | ochrisoyea/AccessControlListsintheDOM | 93d0a1f77f7f3af864d4a2942e4590af9065a7d8 | 9a8796f899592d236628f4d3007337ff5743c32f | refs/heads/master | 2020-06-08T14:31:37.838842 | 2019-06-22T16:17:41 | 2019-06-22T16:17:41 | 193,242,663 | 0 | 0 | null | 2019-06-22T14:24:31 | 2019-06-22T14:24:31 | null | UTF-8 | C++ | false | false | 43,883 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/libgtkui/gtk_ui.h"
#include <dlfcn.h>
#include <gdk/gdk.h>
#include <math.h>
#include <pango/pango.h>
#include <cmath>
#include <set>
#include <utility>
#include "base/command_line.h"
#include "base/debug/leak_annotations.h"
#include "base/environment.h"
#include "base/i18n/rtl.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/protected_memory.h"
#include "base/memory/protected_memory_cfi.h"
#include "base/nix/mime_util_xdg.h"
#include "base/nix/xdg_util.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/browser/ui/libgtkui/app_indicator_icon.h"
#include "chrome/browser/ui/libgtkui/chrome_gtk_frame.h"
#include "chrome/browser/ui/libgtkui/gtk_event_loop.h"
#include "chrome/browser/ui/libgtkui/gtk_key_bindings_handler.h"
#include "chrome/browser/ui/libgtkui/gtk_status_icon.h"
#include "chrome/browser/ui/libgtkui/gtk_util.h"
#include "chrome/browser/ui/libgtkui/print_dialog_gtk.h"
#include "chrome/browser/ui/libgtkui/printing_gtk_util.h"
#include "chrome/browser/ui/libgtkui/select_file_dialog_impl.h"
#include "chrome/browser/ui/libgtkui/skia_utils_gtk.h"
#include "chrome/browser/ui/libgtkui/unity_service.h"
#include "chrome/browser/ui/libgtkui/x11_input_method_context_impl_gtk.h"
#include "printing/buildflags/buildflags.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkShader.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/display/display.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font_render_params.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia_source.h"
#include "ui/gfx/skbitmap_operations.h"
#include "ui/gfx/skia_util.h"
#include "ui/gfx/x/x11.h"
#include "ui/gfx/x/x11_types.h"
#include "ui/native_theme/native_theme.h"
#include "ui/shell_dialogs/select_file_policy.h"
#include "ui/views/controls/button/blue_button.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/button/label_button_border.h"
#include "ui/views/linux_ui/device_scale_factor_observer.h"
#include "ui/views/linux_ui/window_button_order_observer.h"
#include "ui/views/resources/grit/views_resources.h"
#if GTK_MAJOR_VERSION == 2
#include "chrome/browser/ui/libgtkui/native_theme_gtk2.h" // nogncheck
#elif GTK_MAJOR_VERSION == 3
#include "chrome/browser/ui/libgtkui/native_theme_gtk3.h" // nogncheck
#include "chrome/browser/ui/libgtkui/nav_button_provider_gtk3.h" // nogncheck
#include "chrome/browser/ui/libgtkui/settings_provider_gtk3.h" // nogncheck
#endif
#if defined(USE_GIO)
#include "chrome/browser/ui/libgtkui/settings_provider_gsettings.h"
#endif
#if BUILDFLAG(ENABLE_PRINTING)
#include "printing/printing_context_linux.h"
#endif
#if BUILDFLAG(ENABLE_NATIVE_WINDOW_NAV_BUTTONS)
#include "chrome/browser/ui/views/nav_button_provider.h"
#endif
// A minimized port of GtkThemeService into something that can provide colors
// and images for aura.
//
// TODO(erg): There's still a lot that needs ported or done for the first time:
//
// - Render and inject the omnibox background.
// - Make sure to test with a light on dark theme, too.
namespace libgtkui {
namespace {
const double kDefaultDPI = 96;
class GtkButtonImageSource : public gfx::ImageSkiaSource {
public:
GtkButtonImageSource(const char* idr_string, gfx::Size size)
: width_(size.width()), height_(size.height()) {
is_blue_ = !!strstr(idr_string, "IDR_BLUE");
focus_ = !!strstr(idr_string, "_FOCUSED_");
if (strstr(idr_string, "_DISABLED")) {
state_ = ui::NativeTheme::kDisabled;
} else if (strstr(idr_string, "_HOVER")) {
state_ = ui::NativeTheme::kHovered;
} else if (strstr(idr_string, "_PRESSED")) {
state_ = ui::NativeTheme::kPressed;
} else {
state_ = ui::NativeTheme::kNormal;
}
}
~GtkButtonImageSource() override {}
gfx::ImageSkiaRep GetImageForScale(float scale) override {
int width = width_ * scale;
int height = height_ * scale;
SkBitmap border;
border.allocN32Pixels(width, height);
border.eraseColor(0);
cairo_surface_t* surface = cairo_image_surface_create_for_data(
static_cast<unsigned char*>(border.getAddr(0, 0)), CAIRO_FORMAT_ARGB32,
width, height, width * 4);
cairo_t* cr = cairo_create(surface);
#if GTK_MAJOR_VERSION == 2
// Create a temporary GTK button to snapshot
GtkWidget* window = gtk_offscreen_window_new();
GtkWidget* button = gtk_toggle_button_new();
if (state_ == ui::NativeTheme::kPressed)
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button), true);
else if (state_ == ui::NativeTheme::kDisabled)
gtk_widget_set_sensitive(button, false);
gtk_widget_set_size_request(button, width, height);
gtk_container_add(GTK_CONTAINER(window), button);
if (is_blue_)
TurnButtonBlue(button);
gtk_widget_show_all(window);
if (focus_)
GTK_WIDGET_SET_FLAGS(button, GTK_HAS_FOCUS);
int w, h;
GdkPixmap* pixmap;
{
// http://crbug.com/346740
ANNOTATE_SCOPED_MEMORY_LEAK;
pixmap = gtk_widget_get_snapshot(button, nullptr);
}
gdk_drawable_get_size(GDK_DRAWABLE(pixmap), &w, &h);
GdkColormap* colormap = gdk_drawable_get_colormap(pixmap);
GdkPixbuf* pixbuf = gdk_pixbuf_get_from_drawable(
nullptr, GDK_DRAWABLE(pixmap), colormap, 0, 0, 0, 0, w, h);
gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);
cairo_paint(cr);
g_object_unref(pixbuf);
g_object_unref(pixmap);
gtk_widget_destroy(window);
#else
ScopedStyleContext context = GetStyleContextFromCss(
is_blue_ ? "GtkButton#button.default.suggested-action"
: "GtkButton#button");
GtkStateFlags state_flags = StateToStateFlags(state_);
if (focus_) {
state_flags =
static_cast<GtkStateFlags>(state_flags | GTK_STATE_FLAG_FOCUSED);
}
gtk_style_context_set_state(context, state_flags);
gtk_render_background(context, cr, 0, 0, width, height);
gtk_render_frame(context, cr, 0, 0, width, height);
if (focus_) {
gfx::Rect focus_rect(width, height);
if (!GtkVersionCheck(3, 14)) {
gint focus_pad;
gtk_style_context_get_style(context, "focus-padding", &focus_pad,
nullptr);
focus_rect.Inset(focus_pad, focus_pad);
if (state_ == ui::NativeTheme::kPressed) {
gint child_displacement_x, child_displacement_y;
gboolean displace_focus;
gtk_style_context_get_style(
context, "child-displacement-x", &child_displacement_x,
"child-displacement-y", &child_displacement_y, "displace-focus",
&displace_focus, nullptr);
if (displace_focus)
focus_rect.Offset(child_displacement_x, child_displacement_y);
}
}
if (!GtkVersionCheck(3, 20)) {
GtkBorder border;
gtk_style_context_get_border(context, state_flags, &border);
focus_rect.Inset(border.left, border.top, border.right, border.bottom);
}
gtk_render_focus(context, cr, focus_rect.x(), focus_rect.y(),
focus_rect.width(), focus_rect.height());
}
#endif
cairo_destroy(cr);
cairo_surface_destroy(surface);
return gfx::ImageSkiaRep(border, scale);
}
private:
bool is_blue_;
bool focus_;
ui::NativeTheme::State state_;
int width_;
int height_;
DISALLOW_COPY_AND_ASSIGN(GtkButtonImageSource);
};
class GtkButtonPainter : public views::Painter {
public:
explicit GtkButtonPainter(std::string idr) : idr_(idr) {}
~GtkButtonPainter() override {}
gfx::Size GetMinimumSize() const override { return gfx::Size(); }
void Paint(gfx::Canvas* canvas, const gfx::Size& size) override {
gfx::ImageSkia image(
std::make_unique<GtkButtonImageSource>(idr_.c_str(), size), 1);
canvas->DrawImageInt(image, 0, 0);
}
private:
std::string idr_;
DISALLOW_COPY_AND_ASSIGN(GtkButtonPainter);
};
struct GObjectDeleter {
void operator()(void* ptr) { g_object_unref(ptr); }
};
struct GtkIconInfoDeleter {
void operator()(GtkIconInfo* ptr) {
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
gtk_icon_info_free(ptr);
G_GNUC_END_IGNORE_DEPRECATIONS
}
};
typedef std::unique_ptr<GIcon, GObjectDeleter> ScopedGIcon;
typedef std::unique_ptr<GtkIconInfo, GtkIconInfoDeleter> ScopedGtkIconInfo;
typedef std::unique_ptr<GdkPixbuf, GObjectDeleter> ScopedGdkPixbuf;
// Prefix for app indicator ids
const char kAppIndicatorIdPrefix[] = "chrome_app_indicator_";
// Number of app indicators used (used as part of app-indicator id).
int indicators_count;
// The unknown content type.
const char* kUnknownContentType = "application/octet-stream";
std::unique_ptr<SettingsProvider> CreateSettingsProvider(GtkUi* gtk_ui) {
#if GTK_MAJOR_VERSION == 3
if (GtkVersionCheck(3, 14))
return std::make_unique<SettingsProviderGtk3>(gtk_ui);
#endif
#if defined(USE_GIO)
return std::make_unique<SettingsProviderGSettings>(gtk_ui);
#else
return nullptr;
#endif
}
// Returns a gfx::FontRenderParams corresponding to GTK's configuration.
gfx::FontRenderParams GetGtkFontRenderParams() {
GtkSettings* gtk_settings = gtk_settings_get_default();
CHECK(gtk_settings);
gint antialias = 0;
gint hinting = 0;
gchar* hint_style = nullptr;
gchar* rgba = nullptr;
g_object_get(gtk_settings, "gtk-xft-antialias", &antialias, "gtk-xft-hinting",
&hinting, "gtk-xft-hintstyle", &hint_style, "gtk-xft-rgba",
&rgba, nullptr);
gfx::FontRenderParams params;
params.antialiasing = antialias != 0;
if (hinting == 0 || !hint_style || strcmp(hint_style, "hintnone") == 0) {
params.hinting = gfx::FontRenderParams::HINTING_NONE;
} else if (strcmp(hint_style, "hintslight") == 0) {
params.hinting = gfx::FontRenderParams::HINTING_SLIGHT;
} else if (strcmp(hint_style, "hintmedium") == 0) {
params.hinting = gfx::FontRenderParams::HINTING_MEDIUM;
} else if (strcmp(hint_style, "hintfull") == 0) {
params.hinting = gfx::FontRenderParams::HINTING_FULL;
} else {
LOG(WARNING) << "Unexpected gtk-xft-hintstyle \"" << hint_style << "\"";
params.hinting = gfx::FontRenderParams::HINTING_NONE;
}
if (!rgba || strcmp(rgba, "none") == 0) {
params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
} else if (strcmp(rgba, "rgb") == 0) {
params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB;
} else if (strcmp(rgba, "bgr") == 0) {
params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR;
} else if (strcmp(rgba, "vrgb") == 0) {
params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB;
} else if (strcmp(rgba, "vbgr") == 0) {
params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR;
} else {
LOG(WARNING) << "Unexpected gtk-xft-rgba \"" << rgba << "\"";
params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE;
}
g_free(hint_style);
g_free(rgba);
return params;
}
views::LinuxUI::NonClientWindowFrameAction GetDefaultMiddleClickAction() {
#if GTK_MAJOR_VERSION == 3
if (GtkVersionCheck(3, 14))
return views::LinuxUI::WINDOW_FRAME_ACTION_NONE;
#endif
std::unique_ptr<base::Environment> env(base::Environment::Create());
switch (base::nix::GetDesktopEnvironment(env.get())) {
case base::nix::DESKTOP_ENVIRONMENT_KDE4:
case base::nix::DESKTOP_ENVIRONMENT_KDE5:
// Starting with KDE 4.4, windows' titlebars can be dragged with the
// middle mouse button to create tab groups. We don't support that in
// Chrome, but at least avoid lowering windows in response to middle
// clicks to avoid surprising users who expect the KDE behavior.
return views::LinuxUI::WINDOW_FRAME_ACTION_NONE;
default:
return views::LinuxUI::WINDOW_FRAME_ACTION_LOWER;
}
}
#if GTK_MAJOR_VERSION > 2
// COLOR_TOOLBAR_TOP_SEPARATOR represents the border between tabs and the
// frame, as well as the border between tabs and the toolbar. For this
// reason, it is difficult to calculate the One True Color that works well on
// all themes and is opaque. However, we can cheat to get a good color that
// works well for both borders. The idea is we have two variables: alpha and
// lightness. And we have two constraints (on lightness):
// 1. the border color, when painted on |header_bg|, should give |header_fg|
// 2. the border color, when painted on |tab_bg|, should give |tab_fg|
// This gives the equations:
// alpha*lightness + (1 - alpha)*header_bg = header_fg
// alpha*lightness + (1 - alpha)*tab_bg = tab_fg
// The algorithm below is just a result of solving those equations for alpha
// and lightness. If a problem is encountered, like division by zero, or
// |a| or |l| not in [0, 1], then fallback on |header_fg| or |tab_fg|.
SkColor GetToolbarTopSeparatorColor(SkColor header_fg,
SkColor header_bg,
SkColor tab_fg,
SkColor tab_bg) {
using namespace color_utils;
SkColor default_color = SkColorGetA(header_fg) ? header_fg : tab_fg;
if (!SkColorGetA(default_color))
return SK_ColorTRANSPARENT;
auto get_lightness = [](SkColor color) {
HSL hsl;
SkColorToHSL(color, &hsl);
return hsl.l;
};
double f1 = get_lightness(GetResultingPaintColor(header_fg, header_bg));
double b1 = get_lightness(header_bg);
double f2 = get_lightness(GetResultingPaintColor(tab_fg, tab_bg));
double b2 = get_lightness(tab_bg);
if (b1 == b2)
return default_color;
double a = (f1 - f2 - b1 + b2) / (b2 - b1);
if (a == 0)
return default_color;
double l = (f1 - (1 - a) * b1) / a;
if (a < 0 || a > 1 || l < 0 || l > 1)
return default_color;
// Take the hue and saturation from |default_color|, but use the
// calculated lightness.
HSL border;
SkColorToHSL(default_color, &border);
border.l = l;
return HSLToSkColor(border, a * 0xff);
}
#endif
#if GTK_MAJOR_VERSION > 2
using GdkSetAllowedBackendsFn = void (*)(const gchar*);
// Place this function pointers in read-only memory after being resolved to
// prevent it being tampered with. See crbug.com/771365 for details.
PROTECTED_MEMORY_SECTION base::ProtectedMemory<GdkSetAllowedBackendsFn>
g_gdk_set_allowed_backends;
#endif
} // namespace
GtkUi::GtkUi() {
window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_DOUBLE_CLICK] =
views::LinuxUI::WINDOW_FRAME_ACTION_TOGGLE_MAXIMIZE;
window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_MIDDLE_CLICK] =
GetDefaultMiddleClickAction();
window_frame_actions_[WINDOW_FRAME_ACTION_SOURCE_RIGHT_CLICK] =
views::LinuxUI::WINDOW_FRAME_ACTION_MENU;
#if GTK_MAJOR_VERSION > 2
// Force Gtk to use Xwayland if it would have used wayland. libgtkui assumes
// the use of X11 (eg. X11InputMethodContextImplGtk) and will crash under
// other backends.
// TODO(thomasanderson): Change this logic once Wayland support is added.
static base::ProtectedMemory<GdkSetAllowedBackendsFn>::Initializer init(
&g_gdk_set_allowed_backends,
reinterpret_cast<void (*)(const gchar*)>(
dlsym(GetGdkSharedLibrary(), "gdk_set_allowed_backends")));
if (GtkVersionCheck(3, 10))
DCHECK(*g_gdk_set_allowed_backends);
if (*g_gdk_set_allowed_backends)
base::UnsanitizedCfiCall(g_gdk_set_allowed_backends)("x11");
#endif
#if GTK_MAJOR_VERSION >= 3
// Avoid GTK initializing atk-bridge, and let AuraLinux implementation
// do it once it is ready.
std::unique_ptr<base::Environment> env(base::Environment::Create());
env->SetVar("NO_AT_BRIDGE", "1");
#endif
GtkInitFromCommandLine(*base::CommandLine::ForCurrentProcess());
#if GTK_MAJOR_VERSION == 2
native_theme_ = NativeThemeGtk2::instance();
fake_window_ = chrome_gtk_frame_new();
#elif GTK_MAJOR_VERSION == 3
native_theme_ = NativeThemeGtk3::instance();
fake_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL);
#else
#error "Unsupported GTK version"
#endif
gtk_widget_realize(fake_window_);
}
GtkUi::~GtkUi() {
gtk_widget_destroy(fake_window_);
}
void OnThemeChanged(GObject* obj, GParamSpec* param, GtkUi* gtkui) {
gtkui->ResetStyle();
}
void GtkUi::Initialize() {
GtkSettings* settings = gtk_settings_get_default();
g_signal_connect_after(settings, "notify::gtk-theme-name",
G_CALLBACK(OnThemeChanged), this);
g_signal_connect_after(settings, "notify::gtk-icon-theme-name",
G_CALLBACK(OnThemeChanged), this);
GdkScreen* screen = gdk_screen_get_default();
// Listen for DPI changes.
g_signal_connect_after(screen, "notify::resolution",
G_CALLBACK(OnDeviceScaleFactorMaybeChangedThunk),
this);
// Listen for scale factor changes. We would prefer to listen on
// |screen|, but there is no scale-factor property, so use an
// unmapped window instead.
g_signal_connect(fake_window_, "notify::scale-factor",
G_CALLBACK(OnDeviceScaleFactorMaybeChangedThunk), this);
LoadGtkValues();
#if BUILDFLAG(ENABLE_PRINTING)
printing::PrintingContextLinux::SetCreatePrintDialogFunction(
&PrintDialogGtk2::CreatePrintDialog);
printing::PrintingContextLinux::SetPdfPaperSizeFunction(
&GetPdfPaperSizeDeviceUnitsGtk);
#endif
// We must build this after GTK gets initialized.
settings_provider_ = CreateSettingsProvider(this);
indicators_count = 0;
// Instantiate the singleton instance of Gtk2EventLoop.
Gtk2EventLoop::GetInstance();
}
bool GtkUi::GetTint(int id, color_utils::HSL* tint) const {
switch (id) {
// Tints for which the cross-platform default is fine. Before adding new
// values here, specifically verify they work well on Linux.
case ThemeProperties::TINT_BACKGROUND_TAB:
// TODO(estade): Return something useful for TINT_BUTTONS so that chrome://
// page icons are colored appropriately.
case ThemeProperties::TINT_BUTTONS:
break;
default:
// Assume any tints not specifically verified on Linux aren't usable.
// TODO(pkasting): Try to remove values from |colors_| that could just be
// added to the group above instead.
NOTREACHED();
}
return false;
}
bool GtkUi::GetColor(int id, SkColor* color) const {
ColorMap::const_iterator it = colors_.find(id);
if (it != colors_.end()) {
*color = it->second;
return true;
}
return false;
}
SkColor GtkUi::GetFocusRingColor() const {
return focus_ring_color_;
}
SkColor GtkUi::GetThumbActiveColor() const {
return thumb_active_color_;
}
SkColor GtkUi::GetThumbInactiveColor() const {
return thumb_inactive_color_;
}
SkColor GtkUi::GetTrackColor() const {
return track_color_;
}
SkColor GtkUi::GetActiveSelectionBgColor() const {
return active_selection_bg_color_;
}
SkColor GtkUi::GetActiveSelectionFgColor() const {
return active_selection_fg_color_;
}
SkColor GtkUi::GetInactiveSelectionBgColor() const {
return inactive_selection_bg_color_;
}
SkColor GtkUi::GetInactiveSelectionFgColor() const {
return inactive_selection_fg_color_;
}
base::TimeDelta GtkUi::GetCursorBlinkInterval() const {
// From http://library.gnome.org/devel/gtk/unstable/GtkSettings.html, this is
// the default value for gtk-cursor-blink-time.
static const gint kGtkDefaultCursorBlinkTime = 1200;
// Dividing GTK's cursor blink cycle time (in milliseconds) by this value
// yields an appropriate value for
// content::RendererPreferences::caret_blink_interval. This matches the
// logic in the WebKit GTK port.
static const double kGtkCursorBlinkCycleFactor = 2000.0;
gint cursor_blink_time = kGtkDefaultCursorBlinkTime;
gboolean cursor_blink = TRUE;
g_object_get(gtk_settings_get_default(), "gtk-cursor-blink-time",
&cursor_blink_time, "gtk-cursor-blink", &cursor_blink, nullptr);
return cursor_blink ? base::TimeDelta::FromSecondsD(
cursor_blink_time / kGtkCursorBlinkCycleFactor)
: base::TimeDelta();
}
ui::NativeTheme* GtkUi::GetNativeTheme(aura::Window* window) const {
ui::NativeTheme* native_theme_override = nullptr;
if (!native_theme_overrider_.is_null())
native_theme_override = native_theme_overrider_.Run(window);
if (native_theme_override)
return native_theme_override;
return native_theme_;
}
void GtkUi::SetNativeThemeOverride(const NativeThemeGetter& callback) {
native_theme_overrider_ = callback;
}
bool GtkUi::GetDefaultUsesSystemTheme() const {
std::unique_ptr<base::Environment> env(base::Environment::Create());
switch (base::nix::GetDesktopEnvironment(env.get())) {
case base::nix::DESKTOP_ENVIRONMENT_CINNAMON:
case base::nix::DESKTOP_ENVIRONMENT_GNOME:
case base::nix::DESKTOP_ENVIRONMENT_PANTHEON:
case base::nix::DESKTOP_ENVIRONMENT_UNITY:
case base::nix::DESKTOP_ENVIRONMENT_XFCE:
return true;
case base::nix::DESKTOP_ENVIRONMENT_KDE3:
case base::nix::DESKTOP_ENVIRONMENT_KDE4:
case base::nix::DESKTOP_ENVIRONMENT_KDE5:
case base::nix::DESKTOP_ENVIRONMENT_OTHER:
return false;
}
// Unless GetDesktopEnvironment() badly misbehaves, this should never happen.
NOTREACHED();
return false;
}
void GtkUi::SetDownloadCount(int count) const {
if (unity::IsRunning())
unity::SetDownloadCount(count);
}
void GtkUi::SetProgressFraction(float percentage) const {
if (unity::IsRunning())
unity::SetProgressFraction(percentage);
}
bool GtkUi::IsStatusIconSupported() const {
return true;
}
std::unique_ptr<views::StatusIconLinux> GtkUi::CreateLinuxStatusIcon(
const gfx::ImageSkia& image,
const base::string16& tool_tip) const {
if (AppIndicatorIcon::CouldOpen()) {
++indicators_count;
return std::unique_ptr<views::StatusIconLinux>(new AppIndicatorIcon(
base::StringPrintf("%s%d", kAppIndicatorIdPrefix, indicators_count),
image, tool_tip));
} else {
return std::unique_ptr<views::StatusIconLinux>(
new Gtk2StatusIcon(image, tool_tip));
}
}
gfx::Image GtkUi::GetIconForContentType(const std::string& content_type,
int size) const {
// This call doesn't take a reference.
GtkIconTheme* theme = gtk_icon_theme_get_default();
std::string content_types[] = {content_type, kUnknownContentType};
for (size_t i = 0; i < arraysize(content_types); ++i) {
ScopedGIcon icon(g_content_type_get_icon(content_types[i].c_str()));
ScopedGtkIconInfo icon_info(gtk_icon_theme_lookup_by_gicon(
theme, icon.get(), size,
static_cast<GtkIconLookupFlags>(GTK_ICON_LOOKUP_FORCE_SIZE)));
if (!icon_info)
continue;
ScopedGdkPixbuf pixbuf(gtk_icon_info_load_icon(icon_info.get(), nullptr));
if (!pixbuf)
continue;
SkBitmap bitmap = GdkPixbufToImageSkia(pixbuf.get());
DCHECK_EQ(size, bitmap.width());
DCHECK_EQ(size, bitmap.height());
gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap);
image_skia.MakeThreadSafe();
return gfx::Image(image_skia);
}
return gfx::Image();
}
std::unique_ptr<views::Border> GtkUi::CreateNativeBorder(
views::LabelButton* owning_button,
std::unique_ptr<views::LabelButtonBorder> border) {
if (owning_button->GetNativeTheme() != native_theme_)
return std::move(border);
std::unique_ptr<views::LabelButtonAssetBorder> gtk_border(
new views::LabelButtonAssetBorder(owning_button->style()));
gtk_border->set_insets(border->GetInsets());
static struct {
const char* idr;
const char* idr_blue;
bool focus;
views::Button::ButtonState state;
} const paintstate[] = {
{
"IDR_BUTTON_NORMAL", "IDR_BLUE_BUTTON_NORMAL", false,
views::Button::STATE_NORMAL,
},
{
"IDR_BUTTON_HOVER", "IDR_BLUE_BUTTON_HOVER", false,
views::Button::STATE_HOVERED,
},
{
"IDR_BUTTON_PRESSED", "IDR_BLUE_BUTTON_PRESSED", false,
views::Button::STATE_PRESSED,
},
{
"IDR_BUTTON_DISABLED", "IDR_BLUE_BUTTON_DISABLED", false,
views::Button::STATE_DISABLED,
},
{
"IDR_BUTTON_FOCUSED_NORMAL", "IDR_BLUE_BUTTON_FOCUSED_NORMAL", true,
views::Button::STATE_NORMAL,
},
{
"IDR_BUTTON_FOCUSED_HOVER", "IDR_BLUE_BUTTON_FOCUSED_HOVER", true,
views::Button::STATE_HOVERED,
},
{
"IDR_BUTTON_FOCUSED_PRESSED", "IDR_BLUE_BUTTON_FOCUSED_PRESSED", true,
views::Button::STATE_PRESSED,
},
{
"IDR_BUTTON_DISABLED", "IDR_BLUE_BUTTON_DISABLED", true,
views::Button::STATE_DISABLED,
},
};
bool is_blue =
owning_button->GetClassName() == views::BlueButton::kViewClassName;
for (unsigned i = 0; i < arraysize(paintstate); i++) {
std::string idr = is_blue ? paintstate[i].idr_blue : paintstate[i].idr;
gtk_border->SetPainter(
paintstate[i].focus, paintstate[i].state,
border->PaintsButtonState(paintstate[i].focus, paintstate[i].state)
? std::make_unique<GtkButtonPainter>(idr)
: nullptr);
}
return std::move(gtk_border);
}
void GtkUi::AddWindowButtonOrderObserver(
views::WindowButtonOrderObserver* observer) {
if (nav_buttons_set_)
observer->OnWindowButtonOrderingChange(leading_buttons_, trailing_buttons_);
window_button_order_observer_list_.AddObserver(observer);
}
void GtkUi::RemoveWindowButtonOrderObserver(
views::WindowButtonOrderObserver* observer) {
window_button_order_observer_list_.RemoveObserver(observer);
}
void GtkUi::SetWindowButtonOrdering(
const std::vector<views::FrameButton>& leading_buttons,
const std::vector<views::FrameButton>& trailing_buttons) {
leading_buttons_ = leading_buttons;
trailing_buttons_ = trailing_buttons;
nav_buttons_set_ = true;
for (views::WindowButtonOrderObserver& observer :
window_button_order_observer_list_) {
observer.OnWindowButtonOrderingChange(leading_buttons_, trailing_buttons_);
}
}
void GtkUi::SetNonClientWindowFrameAction(
NonClientWindowFrameActionSourceType source,
NonClientWindowFrameAction action) {
window_frame_actions_[source] = action;
}
std::unique_ptr<ui::LinuxInputMethodContext> GtkUi::CreateInputMethodContext(
ui::LinuxInputMethodContextDelegate* delegate,
bool is_simple) const {
return std::unique_ptr<ui::LinuxInputMethodContext>(
new X11InputMethodContextImplGtk2(delegate, is_simple));
}
gfx::FontRenderParams GtkUi::GetDefaultFontRenderParams() const {
static gfx::FontRenderParams params = GetGtkFontRenderParams();
return params;
}
void GtkUi::GetDefaultFontDescription(std::string* family_out,
int* size_pixels_out,
int* style_out,
gfx::Font::Weight* weight_out,
gfx::FontRenderParams* params_out) const {
*family_out = default_font_family_;
*size_pixels_out = default_font_size_pixels_;
*style_out = default_font_style_;
*weight_out = default_font_weight_;
*params_out = default_font_render_params_;
}
ui::SelectFileDialog* GtkUi::CreateSelectFileDialog(
ui::SelectFileDialog::Listener* listener,
std::unique_ptr<ui::SelectFilePolicy> policy) const {
return SelectFileDialogImpl::Create(listener, std::move(policy));
}
views::LinuxUI::NonClientWindowFrameAction GtkUi::GetNonClientWindowFrameAction(
NonClientWindowFrameActionSourceType source) {
return window_frame_actions_[source];
}
void GtkUi::NotifyWindowManagerStartupComplete() {
// TODO(port) Implement this using _NET_STARTUP_INFO_BEGIN/_NET_STARTUP_INFO
// from http://standards.freedesktop.org/startup-notification-spec/ instead.
gdk_notify_startup_complete();
}
void GtkUi::AddDeviceScaleFactorObserver(
views::DeviceScaleFactorObserver* observer) {
device_scale_factor_observer_list_.AddObserver(observer);
}
void GtkUi::RemoveDeviceScaleFactorObserver(
views::DeviceScaleFactorObserver* observer) {
device_scale_factor_observer_list_.RemoveObserver(observer);
}
bool GtkUi::PreferDarkTheme() const {
gboolean dark = false;
g_object_get(gtk_settings_get_default(), "gtk-application-prefer-dark-theme",
&dark, nullptr);
return dark;
}
#if BUILDFLAG(ENABLE_NATIVE_WINDOW_NAV_BUTTONS)
std::unique_ptr<views::NavButtonProvider> GtkUi::CreateNavButtonProvider() {
if (GtkVersionCheck(3, 14))
return std::make_unique<libgtkui::NavButtonProviderGtk3>();
return nullptr;
}
#endif
base::flat_map<std::string, std::string> GtkUi::GetKeyboardLayoutMap() {
GdkDisplay* display = gdk_display_get_default();
GdkKeymap* keymap = gdk_keymap_get_for_display(display);
auto map = base::flat_map<std::string, std::string>();
if (!keymap)
return map;
for (unsigned int i = 0; i < ui::kWritingSystemKeyDomCodeEntries; ++i) {
ui::DomCode domcode = ui::writing_system_key_domcodes[i];
guint16 keycode = ui::KeycodeConverter::DomCodeToNativeKeycode(domcode);
GdkKeymapKey* keys = nullptr;
guint* keyvals = nullptr;
gint n_entries = 0;
// The order of the layouts is based on the system default ordering in
// Keyboard Settings. The currently active layout does not affect this
// order.
if (gdk_keymap_get_entries_for_keycode(keymap, keycode, &keys, &keyvals,
&n_entries)) {
for (gint i = 0; i < n_entries; ++i) {
// There are 4 entries per layout, one each for shift level 0..3.
// We only care about the unshifted values (level = 0).
if (keys[i].level != 0 || keyvals[i] >= 255)
continue;
char keystring[2];
keystring[0] = keyvals[i];
keystring[1] = '\0';
map.emplace(ui::KeycodeConverter::DomCodeToCodeString(domcode),
keystring);
break;
}
}
g_free(keys);
keys = nullptr;
g_free(keyvals);
keyvals = nullptr;
}
return map;
}
bool GtkUi::MatchEvent(const ui::Event& event,
std::vector<ui::TextEditCommandAuraLinux>* commands) {
// Ensure that we have a keyboard handler.
if (!key_bindings_handler_)
key_bindings_handler_.reset(new Gtk2KeyBindingsHandler);
return key_bindings_handler_->MatchEvent(event, commands);
}
void GtkUi::OnDeviceScaleFactorMaybeChanged(void*, GParamSpec*) {
UpdateDeviceScaleFactor();
}
void GtkUi::SetScrollbarColors() {
thumb_active_color_ = SkColorSetRGB(244, 244, 244);
thumb_inactive_color_ = SkColorSetRGB(234, 234, 234);
track_color_ = SkColorSetRGB(211, 211, 211);
GetChromeStyleColor("scrollbar-slider-prelight-color", &thumb_active_color_);
GetChromeStyleColor("scrollbar-slider-normal-color", &thumb_inactive_color_);
GetChromeStyleColor("scrollbar-trough-color", &track_color_);
}
void GtkUi::LoadGtkValues() {
// TODO(erg): GtkThemeService had a comment here about having to muck with
// the raw Prefs object to remove prefs::kCurrentThemeImages or else we'd
// regress startup time. Figure out how to do that when we can't access the
// prefs system from here.
UpdateDeviceScaleFactor();
UpdateCursorTheme();
#if GTK_MAJOR_VERSION == 2
const color_utils::HSL kDefaultFrameShift = {-1, -1, 0.4};
SkColor frame_color =
native_theme_->GetSystemColor(ui::NativeTheme::kColorId_WindowBackground);
frame_color = color_utils::HSLShift(frame_color, kDefaultFrameShift);
GetChromeStyleColor("frame-color", &frame_color);
colors_[ThemeProperties::COLOR_FRAME] = frame_color;
GtkStyle* style = gtk_rc_get_style(fake_window_);
SkColor temp_color = color_utils::HSLShift(
GdkColorToSkColor(style->bg[GTK_STATE_INSENSITIVE]), kDefaultFrameShift);
GetChromeStyleColor("inactive-frame-color", &temp_color);
colors_[ThemeProperties::COLOR_FRAME_INACTIVE] = temp_color;
temp_color = color_utils::HSLShift(frame_color, kDefaultTintFrameIncognito);
GetChromeStyleColor("incognito-frame-color", &temp_color);
colors_[ThemeProperties::COLOR_FRAME_INCOGNITO] = temp_color;
temp_color =
color_utils::HSLShift(frame_color, kDefaultTintFrameIncognitoInactive);
GetChromeStyleColor("incognito-inactive-frame-color", &temp_color);
colors_[ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE] = temp_color;
SkColor tab_color =
native_theme_->GetSystemColor(ui::NativeTheme::kColorId_DialogBackground);
SkColor label_color = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_LabelEnabledColor);
colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON] =
color_utils::DeriveDefaultIconColor(label_color);
colors_[ThemeProperties::COLOR_TAB_TEXT] = label_color;
colors_[ThemeProperties::COLOR_BOOKMARK_TEXT] = label_color;
colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
color_utils::BlendTowardOppositeLuma(label_color, 50);
inactive_selection_bg_color_ = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldReadOnlyBackground);
inactive_selection_fg_color_ = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldReadOnlyColor);
// We pick the text and background colors for the NTP out of the
// colors for a GtkEntry. We do this because GtkEntries background
// color is never the same as |tab_color|, is usually a white,
// and when it isn't a white, provides sufficient contrast to
// |tab_color|. Try this out with Darklooks, HighContrastInverse
// or ThinIce.
colors_[ThemeProperties::COLOR_NTP_BACKGROUND] =
native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldDefaultBackground);
colors_[ThemeProperties::COLOR_NTP_TEXT] = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldDefaultColor);
// The NTP header is the color that surrounds the current active
// thumbnail on the NTP, and acts as the border of the "Recent
// Links" box. It would be awesome if they were separated so we
// could use GetBorderColor() for the border around the "Recent
// Links" section, but matching the frame color is more important.
colors_[ThemeProperties::COLOR_NTP_HEADER] =
colors_[ThemeProperties::COLOR_FRAME];
#else
std::string header_selector = GtkVersionCheck(3, 10)
? "#headerbar.header-bar.titlebar"
: "GtkMenuBar#menubar";
SkColor frame_color = GetBgColor(header_selector);
SkColor frame_color_inactive = GetBgColor(header_selector + ":backdrop");
colors_[ThemeProperties::COLOR_FRAME] = frame_color;
colors_[ThemeProperties::COLOR_FRAME_INACTIVE] = frame_color_inactive;
colors_[ThemeProperties::COLOR_FRAME_INCOGNITO] =
color_utils::HSLShift(frame_color, kDefaultTintFrameIncognito);
colors_[ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE] =
color_utils::HSLShift(frame_color_inactive, kDefaultTintFrameIncognito);
SkColor tab_color = GetBgColor("");
SkColor tab_text_color = GetFgColor("GtkLabel");
colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON] = tab_text_color;
colors_[ThemeProperties::COLOR_TAB_TEXT] = tab_text_color;
colors_[ThemeProperties::COLOR_BOOKMARK_TEXT] = tab_text_color;
colors_[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] =
color_utils::BlendTowardOppositeLuma(tab_text_color, 50);
SkColor location_bar_border = GetBorderColor("GtkEntry#entry");
if (SkColorGetA(location_bar_border))
colors_[ThemeProperties::COLOR_LOCATION_BAR_BORDER] = location_bar_border;
inactive_selection_bg_color_ = GetSelectionBgColor(
GtkVersionCheck(3, 20) ? "GtkTextView#textview.view:backdrop "
"#text:backdrop #selection:backdrop"
: "GtkTextView.view:selected:backdrop");
inactive_selection_fg_color_ =
GetFgColor(GtkVersionCheck(3, 20) ? "GtkTextView#textview.view:backdrop "
"#text:backdrop #selection:backdrop"
: "GtkTextView.view:selected:backdrop");
SkColor tab_border = GetBorderColor("GtkButton#button");
colors_[ThemeProperties::COLOR_DETACHED_BOOKMARK_BAR_BACKGROUND] = tab_color;
colors_[ThemeProperties::COLOR_BOOKMARK_BAR_INSTRUCTIONS_TEXT] =
tab_text_color;
// Separates the toolbar from the bookmark bar or butter bars.
colors_[ThemeProperties::COLOR_TOOLBAR_BOTTOM_SEPARATOR] = tab_border;
// Separates entries in the downloads bar.
colors_[ThemeProperties::COLOR_TOOLBAR_VERTICAL_SEPARATOR] = tab_border;
// These colors represent the border drawn around tabs and between
// the tabstrip and toolbar.
SkColor toolbar_top_separator = GetToolbarTopSeparatorColor(
GetBorderColor(header_selector + " GtkButton#button"), frame_color,
tab_border, tab_color);
SkColor toolbar_top_separator_inactive = GetToolbarTopSeparatorColor(
GetBorderColor(header_selector + ":backdrop GtkButton#button"),
frame_color_inactive, tab_border, tab_color);
// Unlike with toolbars, we always want a border around tabs, so let
// ThemeService choose the border color if the theme doesn't provide one.
if (SkColorGetA(toolbar_top_separator) &&
SkColorGetA(toolbar_top_separator_inactive)) {
colors_[ThemeProperties::COLOR_TOOLBAR_TOP_SEPARATOR] =
toolbar_top_separator;
colors_[ThemeProperties::COLOR_TOOLBAR_TOP_SEPARATOR_INACTIVE] =
toolbar_top_separator_inactive;
}
colors_[ThemeProperties::COLOR_NTP_BACKGROUND] =
native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldDefaultBackground);
colors_[ThemeProperties::COLOR_NTP_TEXT] = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldDefaultColor);
colors_[ThemeProperties::COLOR_NTP_HEADER] =
GetBorderColor("GtkButton#button");
#endif
colors_[ThemeProperties::COLOR_TOOLBAR] = tab_color;
colors_[ThemeProperties::COLOR_CONTROL_BACKGROUND] = tab_color;
colors_[ThemeProperties::COLOR_NTP_LINK] = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused);
// Generate the colors that we pass to WebKit.
SetScrollbarColors();
focus_ring_color_ = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_FocusedBorderColor);
// Some GTK themes only define the text selection colors on the GtkEntry
// class, so we need to use that for getting selection colors.
active_selection_bg_color_ = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused);
active_selection_fg_color_ = native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_TextfieldSelectionColor);
colors_[ThemeProperties::COLOR_TAB_THROBBER_SPINNING] =
native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_ThrobberSpinningColor);
colors_[ThemeProperties::COLOR_TAB_THROBBER_WAITING] =
native_theme_->GetSystemColor(
ui::NativeTheme::kColorId_ThrobberWaitingColor);
}
void GtkUi::UpdateCursorTheme() {
GtkSettings* settings = gtk_settings_get_default();
gchar* theme = nullptr;
gint size = 0;
g_object_get(settings, "gtk-cursor-theme-name", &theme,
"gtk-cursor-theme-size", &size, nullptr);
if (theme)
XcursorSetTheme(gfx::GetXDisplay(), theme);
if (size)
XcursorSetDefaultSize(gfx::GetXDisplay(), size);
g_free(theme);
}
void GtkUi::UpdateDefaultFont() {
gfx::SetFontRenderParamsDeviceScaleFactor(device_scale_factor_);
GtkWidget* fake_label = gtk_label_new(nullptr);
g_object_ref_sink(fake_label); // Remove the floating reference.
PangoContext* pc = gtk_widget_get_pango_context(fake_label);
const PangoFontDescription* desc = pango_context_get_font_description(pc);
// Use gfx::FontRenderParams to select a family and determine the rendering
// settings.
gfx::FontRenderParamsQuery query;
query.families =
base::SplitString(pango_font_description_get_family(desc), ",",
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (pango_font_description_get_size_is_absolute(desc)) {
// If the size is absolute, it's specified in Pango units. There are
// PANGO_SCALE Pango units in a device unit (pixel).
const int size_pixels = pango_font_description_get_size(desc) / PANGO_SCALE;
default_font_size_pixels_ = size_pixels;
query.pixel_size = size_pixels;
} else {
// Non-absolute sizes are in points (again scaled by PANGO_SIZE).
// Round the value when converting to pixels to match GTK's logic.
const double size_points = pango_font_description_get_size(desc) /
static_cast<double>(PANGO_SCALE);
default_font_size_pixels_ =
static_cast<int>(kDefaultDPI / 72.0 * size_points + 0.5);
query.point_size = static_cast<int>(size_points);
}
query.style = gfx::Font::NORMAL;
query.weight =
static_cast<gfx::Font::Weight>(pango_font_description_get_weight(desc));
// TODO(davemoore): What about PANGO_STYLE_OBLIQUE?
if (pango_font_description_get_style(desc) == PANGO_STYLE_ITALIC)
query.style |= gfx::Font::ITALIC;
default_font_render_params_ =
gfx::GetFontRenderParams(query, &default_font_family_);
default_font_style_ = query.style;
gtk_widget_destroy(fake_label);
g_object_unref(fake_label);
}
bool GtkUi::GetChromeStyleColor(const char* style_property,
SkColor* ret_color) const {
#if GTK_MAJOR_VERSION == 2
GdkColor* style_color = nullptr;
gtk_widget_style_get(fake_window_, style_property, &style_color, nullptr);
if (style_color) {
*ret_color = GdkColorToSkColor(*style_color);
gdk_color_free(style_color);
return true;
}
#endif
return false;
}
void GtkUi::ResetStyle() {
LoadGtkValues();
native_theme_->NotifyObservers();
}
float GtkUi::GetRawDeviceScaleFactor() {
if (display::Display::HasForceDeviceScaleFactor())
return display::Display::GetForcedDeviceScaleFactor();
#if GTK_MAJOR_VERSION == 2
GtkSettings* gtk_settings = gtk_settings_get_default();
gint gtk_dpi = -1;
g_object_get(gtk_settings, "gtk-xft-dpi", >k_dpi, nullptr);
const float scale_factor = gtk_dpi / (1024 * kDefaultDPI);
#else
GdkScreen* screen = gdk_screen_get_default();
gint scale = gtk_widget_get_scale_factor(fake_window_);
DCHECK_GT(scale, 0);
gdouble resolution = gdk_screen_get_resolution(screen);
const float scale_factor =
resolution <= 0 ? scale : resolution * scale / kDefaultDPI;
#endif
// Blacklist scaling factors <120% (crbug.com/484400) and round
// to 1 decimal to prevent rendering problems (crbug.com/485183).
return scale_factor < 1.2f ? 1.0f : roundf(scale_factor * 10) / 10;
}
void GtkUi::UpdateDeviceScaleFactor() {
float old_device_scale_factor = device_scale_factor_;
device_scale_factor_ = GetRawDeviceScaleFactor();
if (device_scale_factor_ != old_device_scale_factor) {
for (views::DeviceScaleFactorObserver& observer :
device_scale_factor_observer_list_) {
observer.OnDeviceScaleFactorChanged();
}
}
UpdateDefaultFont();
}
float GtkUi::GetDeviceScaleFactor() const {
return device_scale_factor_;
}
} // namespace libgtkui
views::LinuxUI* BuildGtkUi() {
return new libgtkui::GtkUi;
}
| [
"heatherfarrar.ima@gmail.com"
] | heatherfarrar.ima@gmail.com |
3ebeedf97df49842ffcfcfedb7331250015f06c8 | 07a72a30913757756484c60402007ad39154b2f4 | /Spider/Worker.cpp | 8d00a3dde2098813a7445d44b10b6d05d789e695 | [] | no_license | SammyEnigma/ImageSpider | d767275feea58f5d0a8b40f7cbb49ec70d02f341 | 6bf4e9d8085ec080d9f9bc06fb083a23153bb827 | refs/heads/master | 2021-07-20T03:26:27.602635 | 2016-02-20T03:43:56 | 2016-02-20T03:43:56 | 223,331,944 | 0 | 0 | null | 2020-08-01T12:57:47 | 2019-11-22T05:43:19 | null | UTF-8 | C++ | false | false | 1,681 | cpp | #include "Worker.h"
Worker::Worker(QObject *parent) : QObject(parent)
{
//http://sexy.faceks.com/
//http://www.2xiezhen.com/meinvxiezhen/
startUrl = QUrl("http://sexy.faceks.com/");
// startUrl = QUrl("http://www.2xiezhen.com/meinvxiezhen/");
QString referer = "http://" + startUrl.host();
DataQueue::data()->appendUrl(startUrl);
network = new QNetworkAccessManager(this);
spider = new Spider;
parser = new Parser;
QStringList nextPagePatterns;
nextPagePatterns << "<a\\s+class=[\"']next[\"'].*href=[\"']([^>]*page=\\d+.*)[\"']>"
<< "<a\\s+href=['\"]([^['\"]+.html)['\"]>></a>"
<< "<a\\s+href=['\"]([^['\"]+.html)['\"]>下一页</a>"
<< "<a\\s+href=['\"]([^['\"]+.html)['\"]>Next</a>";
//http://sexy.faceks.com
parser->setUrlRegexpPattern("<div\\s+class=['\"]pic['\"].*href=['\"]([^['\"]+)['\"].*>");
parser->setImageRegexpPattern("bigimgsrc=[\"']([^'\"]+)['\"]");
parser->setNextPageRegexpPatterns(nextPagePatterns);
//http://www.2xiezhen.com/siwameinv
// parser->setUrlRegexpPattern("<li>\\s*<a.*href=['\"]([^['\"]+.html)['\"].*/></a>");
// parser->setImageRegexpPattern("<a\\s+class=['\"]showpic['\"].*href=.*src=['\"]([^['\"]+.jpg)['\"]\\s*/>");
parser->setRefererUrl(referer);
spider->setNetwokManager(network);
spider->setParser(parser);
// download images
downloader = new Downloader;
downloader->setNetwokManager(network);
downloader->setRefererUrl(referer.toLocal8Bit());
}
Worker::~Worker()
{
delete parser;
delete spider;
delete network;
}
void Worker::start()
{
spider->start();
}
| [
"yuri.young@newdebug.com"
] | yuri.young@newdebug.com |
c66afabc1ff3c9d43a80f7f7ed592e835939795e | b3679befe0405fbb04b3b8e331055e1d04704819 | /src/cl_sphere.cpp | f09b8ecdadef40277f3980997ffa4947346dbca9 | [
"MIT"
] | permissive | gmmoreira/ruby-ffi-opencl | f3d5c1ffe249d437439ab3195bcff48805873d24 | 48363889d01428a1d9df78690db7b437974a545c | refs/heads/master | 2021-01-11T08:24:45.982661 | 2016-11-03T01:28:57 | 2016-11-03T01:28:57 | 72,287,687 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,028 | cpp | #include "cl_sphere.h"
#include "cl_platform.hpp"
#include "cl_device.hpp"
#include <cstring>
using std::string;
using std::vector;
using std::strcpy;
const char * string_to_char(string data) {
auto c_data = (char *) malloc(sizeof(char) * (data.size() + 1));
strcpy(c_data, data.c_str());
return c_data;
}
cl_uint get_platforms_size() {
return getPlatformsSize();
}
cl_platform_id get_platform(cl_uint position) {
auto platforms = getPlatforms();
return platforms[position].id;
}
const char * get_platform_name(cl_platform_id platform_id) {
auto platform = getPlatform(platform_id);
return string_to_char(platform.name);
}
cl_uint get_devices_size(cl_platform_id platform_id) {
return getDevicesSize(platform_id);
}
cl_device_id get_device(cl_platform_id platform_id, cl_uint position) {
auto devices = getDevices(platform_id);
return devices[position].id;
}
const char * get_device_name(cl_device_id device_id) {
auto device = getDevice(device_id);
return string_to_char(device.name);
}
| [
"guilhermerx7@gmail.com"
] | guilhermerx7@gmail.com |
ec27883f3a712e4cc23567b6e8b2d992fd684b8f | becc5bffc7a29491a09780c57e89f5ab8d688299 | /Code/src/simcube/simcube_projection-galactic/fits_simimg.cpp | b7e4539fc627ed9602457940fff8480abc09e5dc | [
"Apache-2.0"
] | permissive | VisIVOLab/ViaLacteaVisualAnalytics | 6186d282f553e63984bac9f6086ca326d3ac8503 | fbd5da6dc28c1f32632a7622193c03a98263903b | refs/heads/master | 2023-08-21T19:46:05.667116 | 2023-06-01T14:30:43 | 2023-06-01T14:30:43 | 269,041,293 | 1 | 0 | Apache-2.0 | 2023-09-11T08:39:46 | 2020-06-03T09:09:00 | C++ | UTF-8 | C++ | false | false | 3,503 | cpp | #include "fits_simimg.hpp"
#include <fitsio.h>
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <string>
using namespace std;
string get_errstatus(int status)
{
char err_text[32]; // CFITSIO doc: max 30 char error text
fits_get_errstatus(status, err_text);
return string { err_text };
}
fits_simimg::fits_simimg(string fits_filename) : fptr { nullptr }
{
int status = 0;
if (fits_open_image(&fptr, fits_filename.c_str(), READWRITE, &status)) {
throw std::runtime_error(get_errstatus(status) + " : " + fits_filename);
}
// FIXME assert that ctype is parsec -> only then cdelt/dist is valid
int nfound = 0;
if (fits_read_keys_dbl(fptr, "CDELT", 1, 2, cdelt_vals, &nfound, &status) || (nfound != 2)) {
throw std::invalid_argument(string("Error: reading CDELT 1 2 : ") + get_errstatus(status));
}
}
void fits_simimg::update_card(string keyname, string keyvalue)
{
int status = 0;
char card[FLEN_CARD], oldcard[FLEN_CARD], newcard[FLEN_CARD];
char oldvalue[FLEN_VALUE], comment[FLEN_COMMENT];
int keytype;
if (fits_read_card(fptr, keyname.c_str(), card, &status)) {
throw invalid_argument(string("Keys to update must exist but read card ") + string(card)
+ " yields error : " + get_errstatus(status));
}
strcpy(oldcard, card);
/* check if this is a protected keyword that must not be changed */
if (*card && fits_get_keyclass(card) == TYP_STRUC_KEY) {
throw invalid_argument(string("Protected keyword cannot be modified: ") + string(card));
} else {
/* get the comment string */
if (*card)
fits_parse_value(card, oldvalue, comment, &status);
/* construct template for new keyword */
strcpy(newcard, keyname.c_str()); /* copy keyword name */
strcat(newcard, " = "); /* '=' value delimiter */
strcat(newcard, keyvalue.c_str()); /* new value */
if (*comment) {
strcat(newcard, " / "); /* comment delimiter */
strcat(newcard, comment); /* append the comment */
}
/* reformat the keyword string to conform to FITS rules */
fits_parse_template(newcard, card, &keytype, &status);
if (string(card) == string(oldcard)) {
throw invalid_argument(string("Card has already the expected value: ") + string(card));
}
/* overwrite the keyword with the new value */
fits_update_card(fptr, keyname.c_str(), card, &status);
}
if (status)
throw runtime_error(string("update_card failed: ") + get_errstatus(status));
}
void fits_simimg::update_header(const double cdelt_deg[2], const double crval_deg[2])
{
map<string, string> keys_const_value {
{ "CTYPE1", "GLON-CAR" },
{ "CTYPE2", "GLAT-CAR" },
{ "CUNIT1", "deg" },
{ "CUNIT2", "deg" },
};
for (map<string, string>::iterator it = keys_const_value.begin(); it != keys_const_value.end();
++it)
update_card(it->first, it->second);
map<string, string> keys_calc_value {
{ "CRVAL1", to_string(crval_deg[0]) },
{ "CRVAL2", to_string(crval_deg[1]) },
{ "CDELT1", to_string(cdelt_deg[0]) },
{ "CDELT2", to_string(cdelt_deg[1]) },
};
for (map<string, string>::iterator it = keys_calc_value.begin(); it != keys_calc_value.end();
++it)
update_card(it->first, it->second);
}
| [
"giuseppe.tudisco@inaf.it"
] | giuseppe.tudisco@inaf.it |
9f86d9166140fef0455357fd0d9e6b87fa56e3fa | 6c57b1f26dabd8bb24a41471ced5e0d1ac30735b | /BB/include/BB/Serial/SerialMessage.h | 3bcaedf8cff29c8c0a4520c42fcbfebaaeaa4140 | [] | no_license | hadzim/bb | 555bb50465fbd604c56c755cdee2cce796118322 | a6f43a9780753242e5e9f2af804c5233af4a920e | refs/heads/master | 2021-01-21T04:54:53.835407 | 2016-06-06T06:31:55 | 2016-06-06T06:31:55 | 17,916,029 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,219 | h | /*
* SerialMessage.h
*
* Created on: 18.5.2014
* Author: JV
*/
#ifndef SERIALMESSAGE_H_
#define SERIALMESSAGE_H_
#include <vector>
#include <string>
#include "BB/Sensor/SensorData.h"
namespace BB {
/*
* byte sequence
* 0 - start byte
* 1 - NodeID
* 2 - NodeStatus
* 3 - NodeType
* 4 - MessageLength
* 5 - n Message
*/
class SerialMessage {
public:
typedef int NodeID;
typedef unsigned char Length;
enum NodeStatus {
NodeOk = 'O',
NodeError = 'E'
};
enum NodeType {
NodeTemperature = 'T',
NodeMotion = 'M'
};
enum DataType {
DataDouble = 'D'
};
NodeID nodeID;
NodeStatus nodeStatus;
NodeType nodeType;
DataType dataType;
Length length;
std::string message;
SerialMessage(std::vector <unsigned char> & bytes);
virtual ~SerialMessage();
SensorData createSensorData();
private:
};
} /* namespace BB */
std::ostream & operator<<(std::ostream & stream, const BB::SerialMessage::NodeType & s);
std::ostream & operator<<(std::ostream & stream, const BB::SerialMessage::NodeStatus & s);
std::ostream & operator<<(std::ostream & stream, const BB::SerialMessage & s);
#endif /* SERIALMESSAGE_H_ */
| [
"jan.vana@tbs-biometrics.com"
] | jan.vana@tbs-biometrics.com |
4026209bb982fc198cd3f1eda31ea3f3fb757153 | 5ae308aaa7bb2e60b1ddff28fcaf39567da1b6ae | /LCP/lcp_074_search_a_2D_matrix.cpp | 7c4af2d1f617bfa0f15ed800596c4be892f02961 | [] | no_license | jiahonglin/LCP | 55cde187f98b8a013544f95aea6087df92516fc3 | 1805972511193dd91103ced834bdd35302481e98 | refs/heads/master | 2023-08-17T06:59:00.287333 | 2023-08-16T15:34:14 | 2023-08-16T15:34:14 | 189,690,649 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,468 | cpp | class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
bool bFind = false;
if(m == 1){
for(int j=0;j<n;j++){
if(matrix[0][j] == target){
bFind=true;
break;
}
}
return bFind;
}
if(n == 1){
for(int i=0;i<m;i++){
if(matrix[i][0] == target){
bFind=true;
break;
}
}
return bFind;
}
for(int i=0;i<m;i++){
if(matrix[i][0] <= target && target <= matrix[i][n-1]){
for(int j=0;j<n;j++){
if(matrix[i][j] == target){
bFind=true;
break;
}
}
return bFind;
}
}
return bFind;
}
/*
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();
int n = matrix[0].size();
int i=0;
for(;i<m;i++){
if(matrix[i][0] <= target && matrix[i][n-1] >= target)
break;
if(i == m-1) return false;
}
for(int j=0;j<n;j++){
if(matrix[i][j] == target) return true;
}
return false;
}
*/
};
| [
"jiahonglin17@gmail.com"
] | jiahonglin17@gmail.com |
37d9f26142043f7e9671c4145c998b08f8aac179 | 8687a237b885bb7a116410491e48c35d444745b5 | /c++/primer_plus_s_pratt/ch_12/pe_2/include/string2.h | befd489d13e2ea2f9251f323c4a68d73227cb3c6 | [
"MIT"
] | permissive | dinimar/Projects | 150b3d95247c738ca9a5ce6b2ec1ed9cee30b415 | 7606c23c4e55d6f0c03692b4a1d2bb5b42f10992 | refs/heads/master | 2021-06-11T20:34:29.081266 | 2021-05-15T19:22:36 | 2021-05-15T19:22:36 | 183,491,754 | 0 | 0 | MIT | 2019-04-25T18:47:39 | 2019-04-25T18:47:39 | null | UTF-8 | C++ | false | false | 1,404 | h | //
// Created by Dinir Imameev on 11/21/19.
// Github: @dinimar
//
#ifndef STRING2_H_
#define STRING2_H_
#include <iostream>
using std::ostream;
using std::istream;
class String
{
private:
char * str;
// pointer to string
int len;
// length of string
static int num_strings; // number of objects
static const int CINLIM = 80; // cin input limit
public:
// constructors and other methods
String(const char * s); // constructor
String();
// default constructor
String(const String &); // copy constructor
~String();
// destructor
int length () const { return len; }
int has(const char &);
void stringLow();
void stringUp();
// overloaded operator methods
String & operator=(const String &);
String & operator=(const char *);
String operator+(const String &) const;
String operator+(const char *) const;
char & operator[](int i);
const char & operator[](int i) const;
// overloaded operator friends
friend String operator+(char * s, const String &st);
friend bool operator<(const String &st, const String &st2);
friend bool operator>(const String &st1, const String &st2);
friend bool operator==(const String &st, const String &st2);
friend ostream & operator<<(ostream & os, const String & st);
friend istream & operator>>(istream & is, String & st);
// static function
static int HowMany();
};
#endif
| [
"dinir.imameev@gmail.com"
] | dinir.imameev@gmail.com |
d16d901662b1158fd7289b98503415a1efa58400 | 59819ec8eb426ec0cdf4d187c41961b9a35cfe09 | /questions_on_functions/dec_to_binary.cpp | 6c2c866ef10d08dee7ffd66701d848eba5913f1a | [] | no_license | deep1358/CPP-Programs | 46d0a84e2d1790983641303921fec82733cffbd5 | f5eb80f0fca195ef40300ea5c13adb896d6ee978 | refs/heads/master | 2023-08-18T11:08:17.678754 | 2021-08-26T12:26:26 | 2021-08-26T12:26:26 | 373,787,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | cpp | #include <bits/stdc++.h>
using namespace std;
void dec_to_bin(int n)
{
int ans = 0;
int c = 0;
while (n > 0)
{
int temp = n % 2;
ans += pow(10, c) * temp;
c++;
n /= 2;
}
cout << ans;
}
int main()
{
int n;
cin >> n;
dec_to_bin(n);
return 0;
} | [
"deepshah1358@gmail.com"
] | deepshah1358@gmail.com |
ffaa53a6d966d9872692c9fc4b814cc96d412bb0 | 0b34dc130e8296d3d61eedf37452be5de41af1c2 | /OpenGl/OpenGL超级宝典完整源码(第五版)/OpenGL超级宝典完整源码(第五版)/Src/Chapter07/TextureArrays/TextureArrays.cpp | 6175095d59282c7ccfb534788f26f04a7c793668 | [] | no_license | BIbiLion/LS_Wqiakun2017Test | 67a77c07a33ea4d5f308492580a403774de99b30 | 2955f20d8ac63acd8ace2a553f2e062e9ac26e92 | refs/heads/master | 2021-01-20T14:19:28.468757 | 2017-09-15T08:04:55 | 2017-09-15T08:04:55 | 90,591,454 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 9,071 | cpp | // TextureArrays.cpp
// OpenGL SuperBible
// Demonstrates Passing a TextureArray to a shader
// Program by Richard S. Wright Jr.
#include <GLTools.h> // OpenGL toolkit
#include <GLFrustum.h>
#include <Stopwatch.h>
#ifdef __APPLE__
#include <glut/glut.h>
#else
#define FREEGLUT_STATIC
#include <GL/glut.h>
#endif
GLShaderManager shaderManager;
GLFrustum viewFrustum;
GLBatch smallStarBatch;
GLBatch mediumStarBatch;
GLBatch largeStarBatch;
GLBatch mountainRangeBatch;
GLBatch moonBatch;
GLuint starTexture;
GLuint starFieldShader; // The point sprite shader
GLint locMVP; // The location of the ModelViewProjection matrix uniform
GLint locStarTexture; // The location of the texture uniform
GLuint moonTexture;
GLuint moonShader;
GLint locMoonMVP;
GLint locMoonTexture;
GLint locMoonTime;
GLint locTimeStamp; // The location of the time stamp
// Array of small stars
#define SMALL_STARS 100
#define MEDIUM_STARS 40
#define LARGE_STARS 15
#define SCREEN_X 800
#define SCREEN_Y 600
// Load a TGA as a 2D Texture. Completely initialize the state
bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode)
{
GLbyte *pBits;
int nWidth, nHeight, nComponents;
GLenum eFormat;
// Read the texture bits
pBits = gltReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat);
if(pBits == NULL)
return false;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, nComponents, nWidth, nHeight, 0,
eFormat, GL_UNSIGNED_BYTE, pBits);
free(pBits);
if(minFilter == GL_LINEAR_MIPMAP_LINEAR ||
minFilter == GL_LINEAR_MIPMAP_NEAREST ||
minFilter == GL_NEAREST_MIPMAP_LINEAR ||
minFilter == GL_NEAREST_MIPMAP_NEAREST)
glGenerateMipmap(GL_TEXTURE_2D);
return true;
}
///////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
static CStopWatch timer;
// Clear the window
glClear(GL_COLOR_BUFFER_BIT);
// Everything is white
GLfloat vWhite [] = { 1.0f, 1.0f, 1.0f, 1.0f };
glBindTexture(GL_TEXTURE_2D, starTexture);
glUseProgram(starFieldShader);
glUniformMatrix4fv(locMVP, 1, GL_FALSE, viewFrustum.GetProjectionMatrix());
glUniform1i(locStarTexture, 0);
// Draw small stars
glPointSize(4.0f);
smallStarBatch.Draw();
// Draw medium sized stars
glPointSize(8.0f);
mediumStarBatch.Draw();
// Draw largest stars
glPointSize(12.0f);
largeStarBatch.Draw();
// Draw distant horizon
shaderManager.UseStockShader(GLT_SHADER_FLAT, viewFrustum.GetProjectionMatrix(), vWhite);
glLineWidth(3.5);
mountainRangeBatch.Draw();
// Draw the "moon"
glBindTexture(GL_TEXTURE_2D_ARRAY, moonTexture);
glUseProgram(moonShader);
glUniformMatrix4fv(locMoonMVP, 1, GL_FALSE, viewFrustum.GetProjectionMatrix());
glUniform1i(locMoonTexture, 0);
// fTime goes from 0.0 to 28.0 and recycles
float fTime = timer.GetElapsedSeconds();
fTime = fmod(fTime, 28.0f);
glUniform1f(locTimeStamp, fTime);
moonBatch.Draw();
// Swap buffers
glutSwapBuffers();
glutPostRedisplay();
}
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
M3DVector3f vVerts[SMALL_STARS]; // SMALL_STARS is the largest batch we are going to need
int i;
shaderManager.InitializeStockShaders();
// Populate star list
smallStarBatch.Begin(GL_POINTS, SMALL_STARS);
for(i = 0; i < SMALL_STARS; i++)
{
vVerts[i][0] = (GLfloat)(rand() % SCREEN_X);
vVerts[i][1] = (GLfloat)(rand() % (SCREEN_Y - 100)) + 100.0f;
vVerts[i][2] = 0.0f;
}
smallStarBatch.CopyVertexData3f(vVerts);
smallStarBatch.End();
// Populate star list
mediumStarBatch.Begin(GL_POINTS, MEDIUM_STARS);
for(i = 0; i < MEDIUM_STARS; i++)
{
vVerts[i][0] = (GLfloat)(rand() % SCREEN_X);
vVerts[i][1] = (GLfloat)(rand() % (SCREEN_Y - 100)) + 100.0f;
vVerts[i][2] = 0.0f;
}
mediumStarBatch.CopyVertexData3f(vVerts);
mediumStarBatch.End();
// Populate star list
largeStarBatch.Begin(GL_POINTS, LARGE_STARS);
for(i = 0; i < LARGE_STARS; i++)
{
vVerts[i][0] = (GLfloat)(rand() % SCREEN_X);
vVerts[i][1] = (GLfloat)(rand() % (SCREEN_Y - 100)) + 100.0f;
vVerts[i][2] = 0.0f;
}
largeStarBatch.CopyVertexData3f(vVerts);
largeStarBatch.End();
M3DVector3f vMountains[12] = { 0.0f, 25.0f, 0.0f,
50.0f, 100.0f, 0.0f,
100.0f, 25.0f, 0.0f,
225.0f, 125.0f, 0.0f,
300.0f, 50.0f, 0.0f,
375.0f, 100.0f, 0.0f,
460.0f, 25.0f, 0.0f,
525.0f, 100.0f, 0.0f,
600.0f, 20.0f, 0.0f,
675.0f, 70.0f, 0.0f,
750.0f, 25.0f, 0.0f,
800.0f, 90.0f, 0.0f };
mountainRangeBatch.Begin(GL_LINE_STRIP, 12);
mountainRangeBatch.CopyVertexData3f(vMountains);
mountainRangeBatch.End();
// The Moon
GLfloat x = 700.0f; // Location and radius of moon
GLfloat y = 500.0f;
GLfloat r = 50.0f;
GLfloat angle = 0.0f; // Another looping variable
moonBatch.Begin(GL_TRIANGLE_FAN, 4, 1);
moonBatch.MultiTexCoord2f(0, 0.0f, 0.0f);
moonBatch.Vertex3f(x - r, y - r, 0.0f);
moonBatch.MultiTexCoord2f(0, 1.0f, 0.0f);
moonBatch.Vertex3f(x + r, y - r, 0.0f);
moonBatch.MultiTexCoord2f(0, 1.0f, 1.0f);
moonBatch.Vertex3f(x + r, y + r, 0.0f);
moonBatch.MultiTexCoord2f(0, 0.0f, 1.0f);
moonBatch.Vertex3f(x - r, y + r, 0.0f);
moonBatch.End();
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
// Turn on line antialiasing, and give hint to do the best
// job possible.
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
starFieldShader = gltLoadShaderPairWithAttributes("StarField.vp", "StarField.fp", 1, GLT_ATTRIBUTE_VERTEX, "vVertex");
locMVP = glGetUniformLocation(starFieldShader, "mvpMatrix");
locStarTexture = glGetUniformLocation(starFieldShader, "starImage");
moonShader = gltLoadShaderPairWithAttributes("MoonShader.vp", "MoonShader.fp", 2, GLT_ATTRIBUTE_VERTEX, "vVertex",
GLT_ATTRIBUTE_TEXTURE0, "vTexCoords");
locMoonMVP = glGetUniformLocation(moonShader, "mvpMatrix");
locMoonTexture = glGetUniformLocation(moonShader, "moonImage");
locMoonTime = glGetUniformLocation(moonShader, "fTime");
glGenTextures(1, &starTexture);
glBindTexture(GL_TEXTURE_2D, starTexture);
LoadTGATexture("Star.tga", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE);
glGenTextures(1, &moonTexture);
glBindTexture(GL_TEXTURE_2D_ARRAY, moonTexture);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 64, 64, 30, 0,
GL_BGRA, GL_UNSIGNED_BYTE, NULL);
for(int i = 0; i < 29; i++) {
char cFile[32];
sprintf(cFile, "moon%02d.tga", i);
GLbyte *pBits;
int nWidth, nHeight, nComponents;
GLenum eFormat;
// Read the texture bits
pBits = gltReadTGABits(cFile, &nWidth, &nHeight, &nComponents, &eFormat);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, nWidth, nHeight, 1, GL_BGRA, GL_UNSIGNED_BYTE, pBits);
free(pBits);
}
}
void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
// Establish clipping volume (left, right, bottom, top, near, far)
viewFrustum.SetOrthographic(0.0f, SCREEN_X, 0.0f, SCREEN_Y, -1.0f, 1.0f);
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Texture Arrays");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
GLenum err = glewInit();
if (GLEW_OK != err) {
fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
return 1;
}
SetupRC();
glutMainLoop();
return 0;
}
| [
"wqiankun89@163.com"
] | wqiankun89@163.com |
f8c0f50ebc607cae607e6f1a3040fd48d3d59752 | 374444870cff54414655655ebfb994717e2907b2 | /SemGapI/Week5/1SumOfDigits.cpp | fd030c1a51f3a0582bce931a14092395d7a69fad | [
"BSD-3-Clause"
] | permissive | AnkitApurv/MCA | 7d7d35a0c45bfa1337de4f3e55f5bf810fb62c06 | e6240fc326a282369e0ca173da28944cf516fbbe | refs/heads/master | 2023-03-22T05:56:09.187082 | 2020-03-23T18:35:32 | 2020-03-23T18:35:32 | 166,032,236 | 1 | 0 | BSD-3-Clause | 2021-03-20T03:19:42 | 2019-01-16T11:54:18 | ASP | UTF-8 | C++ | false | false | 807 | cpp | /* @name 1SumOfDigits.cpp
@desc to find the sum of the digits of a number using recursion.
@author Ankit Apurv 180970042
@date 04/01/2019
*/
#include <iostream>
using namespace std;
/* @desc computes sum of digits recursively
@args
num : integer, number whose digits are to be added
sum : integer, variable to store and return the result
@return integer, sum of digits of the given number
*/
int rSum(int num, int sum)
{
if(num > 0)
{
if(num >= 10)
{
int i = num % 10;
num -= i;
num /= 10;
sum += i;
}
else
{
sum += num;
num = 0;
}
return rSum(num, sum);
}
else
{
return sum;
}
}
/* @desc main
@args
void
@return exit code
*/
int main(void)
{
int n, s = 0;
cout << "Number : ";
cin >> n;
cout << "\nSum : " << rSum(n, s) << "\n";
return 0;
} | [
"k.ankit.capricon@gmail.com"
] | k.ankit.capricon@gmail.com |
6f024c9ba4a90cc8ccdbaa344501abb857db7eeb | 5626349a40a2a0a73cee8d88264ad791fc25791a | /src/aft/aftma/aftma_blockallocator.h | fcbca3b00c68a51f56cce34f7fde6314ca7075ce | [] | no_license | lyell/aegis | ae8600c2b334ad1db3c4005a74a43b4099966701 | 61952676c1d6eb0823e5ff8a7097cc29bb6308f7 | refs/heads/master | 2020-12-24T08:55:11.755560 | 2018-01-06T13:09:01 | 2018-01-06T13:09:01 | 26,701,231 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | h | #ifndef INCLUDED_AEGIS_AFTMA_BLOCKALLOCATOR_H
#define INCLUDED_AEGIS_AFTMA_BLOCKALLOCATOR_H
#include <aftma_allocator.h>
#include <map>
namespace aftma {
class BlockAllocator
: public aftma::Allocator
{
public:
BlockAllocator();
virtual ~BlockAllocator();
virtual void* allocate(size_t size);
virtual void deallocate(void* ptr);
private:
struct Pool
{
void* startPool;
void* endPool;
size_t size;
uint32_t* freeListBitmap;
size_t bitmapLength;
};
typedef std::map<size_t, Pool*> PoolMap;
PoolMap m_poolMap;
};
} // namespace
#endif // INCLUDED
| [
"lyell@sophicstudios.com"
] | lyell@sophicstudios.com |
ff966d913d5427f17ec9fd7e32dd7d537cdf1ff7 | 6e57bdc0a6cd18f9f546559875256c4570256c45 | /external/pdfium/core/fpdfapi/render/cpdf_imagecacheentry.h | 2bede23e628d28b72affbe8c617dbaaf2c083a51 | [
"BSD-3-Clause"
] | permissive | dongdong331/test | 969d6e945f7f21a5819cd1d5f536d12c552e825c | 2ba7bcea4f9d9715cbb1c4e69271f7b185a0786e | refs/heads/master | 2023-03-07T06:56:55.210503 | 2020-12-07T04:15:33 | 2020-12-07T04:15:33 | 134,398,935 | 2 | 1 | null | 2022-11-21T07:53:41 | 2018-05-22T10:26:42 | null | UTF-8 | C++ | false | false | 1,984 | h | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef CORE_FPDFAPI_RENDER_CPDF_IMAGECACHEENTRY_H_
#define CORE_FPDFAPI_RENDER_CPDF_IMAGECACHEENTRY_H_
#include <memory>
#include "core/fxcrt/fx_system.h"
#include "core/fxcrt/retain_ptr.h"
#include "core/fxcrt/unowned_ptr.h"
class CFX_DIBSource;
class CFX_DIBitmap;
class CPDF_Dictionary;
class CPDF_Document;
class CPDF_Image;
class CPDF_RenderStatus;
class IFX_PauseIndicator;
class CPDF_ImageCacheEntry {
public:
CPDF_ImageCacheEntry(CPDF_Document* pDoc,
const RetainPtr<CPDF_Image>& pImage);
~CPDF_ImageCacheEntry();
void Reset(const RetainPtr<CFX_DIBitmap>& pBitmap);
uint32_t EstimateSize() const { return m_dwCacheSize; }
uint32_t GetTimeCount() const { return m_dwTimeCount; }
CPDF_Image* GetImage() const { return m_pImage.Get(); }
int StartGetCachedBitmap(CPDF_Dictionary* pFormResources,
CPDF_Dictionary* pPageResources,
bool bStdCS,
uint32_t GroupFamily,
bool bLoadMask,
CPDF_RenderStatus* pRenderStatus);
int Continue(IFX_PauseIndicator* pPause, CPDF_RenderStatus* pRenderStatus);
RetainPtr<CFX_DIBSource> DetachBitmap();
RetainPtr<CFX_DIBSource> DetachMask();
int m_dwTimeCount;
uint32_t m_MatteColor;
private:
void ContinueGetCachedBitmap(CPDF_RenderStatus* pRenderStatus);
void CalcSize();
UnownedPtr<CPDF_Document> const m_pDocument;
RetainPtr<CPDF_Image> const m_pImage;
RetainPtr<CFX_DIBSource> m_pCurBitmap;
RetainPtr<CFX_DIBSource> m_pCurMask;
RetainPtr<CFX_DIBSource> m_pCachedBitmap;
RetainPtr<CFX_DIBSource> m_pCachedMask;
uint32_t m_dwCacheSize;
};
#endif // CORE_FPDFAPI_RENDER_CPDF_IMAGECACHEENTRY_H_
| [
"dongdong331@163.com"
] | dongdong331@163.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.