1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
|
#include "mkql_heap.h"
#include <yql/essentials/minikql/computation/mkql_computation_node_holders.h>
#include <yql/essentials/minikql/computation/mkql_computation_node_codegen.h> // Y_IGNORE
#include <yql/essentials/minikql/mkql_node_cast.h>
#include <yql/essentials/minikql/mkql_node_builder.h>
#include <yql/essentials/utils/sort.h>
namespace NKikimr {
namespace NMiniKQL {
namespace {
using TComparator = std::function<bool(const NUdf::TUnboxedValuePod l, const NUdf::TUnboxedValuePod r)>;
using TAlgorithm = void(*)(NUdf::TUnboxedValuePod*, NUdf::TUnboxedValuePod*, TComparator);
using TArgsPlace = std::array<NUdf::TUnboxedValuePod, 2U>;
using TComparePtr = bool (*)(TComputationContext& ctx, const NUdf::TUnboxedValuePod l, const NUdf::TUnboxedValuePod r);
class THeapWrapper : public TMutableCodegeneratorNode<THeapWrapper>
#ifndef MKQL_DISABLE_CODEGEN
, public ICodegeneratorRootNode
#endif
{
typedef TMutableCodegeneratorNode<THeapWrapper> TBaseComputation;
public:
THeapWrapper(TAlgorithm algorithm, TComputationMutables& mutables, IComputationNode* list, IComputationExternalNode* left, IComputationExternalNode* right, IComputationNode* compare)
: TBaseComputation(mutables, EValueRepresentation::Boxed)
, Algorithm(algorithm)
, List(list)
, Left(left)
, Right(right)
, Compare(compare)
{}
NUdf::TUnboxedValuePod DoCalculate(TComputationContext& ctx) const {
auto list = List->GetValue(ctx);
const auto size = list.GetListLength();
if (size < 2U)
return list.Release();
NUdf::TUnboxedValue *items = nullptr;
const auto next = ctx.HolderFactory.CloneArray(list.Release(), items);
NUdf::TUnboxedValuePod *const begin = items, *const end = items + size;
Do(ctx, begin, end);
return next;
}
#ifndef MKQL_DISABLE_CODEGEN
Value* DoGenerateGetValue(const TCodegenContext& ctx, BasicBlock*& block) const {
auto& context = ctx.Codegen.GetContext();
const auto valueType = Type::getInt128Ty(context);
const auto fact = ctx.GetFactory();
const auto func = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&THolderFactory::CloneArray));// TODO: Generate code instead of call CloneArray.
const auto list = GetNodeValue(List, ctx, block);
const auto size = CallBoxedValueVirtualMethod<NUdf::TBoxedValueAccessor::EMethod::GetListLength>(Type::getInt64Ty(context), list, ctx.Codegen, block);
const auto test = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT, size, ConstantInt::get(size->getType(), 1ULL), "test", block);
const auto work = BasicBlock::Create(context, "work", ctx.Func);
const auto done = BasicBlock::Create(context, "done", ctx.Func);
const auto result = PHINode::Create(valueType, 2U, "result", done);
result->addIncoming(list, block);
BranchInst::Create(work, done, test, block);
block = work;
const auto itemsType = PointerType::getUnqual(valueType);
const auto itemsPtr = *Stateless || ctx.AlwaysInline ?
new AllocaInst(itemsType, 0U, "items_ptr", &ctx.Func->getEntryBlock().back()):
new AllocaInst(itemsType, 0U, "items_ptr", block);
const auto idxType = Type::getInt32Ty(context);
Value* array = nullptr;
if (NYql::NCodegen::ETarget::Windows != ctx.Codegen.GetEffectiveTarget()) {
const auto funType = FunctionType::get(valueType, {fact->getType(), list->getType(), itemsPtr->getType()}, false);
const auto funcPtr = CastInst::Create(Instruction::IntToPtr, func, PointerType::getUnqual(funType), "function", block);
array = CallInst::Create(funType, funcPtr, {fact, list, itemsPtr}, "array", block);
} else {
const auto arrayPtr = new AllocaInst(valueType, 0U, "array_ptr", block);
new StoreInst(list, arrayPtr, block);
const auto funType = FunctionType::get(Type::getVoidTy(context), {fact->getType(), arrayPtr->getType(), arrayPtr->getType(), itemsPtr->getType()}, false);
const auto funcPtr = CastInst::Create(Instruction::IntToPtr, func, PointerType::getUnqual(funType), "function", block);
CallInst::Create(funType, funcPtr, {fact, arrayPtr, arrayPtr, itemsPtr}, "", block);
array = new LoadInst(valueType, arrayPtr, "array", block);
}
result->addIncoming(array, block);
const auto algo = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&THeapWrapper::Do));
const auto self = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(this));
const auto items = new LoadInst(itemsType, itemsPtr, "items", block);
const auto zero = ConstantInt::get(idxType, 0);
const auto begin = GetElementPtrInst::CreateInBounds(valueType, items, {zero}, "begin", block);
const auto end = GetElementPtrInst::CreateInBounds(valueType, items, {size}, "end", block);
const auto selfPtr = CastInst::Create(Instruction::IntToPtr, self, PointerType::getUnqual(StructType::get(context)), "comp", block);
const auto doType = FunctionType::get(Type::getVoidTy(context), {selfPtr->getType(), ctx.Ctx->getType(), begin->getType(), end->getType()}, false);
const auto doPtr = CastInst::Create(Instruction::IntToPtr, algo, PointerType::getUnqual(doType), "do", block);
CallInst::Create(doType, doPtr, {selfPtr, ctx.Ctx, begin, end}, "", block);
BranchInst::Create(done, block);
block = done;
return result;
}
#endif
private:
void Do(TComputationContext& ctx, NUdf::TUnboxedValuePod* begin, NUdf::TUnboxedValuePod* end) const {
if (ctx.ExecuteLLVM && Comparator) {
return Algorithm(begin, end, std::bind(Comparator, std::ref(ctx), std::placeholders::_1, std::placeholders::_2));
}
TArgsPlace args;
Left->SetGetter([&](TComputationContext&) { return args.front(); });
Right->SetGetter([&](TComputationContext&) { return args.back(); });
Algorithm(begin, end, std::bind(&THeapWrapper::Comp, this, std::ref(args), std::ref(ctx), std::placeholders::_1, std::placeholders::_2));
}
bool Comp(TArgsPlace& args, TComputationContext& ctx, const NUdf::TUnboxedValuePod l, const NUdf::TUnboxedValuePod r) const {
args = {{l, r}};
Left->InvalidateValue(ctx);
Right->InvalidateValue(ctx);
return Compare->GetValue(ctx).Get<bool>();
}
void RegisterDependencies() const final {
this->DependsOn(List);
this->Own(Left);
this->Own(Right);
this->DependsOn(Compare);
}
const TAlgorithm Algorithm;
IComputationNode* const List;
IComputationExternalNode* const Left;
IComputationExternalNode* const Right;
IComputationNode* const Compare;
TComparePtr Comparator = nullptr;
#ifndef MKQL_DISABLE_CODEGEN
TString MakeName() const {
TStringStream out;
out << this->DebugString() << "::compare_(" << static_cast<const void*>(this) << ").";
return out.Str();
}
void FinalizeFunctions(NYql::NCodegen::ICodegen& codegen) final {
if (CompareFunc) {
Comparator = reinterpret_cast<TComparePtr>(codegen.GetPointerToFunction(CompareFunc));
}
}
void GenerateFunctions(NYql::NCodegen::ICodegen& codegen) final {
CompareFunc = GenerateCompareFunction(codegen, MakeName(), Left, Right, Compare);
codegen.ExportSymbol(CompareFunc);
}
Function* CompareFunc = nullptr;
#endif
};
IComputationNode* WrapHeap(TAlgorithm algorithm, TCallable& callable, const TComputationNodeFactoryContext& ctx) {
MKQL_ENSURE(callable.GetInputsCount() == 4, "Expected 4 args");
const auto list = LocateNode(ctx.NodeLocator, callable, 0);
const auto compare = LocateNode(ctx.NodeLocator, callable, 3);
const auto left = LocateExternalNode(ctx.NodeLocator, callable, 1);
const auto right = LocateExternalNode(ctx.NodeLocator, callable, 2);
return new THeapWrapper(algorithm, ctx.Mutables, list, left, right, compare);
}
using TNthAlgorithm = void(*)(NUdf::TUnboxedValuePod*, NUdf::TUnboxedValuePod*, NUdf::TUnboxedValuePod*, TComparator);
class TNthWrapper : public TMutableCodegeneratorNode<TNthWrapper>
#ifndef MKQL_DISABLE_CODEGEN
, public ICodegeneratorRootNode
#endif
{
typedef TMutableCodegeneratorNode<TNthWrapper> TBaseComputation;
public:
TNthWrapper(TNthAlgorithm algorithm, TComputationMutables& mutables, IComputationNode* list, IComputationNode* middle, IComputationExternalNode* left, IComputationExternalNode* right, IComputationNode* compare)
: TBaseComputation(mutables, EValueRepresentation::Boxed)
, Algorithm(algorithm)
, List(list)
, Middle(middle)
, Left(left)
, Right(right)
, Compare(compare)
{}
NUdf::TUnboxedValuePod DoCalculate(TComputationContext& ctx) const {
auto list = List->GetValue(ctx);
auto middle = Middle->GetValue(ctx).Get<ui64>();
const auto size = list.GetListLength();
middle = std::min(middle, size);
if (middle == 0U || size < 2U)
return list.Release();
NUdf::TUnboxedValue *items = nullptr;
const auto next = ctx.HolderFactory.CloneArray(list.Release(), items);
NUdf::TUnboxedValuePod *const begin = items, *const mid = items + middle, *const end = items + size;
Do(ctx, begin, mid, end);
return next;
}
#ifndef MKQL_DISABLE_CODEGEN
Value* DoGenerateGetValue(const TCodegenContext& ctx, BasicBlock*& block) const {
auto& context = ctx.Codegen.GetContext();
const auto valueType = Type::getInt128Ty(context);
const auto fact = ctx.GetFactory();
const auto func = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&THolderFactory::CloneArray));// TODO: Generate code instead of call CloneArray.
const auto list = GetNodeValue(List, ctx, block);
const auto midv = GetNodeValue(Middle, ctx, block);
const auto middle = GetterFor<ui64>(midv, context, block);
const auto size = CallBoxedValueVirtualMethod<NUdf::TBoxedValueAccessor::EMethod::GetListLength>(Type::getInt64Ty(context), list, ctx.Codegen, block);
const auto greater = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT, middle, size, "greater", block);
const auto min = SelectInst::Create(greater, size, middle, "min", block);
const auto one = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT, min, ConstantInt::get(size->getType(), 0ULL), "one", block);
const auto two = CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT, size, ConstantInt::get(size->getType(), 1ULL), "two", block);
const auto test = BinaryOperator::CreateAnd(one, two, "and", block);
const auto work = BasicBlock::Create(context, "work", ctx.Func);
const auto done = BasicBlock::Create(context, "done", ctx.Func);
const auto result = PHINode::Create(valueType, 2U, "result", done);
result->addIncoming(list, block);
BranchInst::Create(work, done, test, block);
block = work;
const auto itemsType = PointerType::getUnqual(valueType);
const auto itemsPtr = *Stateless || ctx.AlwaysInline ?
new AllocaInst(itemsType, 0U, "items_ptr", &ctx.Func->getEntryBlock().back()):
new AllocaInst(itemsType, 0U, "items_ptr", block);
const auto idxType = Type::getInt32Ty(context);
Value* array = nullptr;
if (NYql::NCodegen::ETarget::Windows != ctx.Codegen.GetEffectiveTarget()) {
const auto funType = FunctionType::get(valueType, {fact->getType(), list->getType(), itemsPtr->getType()}, false);
const auto funcPtr = CastInst::Create(Instruction::IntToPtr, func, PointerType::getUnqual(funType), "function", block);
array = CallInst::Create(funType, funcPtr, {fact, list, itemsPtr}, "array", block);
} else {
const auto arrayPtr = new AllocaInst(valueType, 0U, "array_ptr", block);
new StoreInst(list, arrayPtr, block);
const auto funType = FunctionType::get(Type::getVoidTy(context), {fact->getType(), arrayPtr->getType(), arrayPtr->getType(), itemsPtr->getType()}, false);
const auto funcPtr = CastInst::Create(Instruction::IntToPtr, func, PointerType::getUnqual(funType), "function", block);
CallInst::Create(funType, funcPtr, {fact, arrayPtr, arrayPtr, itemsPtr}, "", block);
array = new LoadInst(valueType, arrayPtr, "array", block);
}
result->addIncoming(array, block);
const auto algo = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(&TNthWrapper::Do));
const auto self = ConstantInt::get(Type::getInt64Ty(context), GetMethodPtr(this));
const auto items = new LoadInst(itemsType, itemsPtr, "items", block);
const auto zero = ConstantInt::get(idxType, 0);
const auto begin = GetElementPtrInst::CreateInBounds(valueType, items, {zero}, "begin", block);
const auto mid = GetElementPtrInst::CreateInBounds(valueType, items, {min}, "middle", block);
const auto end = GetElementPtrInst::CreateInBounds(valueType, items, {size}, "end", block);
const auto selfPtr = CastInst::Create(Instruction::IntToPtr, self, PointerType::getUnqual(StructType::get(context)), "comp", block);
const auto doType = FunctionType::get(Type::getVoidTy(context), {selfPtr->getType(), ctx.Ctx->getType(), begin->getType(), mid->getType(), end->getType()}, false);
const auto doPtr = CastInst::Create(Instruction::IntToPtr, algo, PointerType::getUnqual(doType), "do", block);
CallInst::Create(doType, doPtr, {selfPtr, ctx.Ctx, begin, mid, end}, "", block);
BranchInst::Create(done, block);
block = done;
return result;
}
#endif
private:
void Do(TComputationContext& ctx, NUdf::TUnboxedValuePod* begin, NUdf::TUnboxedValuePod* nth, NUdf::TUnboxedValuePod* end) const {
if (ctx.ExecuteLLVM && Comparator) {
return Algorithm(begin, nth, end, std::bind(Comparator, std::ref(ctx), std::placeholders::_1, std::placeholders::_2));
}
TArgsPlace args;
Left->SetGetter([&](TComputationContext&) { return args.front(); });
Right->SetGetter([&](TComputationContext&) { return args.back(); });
Algorithm(begin, nth, end, std::bind(&TNthWrapper::Comp, this, std::ref(args), std::ref(ctx), std::placeholders::_1, std::placeholders::_2));
}
bool Comp(TArgsPlace& args, TComputationContext& ctx, const NUdf::TUnboxedValuePod l, const NUdf::TUnboxedValuePod r) const {
args = {{l, r}};
Left->InvalidateValue(ctx);
Right->InvalidateValue(ctx);
return Compare->GetValue(ctx).Get<bool>();
}
void RegisterDependencies() const final {
this->DependsOn(List);
this->DependsOn(Middle);
this->Own(Left);
this->Own(Right);
this->DependsOn(Compare);
}
const TNthAlgorithm Algorithm;
IComputationNode* const List;
IComputationNode* const Middle;
IComputationExternalNode* const Left;
IComputationExternalNode* const Right;
IComputationNode* const Compare;
TComparePtr Comparator = nullptr;
#ifndef MKQL_DISABLE_CODEGEN
TString MakeName() const {
TStringStream out;
out << this->DebugString() << "::compare_(" << static_cast<const void*>(this) << ").";
return out.Str();
}
void FinalizeFunctions(NYql::NCodegen::ICodegen& codegen) final {
if (CompareFunc) {
Comparator = reinterpret_cast<TComparePtr>(codegen.GetPointerToFunction(CompareFunc));
}
}
void GenerateFunctions(NYql::NCodegen::ICodegen& codegen) final {
CompareFunc = GenerateCompareFunction(codegen, MakeName(), Left, Right, Compare);
codegen.ExportSymbol(CompareFunc);
}
Function* CompareFunc = nullptr;
#endif
};
IComputationNode* WrapNth(TNthAlgorithm algorithm, TCallable& callable, const TComputationNodeFactoryContext& ctx) {
MKQL_ENSURE(callable.GetInputsCount() == 5, "Expected 5 args");
const auto list = LocateNode(ctx.NodeLocator, callable, 0);
const auto middle = LocateNode(ctx.NodeLocator, callable, 1);
const auto compare = LocateNode(ctx.NodeLocator, callable, 4);
const auto left = LocateExternalNode(ctx.NodeLocator, callable, 2);
const auto right = LocateExternalNode(ctx.NodeLocator, callable, 3);
return new TNthWrapper(algorithm, ctx.Mutables, list, middle, left, right, compare);
}
}
IComputationNode* WrapMakeHeap(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
return WrapHeap(&std::make_heap<NUdf::TUnboxedValuePod*, TComparator>, callable, ctx);
}
IComputationNode* WrapPushHeap(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
return WrapHeap(&std::push_heap<NUdf::TUnboxedValuePod*, TComparator>, callable, ctx);
}
IComputationNode* WrapPopHeap(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
return WrapHeap(&std::pop_heap<NUdf::TUnboxedValuePod*, TComparator>, callable, ctx);
}
IComputationNode* WrapSortHeap(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
return WrapHeap(&std::sort_heap<NUdf::TUnboxedValuePod*, TComparator>, callable, ctx);
}
IComputationNode* WrapStableSort(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
return WrapHeap(&std::stable_sort<NUdf::TUnboxedValuePod*, TComparator>, callable, ctx);
}
IComputationNode* WrapNthElement(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
return WrapNth(&NYql::FastNthElement<NUdf::TUnboxedValuePod*, TComparator>, callable, ctx);
}
IComputationNode* WrapPartialSort(TCallable& callable, const TComputationNodeFactoryContext& ctx) {
return WrapNth(&NYql::FastPartialSort<NUdf::TUnboxedValuePod*, TComparator>, callable, ctx);
}
}
}
|