aboutsummaryrefslogtreecommitdiffstats
path: root/ydb/library/yql/minikql/mkql_opt_literal.cpp
blob: 4c7bf5948a38ee49f88461b5eca6aaab05b41980 (plain) (blame)
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
#include "mkql_opt_literal.h"
#include "mkql_node_cast.h"
#include "mkql_node_builder.h"
#include "mkql_node_visitor.h"
#include "mkql_program_builder.h"
#include "mkql_node_printer.h"

#include <library/cpp/containers/stack_vector/stack_vec.h>

#include <util/generic/singleton.h>


namespace NKikimr {
namespace NMiniKQL {

using namespace NDetail;

namespace {

TNode* LiteralAddMember(
        const TStructLiteral& oldStruct,
        const TStructType& newStructType,
        TRuntimeNode newMember,
        TRuntimeNode position,
        const TTypeEnvironment& env)
{
    TStructLiteralBuilder resultBuilder(env);

    TDataLiteral* positionData = AS_VALUE(TDataLiteral, position);
    const ui32 positionValue = positionData->AsValue().Get<ui32>();
    MKQL_ENSURE(positionValue <= oldStruct.GetType()->GetMembersCount(), "Bad member index");

    for (ui32 i = 0; i < positionValue; ++i) {
        resultBuilder.Add(TString(oldStruct.GetType()->GetMemberName(i)), oldStruct.GetValue(i));
    }

    resultBuilder.Add(TString(newStructType.GetMemberName(positionValue)), newMember);
    for (ui32 i = positionValue; i < oldStruct.GetValuesCount(); ++i) {
        resultBuilder.Add(TString(oldStruct.GetType()->GetMemberName(i)), oldStruct.GetValue(i));
    }

    return resultBuilder.Build();
}

TNode* LiteralRemoveMember(
    const TStructLiteral& oldStruct,
    TRuntimeNode position,
    const TTypeEnvironment& env)
{
    TStructLiteralBuilder resultBuilder(env);

    TDataLiteral* positionData = AS_VALUE(TDataLiteral, position);
    const ui32 positionValue = positionData->AsValue().Get<ui32>();
    MKQL_ENSURE(positionValue < oldStruct.GetType()->GetMembersCount(), "Bad member index");

    for (ui32 i = 0; i < positionValue; ++i) {
        resultBuilder.Add(TString(oldStruct.GetType()->GetMemberName(i)), oldStruct.GetValue(i));
    }

    for (ui32 i = positionValue + 1; i < oldStruct.GetValuesCount(); ++i) {
        resultBuilder.Add(TString(oldStruct.GetType()->GetMemberName(i)), oldStruct.GetValue(i));
    }

    return resultBuilder.Build();
}

TRuntimeNode OptimizeIf(TCallable& callable, const TTypeEnvironment& env) {
    Y_UNUSED(env); 
    MKQL_ENSURE(callable.GetInputsCount() == 3, "Expected 3 arguments");

    auto predicateInput = callable.GetInput(0);
    auto thenInput = callable.GetInput(1);
    auto elseInput = callable.GetInput(2);
    if (predicateInput.HasValue()) {
        TDataLiteral* data = AS_VALUE(TDataLiteral, predicateInput);
        const bool predicateValue = data->AsValue().Get<bool>();
        return predicateValue ? thenInput : elseInput;
    }

    if (thenInput == elseInput) {
        return thenInput;
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeSize(TCallable& callable, const TTypeEnvironment& env) {
    MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 arguments");

    auto dataInput = callable.GetInput(0);
    if (dataInput.HasValue()) {
        TDataLiteral* value = AS_VALUE(TDataLiteral, dataInput);
        return TRuntimeNode(BuildDataLiteral(NUdf::TUnboxedValuePod((ui32)value->AsValue().AsStringRef().Size()), NUdf::EDataSlot::Uint32, env), true);
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeLength(TCallable& callable, const TTypeEnvironment& env) {
    MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 arguments");

    auto listOrDictInput = callable.GetInput(0);
    if (listOrDictInput.HasValue()) {
        if (listOrDictInput.GetStaticType()->IsList()) {
            TListLiteral* value = AS_VALUE(TListLiteral, listOrDictInput);
            return TRuntimeNode(BuildDataLiteral(NUdf::TUnboxedValuePod((ui64)value->GetItemsCount()), NUdf::EDataSlot::Uint64, env), true);
        }
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeAddMember(TCallable& callable, const TTypeEnvironment& env) {
    MKQL_ENSURE(callable.GetInputsCount() == 3, "Expected 3 arguments");

    auto callableReturnType = callable.GetType()->GetReturnType();
    MKQL_ENSURE(callableReturnType->IsStruct(), "Expected struct");
    const auto& newType = static_cast<TStructType&>(*callableReturnType);

    auto structInput = callable.GetInput(0);
    if (structInput.HasValue()) {
        TStructLiteral* value = AS_VALUE(TStructLiteral, structInput);
        return TRuntimeNode(LiteralAddMember(*value, newType, callable.GetInput(1), callable.GetInput(2), env), true);
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeRemoveMember(TCallable& callable, const TTypeEnvironment& env) {
    MKQL_ENSURE(callable.GetInputsCount() == 2, "Expected 2 arguments");

    auto callableReturnType = callable.GetType()->GetReturnType();
    MKQL_ENSURE(callableReturnType->IsStruct(), "Expected struct");
    auto structInput = callable.GetInput(0);
    if (structInput.HasValue()) {
        TStructLiteral* value = AS_VALUE(TStructLiteral, structInput);
        return TRuntimeNode(LiteralRemoveMember(*value, callable.GetInput(1), env), true);
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeMember(TCallable& callable, const TTypeEnvironment& env) {
    Y_UNUSED(env); 
    MKQL_ENSURE(callable.GetInputsCount() == 2, "Expected 2 arguments");

    auto structInput = callable.GetInput(0);
    if (structInput.HasValue() && structInput.GetStaticType()->IsStruct()) {
        TStructLiteral* value = AS_VALUE(TStructLiteral, structInput);

        auto position = callable.GetInput(1);
        TDataLiteral* positionData = AS_VALUE(TDataLiteral, position);
        const ui32 positionValue = positionData->AsValue().Get<ui32>();

        MKQL_ENSURE(positionValue < value->GetValuesCount(), "Bad member index");
        return value->GetValue(positionValue);
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeFilter(TCallable& callable, const TTypeEnvironment& env) {
    if (callable.GetInputsCount() == 3U) {
        auto listInput = callable.GetInput(0);
        if (!listInput.GetStaticType()->IsList()) {
            return TRuntimeNode(&callable, false);
        }

        auto listType = static_cast<TListType*>(listInput.GetStaticType());
        auto predicateInput = callable.GetInput(2);
        if (predicateInput.HasValue()) {
            auto predicate = predicateInput.GetValue();
            MKQL_ENSURE(predicate->GetType()->IsData(), "Expected data");

            const auto& data = static_cast<const TDataLiteral&>(*predicate);
            const bool predicateValue = data.AsValue().Get<bool>();
            if (predicateValue) {
                return listInput;
            } else {
                return TRuntimeNode(TListLiteral::Create(nullptr, 0, listType, env), true);
            }
        }
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeMap(TCallable& callable, const TTypeEnvironment& env) {
    MKQL_ENSURE(callable.GetInputsCount() == 3, "Expected 3 arguments");

    auto returnType = callable.GetType()->GetReturnType();
    if (!returnType->IsList()) {
        return TRuntimeNode(&callable, false);
    }

    auto listType = static_cast<TListType*>(returnType);
    auto newItemInput = callable.GetInput(2);
    if (listType->GetItemType()->IsVoid() && newItemInput.HasValue()) {
        return TRuntimeNode(env.GetListOfVoid(), true);
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeFlatMap(TCallable& callable, const TTypeEnvironment& env) {
    MKQL_ENSURE(callable.GetInputsCount() > 2U, "Expected 3 or more arguments");

    const auto returnType = callable.GetType()->GetReturnType();
    if (!returnType->IsList() || callable.GetInputsCount() > 3U) {
        return TRuntimeNode(&callable, false);
    }

    const auto listType = static_cast<TListType*>(returnType);
    const auto newItemInput = callable.GetInput(2);
    if (listType->GetItemType()->IsVoid() && newItemInput.HasValue()) {
        if (newItemInput.GetStaticType()->IsList()) {
            TListLiteral* list = AS_VALUE(TListLiteral, newItemInput);
            if (list->GetItemsCount() == 0) {
                return TRuntimeNode(env.GetListOfVoid(), true);
            }
        } else {
            TOptionalLiteral* opt = AS_VALUE(TOptionalLiteral, newItemInput);
            if (!opt->HasItem()) {
                return TRuntimeNode(env.GetListOfVoid(), true);
            }
        }
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeCoalesce(TCallable& callable, const TTypeEnvironment& env) {
    Y_UNUSED(env); 
    MKQL_ENSURE(callable.GetInputsCount() == 2, "Expected 2 arguments");

    auto optionalInput = callable.GetInput(0);
    auto defaultInput = callable.GetInput(1);
    bool isDefaultOptional;
    UnpackOptional(defaultInput, isDefaultOptional);
    if (optionalInput.HasValue()) {
        auto optionalData = AS_VALUE(TOptionalLiteral, optionalInput);
        if (optionalData->HasItem()) {
            return isDefaultOptional ? optionalInput : optionalData->GetItem();
        } else {
            return defaultInput;
        }
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeExists(TCallable& callable, const TTypeEnvironment& env) {
    MKQL_ENSURE(callable.GetInputsCount() == 1, "Expected 1 arguments");

    auto optionalInput = callable.GetInput(0);
    if (optionalInput.HasValue()) {
        const bool has = AS_VALUE(TOptionalLiteral, optionalInput)->HasItem();
        return TRuntimeNode(BuildDataLiteral(NUdf::TUnboxedValuePod(has), NUdf::EDataSlot::Bool, env), true);
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeNth(TCallable& callable, const TTypeEnvironment& env) {
    Y_UNUSED(env); 
    MKQL_ENSURE(callable.GetInputsCount() == 2, "Expected 2 arguments");

    auto tupleInput = callable.GetInput(0);
    if (tupleInput.HasValue() && tupleInput.GetStaticType()->IsTuple()) {
        auto tuple = tupleInput.GetValue();
        auto indexData = AS_VALUE(TDataLiteral, callable.GetInput(1));
        const ui32 index = indexData->AsValue().Get<ui32>();

        const auto& value = static_cast<const TTupleLiteral&>(*tuple);
        MKQL_ENSURE(index < value.GetValuesCount(), "Index out of range");
        return value.GetValue(index);
    }

    return TRuntimeNode(&callable, false);
}

TRuntimeNode OptimizeExtend(TCallable& callable, const TTypeEnvironment& env) {
    auto returnType = callable.GetType()->GetReturnType();
    if (!returnType->IsList()) {
        return TRuntimeNode(&callable, false);
    }

    auto itemType = static_cast<TListType*>(returnType)->GetItemType();
    if (!itemType->IsVoid()) {
        return TRuntimeNode(&callable, false);
    }

    for (ui32 i = 0; i < callable.GetInputsCount(); ++i) {
        auto seq = callable.GetInput(i);
        auto seqType = seq.GetStaticType();

        MKQL_ENSURE(seqType->IsList(), "Expected list type in extend");
        MKQL_ENSURE(static_cast<TListType*>(seqType)->GetItemType()->IsVoid(), "Expected list of void");

        if (!seq.HasValue()) {
            return TRuntimeNode(&callable, false);
        }

        TListLiteral* listValue = AS_VALUE(TListLiteral, seq);
        if (listValue->GetItemsCount() != 0) {
            return TRuntimeNode(&callable, false);
        }
    }

    return TRuntimeNode(env.GetListOfVoid(), true);
}

struct TOptimizationFuncMapFiller {
    THashMap<TString, TCallableVisitFunc> Map;
    TCallableVisitFuncProvider Provider;

    TOptimizationFuncMapFiller()
    {
        Map["If"] = &OptimizeIf;
        Map["Size"] = &OptimizeSize;
        Map["Length"] = &OptimizeLength;
        Map["AddMember"] = &OptimizeAddMember;
        Map["RemoveMember"] = &OptimizeRemoveMember;
        Map["Member"] = &OptimizeMember;
        Map["Filter"] = &OptimizeFilter;
        Map["Map"] = &OptimizeMap;
        Map["FlatMap"] = &OptimizeFlatMap;
        Map["Coalesce"] = &OptimizeCoalesce;
        Map["Exists"] = &OptimizeExists;
        Map["Nth"] = &OptimizeNth;
        Map["Extend"] = &OptimizeExtend;

        Provider = [&](TInternName name) {
            auto it = Map.find(name.Str());
            if (it != Map.end())
                return it->second;

            return TCallableVisitFunc();
        };
    }
};

} // namespace

TCallableVisitFuncProvider GetLiteralPropagationOptimizationFuncProvider() {
    return Singleton<TOptimizationFuncMapFiller>()->Provider;
}

TRuntimeNode LiteralPropagationOptimization(TRuntimeNode root, const TTypeEnvironment& env, bool inPlace) {
    TExploringNodeVisitor explorer;
    explorer.Walk(root.GetNode(), env);
    bool wereChanges = false;
    return SinglePassVisitCallables(root, explorer, GetLiteralPropagationOptimizationFuncProvider(), env, inPlace, wereChanges);
}

} // namespace NMiniKQL
} // namespace NKikimr