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
|
#include "slang-ir-redundancy-removal.h"
#include "slang-ir-dominators.h"
#include "slang-ir-simplify-cfg.h"
#include "slang-ir-util.h"
namespace Slang
{
struct RedundancyRemovalContext
{
RefPtr<IRDominatorTree> dom;
bool tryHoistInstToOuterMostLoop(IRGlobalValueWithCode* func, IRInst* inst)
{
bool changed = false;
for (auto parentBlock = dom->getImmediateDominator(as<IRBlock>(inst->getParent()));
parentBlock;
parentBlock = dom->getImmediateDominator(parentBlock))
{
auto terminatorInst = parentBlock->getTerminator();
if (auto loop = as<IRLoop>(terminatorInst))
{
// Don't bother hoisting if a loop has only a single trivial iteration.
if (isTrivialSingleIterationLoop(dom, func, loop))
continue;
// If `inst` is outside of the loop region, don't hoist it into the loop.
if (dom->dominates(loop->getBreakBlock(), inst))
continue;
// Consider hoisting the inst into this block.
// This is only possible if all operands of the inst are dominating
// `parentBlock`.
bool canHoist = true;
for (UInt i = 0; i < inst->getOperandCount(); i++)
{
auto operand = inst->getOperand(i);
if (!hasDescendent(func, operand))
{
// Only prevent hoisting from operands local to this function
continue;
}
auto operandParent = as<IRBlock>(operand->getParent());
if (!operandParent)
{
canHoist = false;
break;
}
canHoist = dom->dominates(operandParent, parentBlock);
if (!canHoist)
break;
}
if (!canHoist)
break;
// Move inst to parentBlock.
inst->insertBefore(terminatorInst);
changed = true;
// Continue to consider outer hoisting positions.
}
}
return changed;
}
bool removeRedundancyInBlock(
Dictionary<IRBlock*, DeduplicateContext>& mapBlockToDedupContext,
IRGlobalValueWithCode* func,
IRBlock* block,
bool hoistLoopInvariantInsts)
{
bool result = false;
auto& deduplicateContext = mapBlockToDedupContext.getValue(block);
for (auto instP : block->getModifiableChildren())
{
auto resultInst = deduplicateContext.deduplicate(
instP,
[&](IRInst* inst)
{
auto parentBlock = as<IRBlock>(inst->getParent());
if (!parentBlock)
return false;
if (dom->isUnreachable(parentBlock))
return false;
return isMovableInst(inst);
});
if (resultInst != instP)
{
instP->replaceUsesWith(resultInst);
instP->removeAndDeallocate();
result = true;
}
else if (isMovableInst(resultInst))
{
// This inst is unique, we should consider hoisting it
// if it is inside a loop.
if (hoistLoopInvariantInsts)
result |= tryHoistInstToOuterMostLoop(func, resultInst);
}
}
for (auto child : dom->getImmediatelyDominatedBlocks(block))
{
DeduplicateContext& subContext = mapBlockToDedupContext.getValue(child);
subContext.deduplicateMap = deduplicateContext.deduplicateMap;
}
return result;
}
};
bool removeRedundancy(IRModule* module, bool hoistLoopInvariantInsts)
{
bool changed = false;
for (auto inst : module->getGlobalInsts())
{
if (auto genericInst = as<IRGeneric>(inst))
{
removeRedundancyInFunc(genericInst, hoistLoopInvariantInsts);
inst = findGenericReturnVal(genericInst);
}
if (auto func = as<IRFunc>(inst))
{
changed |= removeRedundancyInFunc(func, hoistLoopInvariantInsts);
}
}
return changed;
}
bool removeRedundancyInFunc(IRGlobalValueWithCode* func, bool hoistLoopInvariantInsts)
{
auto root = func->getFirstBlock();
if (!root)
return false;
RedundancyRemovalContext context;
context.dom = computeDominatorTree(func);
Dictionary<IRBlock*, DeduplicateContext> mapBlockToDeduplicateContext;
for (auto block : func->getBlocks())
{
mapBlockToDeduplicateContext[block] = DeduplicateContext();
}
List<IRBlock*> workList, pendingWorkList;
workList.add(root);
bool result = false;
while (workList.getCount())
{
for (auto block : workList)
{
result |= context.removeRedundancyInBlock(
mapBlockToDeduplicateContext,
func,
block,
hoistLoopInvariantInsts);
for (auto child : context.dom->getImmediatelyDominatedBlocks(block))
{
pendingWorkList.add(child);
}
}
workList.swapWith(pendingWorkList);
pendingWorkList.clear();
}
if (auto normalFunc = as<IRFunc>(func))
{
result |= eliminateRedundantLoadStore(normalFunc);
}
return result;
}
// Remove IR definitions from all AvailableInDownstreamIR functions where the
// languages match what we're currently targetting, as these functions are
// already defined in the embedded precompiled library.
void removeAvailableInDownstreamModuleDecorations(CodeGenTarget target, IRModule* module)
{
List<IRInst*> toRemove;
auto builder = IRBuilder(module);
for (auto globalInst : module->getGlobalInsts())
{
if (auto funcInst = as<IRFunc>(globalInst))
{
if (auto dec = globalInst->findDecoration<IRAvailableInDownstreamIRDecoration>())
{
if ((dec->getTarget() == CodeGenTarget::DXIL && target == CodeGenTarget::HLSL) ||
(dec->getTarget() == target))
{
// Gut the function definition, turning it into a declaration
for (auto block : funcInst->getBlocks())
{
toRemove.add(block);
}
builder.addDecoration(funcInst, kIROp_DownstreamModuleImportDecoration);
}
}
}
}
for (auto inst : toRemove)
{
inst->removeAndDeallocate();
}
}
static IRInst* _getRootVar(IRInst* inst)
{
while (inst)
{
switch (inst->getOp())
{
case kIROp_FieldAddress:
case kIROp_GetElementPtr:
inst = inst->getOperand(0);
break;
default:
return inst;
}
}
return inst;
}
bool tryRemoveRedundantStore(IRGlobalValueWithCode* func, IRStore* store)
{
// We perform a quick and conservative check:
// A store is redundant if it is followed by another store to the same address in
// the same basic block, and there are no instructions that may use any addresses
// related to this address.
bool hasAddrUse = false;
bool hasOverridingStore = false;
// Stores to global variables will never get removed.
auto rootVar = _getRootVar(store->getPtr());
if (!isChildInstOf(rootVar, func))
return false;
// A store can be removed if it stores into a local variable
// that has no other uses than store.
if (const auto varInst = as<IRVar>(rootVar))
{
bool hasNonStoreUse = false;
// If the entire access chain doesn't non-store use, we can safely remove it.
InstHashSet knownAccessChain(func->getModule());
for (auto accessChain = store->getPtr(); accessChain;)
{
knownAccessChain.add(accessChain);
for (auto use = accessChain->firstUse; use; use = use->nextUse)
{
if (as<IRDecoration>(use->getUser()))
continue;
if (knownAccessChain.contains(use->getUser()))
continue;
if (use->getUser()->getOp() == kIROp_Store && use == use->getUser()->getOperands())
{
continue;
}
hasNonStoreUse = true;
break;
}
if (hasNonStoreUse)
break;
switch (accessChain->getOp())
{
case kIROp_GetElementPtr:
case kIROp_FieldAddress:
accessChain = accessChain->getOperand(0);
continue;
default:
break;
}
break;
}
if (!hasNonStoreUse)
{
store->removeAndDeallocate();
return true;
}
}
// A store can be removed if there are subsequent stores to the same variable,
// and there are no insts in between the stores that can read the variable.
HashSet<IRBlock*> visitedBlocks;
for (auto next = store->getNextInst(); next;)
{
if (auto nextStore = as<IRStore>(next))
{
if (nextStore->getPtr() == store->getPtr())
{
hasOverridingStore = true;
break;
}
}
// If we see any insts that have reads or modifies the address before seeing
// an overriding store, don't remove the store.
// We can make the test more accurate by collecting all addresses related to
// the target address first, and only bail out if any of the related addresses
// are involved.
switch (next->getOp())
{
case kIROp_Load:
if (canAddressesPotentiallyAlias(func, next->getOperand(0), store->getPtr()))
{
hasAddrUse = true;
}
break;
default:
if (canInstHaveSideEffectAtAddress(func, next, store->getPtr()))
{
hasAddrUse = true;
}
break;
}
if (hasAddrUse)
break;
// If we are at the end of the current block and see a unconditional branch,
// we can follow the path and check the subsequent block.
if (auto branch = as<IRUnconditionalBranch>(next))
{
auto nextBlock = branch->getTargetBlock();
if (visitedBlocks.add(nextBlock))
{
next = nextBlock->getFirstInst();
continue;
}
}
next = next->getNextInst();
}
if (!hasAddrUse && hasOverridingStore)
{
store->removeAndDeallocate();
return true;
}
// A store can be removed if it is a store into the same var, and there are
// no side effects between the load of the var and the store of the var.
if (auto load = as<IRLoad>(store->getVal()))
{
if (load->getPtr() == store->getPtr())
{
if (load->getParent() == store->getParent())
{
bool valueMayChange = false;
for (auto inst = load->next; inst; inst = inst->next)
{
if (inst == store)
break;
if (canInstHaveSideEffectAtAddress(func, inst, store->getPtr()))
{
valueMayChange = true;
break;
}
}
if (!valueMayChange)
{
store->removeAndDeallocate();
return true;
}
}
}
}
return false;
}
bool eliminateRedundantLoadStore(IRGlobalValueWithCode* func)
{
bool changed = false;
for (auto block : func->getBlocks())
{
for (auto inst = block->getFirstInst(); inst;)
{
auto nextInst = inst->getNextInst();
if (auto load = as<IRLoad>(inst))
{
for (auto prev = inst->getPrevInst(); prev; prev = prev->getPrevInst())
{
if (auto store = as<IRStore>(prev))
{
if (store->getPtr() == load->getPtr())
{
// If the load is preceeded by a store without any side-effect insts
// in-between, remove the load.
auto value = store->getVal();
load->replaceUsesWith(value);
load->removeAndDeallocate();
changed = true;
break;
}
}
if (canInstHaveSideEffectAtAddress(func, prev, load->getPtr()))
{
break;
}
}
}
else if (auto store = as<IRStore>(inst))
{
changed |= tryRemoveRedundantStore(func, store);
}
inst = nextInst;
}
}
return changed;
}
} // namespace Slang
|