-
Notifications
You must be signed in to change notification settings - Fork 497
/
cfg.h
519 lines (441 loc) · 16.5 KB
/
cfg.h
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// Copyright (C) 2022-2024 Exaloop Inc. <https://exaloop.io>
#pragma once
#include <iostream>
#include <list>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include "codon/cir/analyze/analysis.h"
#include "codon/cir/cir.h"
#include "codon/cir/util/iterators.h"
#define DEFAULT_VISIT(x) \
void visit(const x *v) override { defaultInsert(v); }
namespace codon {
namespace ir {
namespace analyze {
namespace dataflow {
class CFGraph;
class CFBlock : public IdMixin {
private:
/// the in-order list of values in this block
std::list<const Value *> values;
/// an un-ordered list of successor blocks
std::unordered_set<CFBlock *> successors;
/// an un-ordered list of successor blocks
std::unordered_set<CFBlock *> predecessors;
/// the block's name
std::string name;
/// the graph
CFGraph *graph;
public:
/// Constructs a control-flow block.
/// @param graph the parent graph
/// @param name the block's name
explicit CFBlock(CFGraph *graph, std::string name = "")
: name(std::move(name)), graph(graph) {}
virtual ~CFBlock() noexcept = default;
/// @return this block's name
std::string getName() const { return name; }
/// @return an iterator to the first value
auto begin() { return values.begin(); }
/// @return an iterator beyond the last value
auto end() { return values.end(); }
/// @return an iterator to the first value
auto begin() const { return values.begin(); }
/// @return an iterator beyond the last value
auto end() const { return values.end(); }
/// @return a pointer to the first value
const Value *front() const { return values.front(); }
/// @return a pointer to the last value
const Value *back() const { return values.back(); }
/// Inserts a value at a given position.
/// @param it the position
/// @param v the new value
/// @param an iterator to the new value
template <typename It> auto insert(It it, const Value *v) {
values.insert(it, v);
reg(v);
}
/// Inserts a value at the back.
/// @param v the new value
void push_back(const Value *v) {
values.push_back(v);
reg(v);
}
/// Erases a value at the given position.
/// @param it the position
/// @return an iterator following the removed value
template <typename It> auto erase(It it) { values.erase(it); }
/// @return an iterator to the first successor
auto successors_begin() { return successors.begin(); }
/// @return an iterator beyond the last successor
auto successors_end() { return successors.end(); }
/// @return an iterator to the first successor
auto successors_begin() const { return successors.begin(); }
/// @return an iterator beyond the last successor
auto successors_end() const { return successors.end(); }
/// Inserts a successor at some position.
/// @param v the new successor
/// @return an iterator to the new successor
auto successors_insert(CFBlock *v) {
successors.insert(v);
v->predecessors.insert(this);
}
/// Removes a given successor.
/// @param v the successor to remove
auto successors_erase(CFBlock *v) {
successors.erase(v);
v->predecessors.erase(this);
}
/// @return an iterator to the first predecessor
auto predecessors_begin() { return predecessors.begin(); }
/// @return an iterator beyond the last predecessor
auto predecessors_end() { return predecessors.end(); }
/// @return an iterator to the first predecessor
auto predecessors_begin() const { return predecessors.begin(); }
/// @return an iterator beyond the last predecessor
auto predecessors_end() const { return predecessors.end(); }
/// @return the graph
CFGraph *getGraph() { return graph; }
/// @return the graph
const CFGraph *getGraph() const { return graph; }
/// Sets the graph.
/// @param g the new graph
void setGraph(CFGraph *g) { graph = g; }
private:
void reg(const Value *v);
};
class SyntheticAssignInstr : public AcceptorExtend<SyntheticAssignInstr, Instr> {
public:
enum Kind { UNKNOWN, KNOWN, NEXT_VALUE, ADD };
private:
/// the left-hand side
Var *lhs;
/// the kind of synthetic assignment
Kind kind;
/// any argument to the synthetic assignment
Value *arg = nullptr;
/// the difference
int64_t diff = 0;
public:
static const char NodeId;
/// Constructs a synthetic assignment.
/// @param lhs the variable being assigned
/// @param arg the argument
/// @param k the kind of assignment
/// @param name the name of the instruction
SyntheticAssignInstr(Var *lhs, Value *arg, Kind k = KNOWN, std::string name = "")
: AcceptorExtend(std::move(name)), lhs(lhs), kind(k), arg(arg) {}
/// Constructs an unknown synthetic assignment.
/// @param lhs the variable being assigned
/// @param name the name of the instruction
explicit SyntheticAssignInstr(Var *lhs, std::string name = "")
: SyntheticAssignInstr(lhs, nullptr, UNKNOWN, std::move(name)) {}
/// Constructs an addition synthetic assignment.
/// @param lhs the variable being assigned
/// @param diff the difference
/// @param name the name of the instruction
SyntheticAssignInstr(Var *lhs, int64_t diff, std::string name = "")
: AcceptorExtend(std::move(name)), lhs(lhs), kind(ADD), diff(diff) {}
/// @return the variable being assigned
Var *getLhs() { return lhs; }
/// @return the variable being assigned
const Var *getLhs() const { return lhs; }
/// Sets the variable being assigned.
/// @param v the variable
void setLhs(Var *v) { lhs = v; }
/// @return the argument
Value *getArg() { return arg; }
/// @return the argument
const Value *getArg() const { return arg; }
/// Sets the argument.
/// @param v the new value
void setArg(Value *v) { arg = v; }
/// @return the diff
int64_t getDiff() const { return diff; }
/// Sets the diff.
/// @param v the new value
void setDiff(int64_t v) { diff = v; }
/// @return the kind of synthetic assignment
Kind getKind() const { return kind; }
/// Sets the kind.
/// @param k the new value
void setKind(Kind k) { kind = k; }
protected:
std::vector<Value *> doGetUsedValues() const override { return {arg}; }
int doReplaceUsedValue(id_t id, Value *newValue) override;
std::vector<Var *> doGetUsedVariables() const override { return {lhs}; }
int doReplaceUsedVariable(id_t id, Var *newVar) override;
};
class SyntheticPhiInstr : public AcceptorExtend<SyntheticPhiInstr, Instr> {
public:
class Predecessor {
private:
/// the predecessor block
CFBlock *pred;
/// the value
Value *result;
public:
/// Constructs a predecessor.
/// @param pred the predecessor block
/// @param result the result of this predecessor.
Predecessor(CFBlock *pred, Value *result) : pred(pred), result(result) {}
/// @return the predecessor block
CFBlock *getPred() { return pred; }
/// @return the predecessor block
const CFBlock *getPred() const { return pred; }
/// Sets the predecessor.
/// @param v the new value
void setPred(CFBlock *v) { pred = v; }
/// @return the result
Value *getResult() { return result; }
/// @return the result
const Value *getResult() const { return result; }
/// Sets the result
/// @param v the new value
void setResult(Value *v) { result = v; }
};
private:
std::list<Predecessor> preds;
public:
static const char NodeId;
explicit SyntheticPhiInstr(std::string name = "") : AcceptorExtend(std::move(name)) {}
/// @return an iterator to the first instruction/flow
auto begin() { return preds.begin(); }
/// @return an iterator beyond the last instruction/flow
auto end() { return preds.end(); }
/// @return an iterator to the first instruction/flow
auto begin() const { return preds.begin(); }
/// @return an iterator beyond the last instruction/flow
auto end() const { return preds.end(); }
/// @return a pointer to the first instruction/flow
Predecessor &front() { return preds.front(); }
/// @return a pointer to the last instruction/flow
Predecessor &back() { return preds.back(); }
/// @return a pointer to the first instruction/flow
const Predecessor &front() const { return preds.front(); }
/// @return a pointer to the last instruction/flow
const Predecessor &back() const { return preds.back(); }
/// Inserts a predecessor.
/// @param pos the position
/// @param v the predecessor
/// @return an iterator to the newly added predecessor
template <typename It> auto insert(It pos, Predecessor v) {
return preds.insert(pos, v);
}
/// Appends an predecessor.
/// @param v the predecessor
void push_back(Predecessor v) { preds.push_back(v); }
/// Erases the item at the supplied position.
/// @param pos the position
/// @return the iterator beyond the removed predecessor
template <typename It> auto erase(It pos) { return preds.erase(pos); }
/// Emplaces a predecessor.
/// @param args the args
template <typename... Args> void emplace_back(Args &&...args) {
preds.emplace_back(std::forward<Args>(args)...);
}
protected:
std::vector<Value *> doGetUsedValues() const override;
int doReplaceUsedValue(id_t id, Value *newValue) override;
};
class CFGraph {
private:
/// owned list of blocks
std::list<std::unique_ptr<CFBlock>> blocks;
/// the current block
CFBlock *cur = nullptr;
/// the function being analyzed
const BodiedFunc *func;
/// a list of synthetic values
std::list<std::unique_ptr<Value>> syntheticValues;
/// a map of synthetic values
std::unordered_map<id_t, Value *> valueMapping;
/// a list of synthetic variables
std::list<std::unique_ptr<Var>> syntheticVars;
/// a mapping from value id to block
std::unordered_map<id_t, CFBlock *> valueLocations;
public:
/// Constructs a control-flow graph.
explicit CFGraph(const BodiedFunc *f);
/// @return an iterator to the first block
auto begin() { return util::raw_ptr_adaptor(blocks.begin()); }
/// @return an iterator beyond the last block
auto end() { return util::raw_ptr_adaptor(blocks.end()); }
/// @return an iterator to the first block
auto begin() const { return util::raw_ptr_adaptor(blocks.begin()); }
/// @return an iterator beyond the last block
auto end() const { return util::raw_ptr_adaptor(blocks.end()); }
/// @return an iterator to the synthetic value
auto synth_begin() { return util::raw_ptr_adaptor(syntheticValues.begin()); }
/// @return an iterator beyond the last synthetic value
auto synth_end() { return util::raw_ptr_adaptor(syntheticValues.end()); }
/// @return an iterator to the first synthetic value
auto synth_begin() const { return util::raw_ptr_adaptor(syntheticValues.begin()); }
/// @return an iterator beyond the last synthetic value
auto synth_end() const { return util::raw_ptr_adaptor(syntheticValues.end()); }
/// @return the entry block
CFBlock *getEntryBlock() { return blocks.front().get(); }
/// @return the entry block
const CFBlock *getEntryBlock() const { return blocks.front().get(); }
/// @return the entry block
CFBlock *getCurrentBlock() { return cur; }
/// @return the entry block
const CFBlock *getCurrentBlock() const { return cur; }
/// Sets the current block.
/// @param v the new value
void setCurrentBlock(CFBlock *v) { cur = v; }
/// @return the function
const BodiedFunc *getFunc() const { return func; }
/// Sets the function.
/// @param f the new value
void setFunc(BodiedFunc *f) { func = f; }
/// Gets the block containing a value.
/// @param val the value
/// @return the block
CFBlock *getBlock(const Value *v) {
auto vmIt = valueMapping.find(v->getId());
if (vmIt != valueMapping.end())
v = vmIt->second;
auto it = valueLocations.find(v->getId());
return it != valueLocations.end() ? it->second : nullptr;
}
/// Gets the block containing a value.
/// @param val the value
/// @return the block
const CFBlock *getBlock(const Value *v) const {
auto vmIt = valueMapping.find(v->getId());
if (vmIt != valueMapping.end())
v = vmIt->second;
auto it = valueLocations.find(v->getId());
return it != valueLocations.end() ? it->second : nullptr;
}
/// Creates and inserts a new block
/// @param name the name
/// @param setCur true if the block should be made the current one
/// @return a newly inserted block
CFBlock *newBlock(std::string name = "", bool setCur = false) {
auto *ret = new CFBlock(this, std::move(name));
blocks.emplace_back(ret);
if (setCur)
setCurrentBlock(ret);
return ret;
}
template <typename NodeType, typename... Args> NodeType *N(Args &&...args) {
auto *ret = new NodeType(std::forward<Args>(args)...);
reg(ret);
ret->setModule(func->getModule());
return ret;
}
/// Remaps a value.
/// @param id original id
/// @param newValue the new value
void remapValue(id_t id, Value *newValue) { valueMapping[id] = newValue; }
/// Remaps a value.
/// @param original the original value
/// @param newValue the new value
void remapValue(const Value *original, Value *newValue) {
remapValue(original->getId(), newValue);
}
/// Gets a value by id.
/// @param id the id
/// @return the value or nullptr
Value *getValue(id_t id) {
auto it = valueMapping.find(id);
return it != valueMapping.end() ? it->second : func->getModule()->getValue(id);
}
friend std::ostream &operator<<(std::ostream &os, const CFGraph &cfg);
friend class CFBlock;
private:
void reg(Var *v) { syntheticVars.emplace_back(v); }
void reg(Value *v) {
syntheticValues.emplace_back(v);
valueMapping[v->getId()] = v;
}
};
/// Builds a control-flow graph from a given function.
/// @param f the function
/// @return the control-flow graph
std::unique_ptr<CFGraph> buildCFGraph(const BodiedFunc *f);
/// Control-flow analysis result.
struct CFResult : public Result {
/// map from function id to control-flow graph
std::unordered_map<id_t, std::unique_ptr<CFGraph>> graphs;
};
/// Control-flow analysis that runs on all functions.
class CFAnalysis : public Analysis {
public:
static const std::string KEY;
std::string getKey() const override { return KEY; }
std::unique_ptr<Result> run(const Module *m) override;
};
class CFVisitor : public util::ConstVisitor {
private:
struct Loop {
analyze::dataflow::CFBlock *nextIt;
analyze::dataflow::CFBlock *end;
id_t loopId;
int tcIndex;
Loop(analyze::dataflow::CFBlock *nextIt, analyze::dataflow::CFBlock *end,
id_t loopId, int tcIndex = -1)
: nextIt(nextIt), end(end), loopId(loopId), tcIndex(tcIndex) {}
};
analyze::dataflow::CFGraph *graph;
std::vector<std::pair<analyze::dataflow::CFBlock *, analyze::dataflow::CFBlock *>>
tryCatchStack;
std::unordered_set<id_t> seenIds;
std::vector<Loop> loopStack;
public:
explicit CFVisitor(analyze::dataflow::CFGraph *graph) : graph(graph) {}
void visit(const BodiedFunc *f) override;
DEFAULT_VISIT(VarValue)
DEFAULT_VISIT(PointerValue)
void visit(const SeriesFlow *v) override;
void visit(const IfFlow *v) override;
void visit(const WhileFlow *v) override;
void visit(const ForFlow *v) override;
void visit(const ImperativeForFlow *v) override;
void visit(const TryCatchFlow *v) override;
void visit(const PipelineFlow *v) override;
void visit(const dsl::CustomFlow *v) override;
DEFAULT_VISIT(TemplatedConst<int64_t>);
DEFAULT_VISIT(TemplatedConst<double>);
DEFAULT_VISIT(TemplatedConst<bool>);
DEFAULT_VISIT(TemplatedConst<std::string>);
DEFAULT_VISIT(dsl::CustomConst);
void visit(const AssignInstr *v) override;
void visit(const ExtractInstr *v) override;
void visit(const InsertInstr *v) override;
void visit(const CallInstr *v) override;
DEFAULT_VISIT(StackAllocInstr);
DEFAULT_VISIT(TypePropertyInstr);
DEFAULT_VISIT(YieldInInstr);
void visit(const TernaryInstr *v) override;
void visit(const BreakInstr *v) override;
void visit(const ContinueInstr *v) override;
void visit(const ReturnInstr *v) override;
void visit(const YieldInstr *v) override;
void visit(const ThrowInstr *v) override;
void visit(const FlowInstr *v) override;
void visit(const dsl::CustomInstr *v) override;
template <typename NodeType> void process(const NodeType *v) {
if (!v)
return;
if (seenIds.find(v->getId()) != seenIds.end())
return;
seenIds.insert(v->getId());
v->accept(*this);
}
void defaultInsert(const Value *v);
void defaultJump(const CFBlock *cf, int newTcLevel = -1);
private:
Loop &findLoop(id_t id);
};
} // namespace dataflow
} // namespace analyze
} // namespace ir
} // namespace codon
template <>
struct fmt::formatter<codon::ir::analyze::dataflow::CFGraph> : fmt::ostream_formatter {
};
#undef DEFAULT_VISIT