File: StackFrameInfo.cpp

package info (click to toggle)
intel-graphics-compiler 1.0.12504.6-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 83,912 kB
  • sloc: cpp: 910,147; lisp: 202,655; ansic: 15,197; python: 4,025; yacc: 2,241; lex: 1,570; pascal: 244; sh: 104; makefile: 25
file content (620 lines) | stat: -rw-r--r-- 17,887 bytes parent folder | download
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/*========================== begin_copyright_notice ============================

Copyright (C) 2019-2021 Intel Corporation

SPDX-License-Identifier: MIT

============================= end_copyright_notice ===========================*/

#include "StackFrameInfo.h"
#include "MDFrameWork.h"
#include "RTBuilder.h"
#include "common/LLVMWarningsPush.hpp"
#include <llvm/IR/InstIterator.h>
#include "common/LLVMWarningsPop.hpp"
#include "Probe/Assertion.h"

/*

Note [Stack Layout]

F1 stack start----> +----------------+   ^   (F1 = Stack Frame 1)
                    |                |   |
                    |    Alloca F1   |   |
                    |                |   |   F1 stack size
                    +----------------+   |
                    |                |   |
                    | Spilled var F1 |   |
                    |                |   |
F2 stack start----> +----------------+   v
                    |                |   ^
                    |  Return IP to  |   |
                    |  continuation  |   |
                    |                |   |   F2 stack size
                    +----------------+   |
                    |                |   |
                    |    Arguments   |   |
                    |                |   |
                    +----------------+   |
                    |                |   |
                    |    Alloca F2   |   |
                    |                |   |
                    +----------------+   |
                    |                |   |
                    | Spilled var F2 |   |
                    |                |   v
 F3 stack start---> +----------------+
                    |                |            Note [Argument Order]
                    | Return IP to   |        ----+-----------------+
                    | F2 continuation|       /    | Payload Pointer |
                    |                |      /     +-----------------+
                    +----------------+-----/      |    Hit Kind     | (procedural)
                    |                |            +-----------------+
                    |  Arguments to  |            | Custom Hit Attr | (procedural)
                    |  F3            |           /+-----------------+
                    +----------------+----------/

Note that this stack layout is purely a construct of the compiler.  The hardware
doesn't know anything about it.

*/

using namespace llvm;
using namespace IGC;
using namespace RTStackFormat;

static std::string getTypeRepr(const Type* Ty)
{
    std::string s;
    raw_string_ostream ss(s);
    Ty->print(ss);
    ss.flush();
    return s;
}

bool StackFrameInfo::skipRecording() const
{
    return (IGC_IS_FLAG_DISABLED(RayTracingDumpYaml) || !LogStackFrameEntries);
}

StackFrameInfo::StackFrameInfo(
    const Function *RootFunc,
    CallableShaderTypeMD ShaderType,
    Optional<HIT_GROUP_TYPE> HitGroupTy,
    RayDispatchShaderContext *RayCtx,
    const FunctionMetaData &FMD,
    RayTracingSWTypes& RTSWTypes,
    bool LogStackFrameEntries) :
    RTArgs(RootFunc, ShaderType, HitGroupTy, RayCtx, FMD, RTSWTypes, LogStackFrameEntries)
{
}

void StackFrameInfo::addFunction(const Function *F)
{
    addAllocas(F);
    addSpills(F);
    addFills(F);
}

bool StackFrameInfo::isContinuation(const Function* F) const
{
    return (F != RootFunction);
}

bool StackFrameInfo::isRoot(const Function* F) const
{
    return !isContinuation(F);
}

bool StackFrameInfo::isRayGen() const
{
    return (FuncType == RayGen);
}

bool StackFrameInfo::isRayGenRoot(const Function *F) const
{
    return (isRayGen() && isRoot(F));
}

uint32_t StackFrameInfo::getAllocasOffset() const
{
    // Raygen has no return IP since it is always the first frame on the
    // call stack so the allocas would be right at the start of the frame
    // in that case.
    if (FuncType == RayGen)
        return 0;

    return TraceRayRTArgs::getPayloadOffset() + ArgumentSize;
}

uint32_t StackFrameInfo::getSpillOffset() const
{
    return getAllocasOffset() + TotalAllocaSize;
}

uint32_t StackFrameInfo::getFrameSize() const
{
    uint32_t TotalSize = getSpillOffset() + TotalSpillSize;
    TotalSize = IGC::Align(TotalSize, StackFrameAlign);

    return TotalSize;
}

void StackFrameInfo::addAllocas(const Function *F)
{
    auto &DL = F->getParent()->getDataLayout();
    auto& C = F->getContext();

    SmallVector<Type*, 4> Tys;

    auto getAlignment = [=](const AllocaInst* AI) -> alignment_t {
        auto Alignment = AI->getAlignment();
        if (Alignment == 0)
            Alignment = DL.getABITypeAlignment(AI->getAllocatedType());
        return Alignment;
    };

    SmallVector<const AllocaInst*, 4> Allocas;

    for (auto& I : instructions(*F))
    {
        if (auto* AI = dyn_cast<AllocaInst>(&I))
        {
            if (!RTBuilder::isNonLocalAlloca(AI))
                continue;

            Allocas.push_back(AI);
        }
    }

    llvm::stable_sort(Allocas,
        [=](const AllocaInst* AI1, const AllocaInst* AI2) {
        return getAlignment(AI1) > getAlignment(AI2);
    });

    uint32_t CurAllocaIdx = 0;
    for (auto* AI : Allocas)
    {
        Tys.push_back(AI->getAllocatedType());
        AllocaIdxMap[AI] = CurAllocaIdx++;
    }

    AllocaStructTy = Tys.empty() ?
        StructType::get(C, true) :
        StructType::create(C, Tys, "IGC::Allocas", false);

    TotalAllocaSize = int_cast<uint32_t>(DL.getTypeAllocSize(AllocaStructTy));
    recordAllocaEntries(Allocas, AllocaStructTy);
}

void StackFrameInfo::recordAllocaEntries(
    ArrayRef<const AllocaInst*> Allocas,
    StructType* StructTy)
{
    if (skipRecording())
        return;

    auto *Layout = DL.getStructLayout(StructTy);

    for (uint32_t i = 0; i < Allocas.size(); i++)
    {
        auto* AI = Allocas[i];

        StackFrameEntry Entry;
        Entry.Name = "N/A";
        if (AI->hasName())
            Entry.Name = AI->getName().str();
        Entry.Offset = int_cast<uint32_t>(Layout->getElementOffset(i));
        Entry.TypeRepr = getTypeRepr(AI->getAllocatedType());
        Entry.EntryType = ENTRY_ALLOCA;
        Entry.Size =
            int_cast<uint32_t>(DL.getTypeAllocSize(AI->getAllocatedType()));
        AllocaEntries.push_back(Entry);
    }

}

void StackFrameInfo::addFills(const Function* F)
{
    auto& DL = F->getParent()->getDataLayout();
    auto& C = F->getContext();
    uint64_t CurOffset = 0;
    uint32_t CurFillIdx = 0;

    SmallVector<const FillValueIntrinsic*, 4> Fills;
    for (auto& I : instructions(*F))
    {
        if (auto* II = dyn_cast<FillValueIntrinsic>(&I))
            Fills.push_back(II);
    }

    std::stable_sort(Fills.begin(), Fills.end(), [&](auto* A, auto* B) {
        return A->getOffset() < B->getOffset();
    });

    SmallVector<Type*, 4> Tys;
    DenseMap<uint64_t, uint32_t> OffsetToIdx;
    for (auto *FI : Fills)
    {
        uint64_t Offset = FI->getOffset();
        uint64_t TypeSize = DL.getTypeAllocSize(FI->getType());

        if (auto I = OffsetToIdx.find(Offset); I != OffsetToIdx.end())
        {
            FillIdxMap[FI] = I->second;
        }
        else
        {
            if (CurOffset != Offset)
            {
                IGC_ASSERT_MESSAGE((CurOffset < Offset), "bad offset!");
                // insert padding
                uint64_t Diff = Offset - CurOffset;
                auto* Padding = ArrayType::get(Type::getInt8Ty(C), Diff);
                Tys.push_back(Padding);
                CurFillIdx++;
            }
            OffsetToIdx[Offset] = CurFillIdx;

            Tys.push_back(FI->getType());
            FillIdxMap[FI] = CurFillIdx++;
            CurOffset = Offset + TypeSize;
        }
    }

    if (!Tys.empty())
    {
        auto *StructTy = StructType::create(C, Tys, "IGC::Fills", true);
        FillTyMap[F] = StructTy;
    }
}

void StackFrameInfo::addSpillsCompacted(const Function* F)
{
    auto& C = F->getContext();
    bool DoLog = !skipRecording();
    for (auto &BB : *F)
    {
        std::string ContName;
        std::vector<StackFrameEntry> Entries;

        uint64_t CurOffset = 0;
        uint32_t CurSpillIdx = 0;
        SmallVector<Type*, 4> Tys;
        for (auto &I : BB)
        {
            if (auto *II = dyn_cast<SpillValueIntrinsic>(&I))
            {
                uint64_t Offset = II->getOffset();
                uint64_t TypeSize = DL.getTypeAllocSize(
                    II->getData()->getType());

                if (CurOffset != Offset)
                {
                    IGC_ASSERT_MESSAGE((CurOffset < Offset), "bad offset!");
                    // insert padding
                    uint64_t Diff = Offset - CurOffset;
                    auto* Padding = ArrayType::get(Type::getInt8Ty(C), Diff);
                    Tys.push_back(Padding);
                    CurSpillIdx++;
                }

                Tys.push_back(II->getData()->getType());
                SpillIdxMap[II] = CurSpillIdx++;
                CurOffset = Offset + TypeSize;

                recordSpillUnionEntry(II, Entries, (uint32_t)TypeSize);

                TotalSpillSize = std::max(
                    TotalSpillSize,
                    (uint32_t)(Offset + TypeSize));
            }

            if (DoLog)
            {
                if (auto* CI = dyn_cast<ContinuationHLIntrinsic>(&I))
                    ContName = CI->getContinuationFn()->getName().str();
            }
        }

        if (!Tys.empty())
        {
            auto *StructTy = StructType::create(C, Tys, "IGC::Spills", true);
            SpillTyMap[&BB] = StructTy;
        }

        if (DoLog)
        {
            if (!ContName.empty())
            {
                StackFrameSpillUnion Union{ ContName, Entries };
                SpillEntries.push_back(Union);
            }
        }
    }
}

void StackFrameInfo::addSpillsUncompacted(const Function* F)
{
    auto& C = F->getContext();

    SmallVector<const SpillValueIntrinsic*, 4> Spills;
    for (auto& I : instructions(*F))
    {
        if (auto* II = dyn_cast<SpillValueIntrinsic>(&I))
            Spills.push_back(II);
    }

    std::stable_sort(Spills.begin(), Spills.end(), [&](auto* A, auto* B) {
        return A->getOffset() < B->getOffset();
    });

    uint64_t CurOffset = 0;
    uint32_t CurSpillIdx = 0;
    SmallVector<Type*, 4> Tys;
    DenseMap<uint64_t, uint32_t> OffsetToIdx;
    for (auto* II : Spills)
    {
        uint64_t Offset = II->getOffset();
        uint64_t TypeSize = DL.getTypeAllocSize(
            II->getData()->getType());

        if (auto I = OffsetToIdx.find(Offset); I != OffsetToIdx.end())
        {
            SpillIdxMap[II] = I->second;
        }
        else
        {
            if (CurOffset != Offset)
            {
                IGC_ASSERT_MESSAGE((CurOffset < Offset), "bad offset!");
                // insert padding
                uint64_t Diff = Offset - CurOffset;
                auto* Padding = ArrayType::get(Type::getInt8Ty(C), Diff);
                Tys.push_back(Padding);
                CurSpillIdx++;
            }
            OffsetToIdx[Offset] = CurSpillIdx;

            Tys.push_back(II->getData()->getType());
            SpillIdxMap[II] = CurSpillIdx++;
            CurOffset = Offset + TypeSize;

            TotalSpillSize = std::max(
                TotalSpillSize,
                (uint32_t)(Offset + TypeSize));
        }
    }

    if (!Tys.empty())
    {
        auto* StructTy = StructType::create(C, Tys, "IGC::Spills", true);
        for (auto& BB : *F)
        {
            SpillTyMap[&BB] = StructTy;
        }
    }
}

void StackFrameInfo::addSpills(const Function *F)
{
    if (IGC_IS_FLAG_ENABLED(DisableCompactifySpills))
        addSpillsUncompacted(F);
    else
        addSpillsCompacted(F);
}

void StackFrameInfo::recordSpillUnionEntry(
    const llvm::SpillValueIntrinsic* SV,
    std::vector<StackFrameEntry>& Entries,
    uint32_t Size)
{
    if (skipRecording())
        return;

    StackFrameEntry Entry;
    Entry.Name = "N/A";
    if (SV->getData()->hasName())
        Entry.Name = SV->getData()->getName().str();
    Entry.Offset = (uint32_t)SV->getOffset();
    Entry.TypeRepr = getTypeRepr(SV->getData()->getType());
    Entry.EntryType = ENTRY_SPILL;
    Entry.Size = Size;
    Entries.push_back(Entry);
}

Value* StackFrameInfo::getSpillPtr(
    IRBuilder<>& IRB,
    RTBuilder::SWStackPtrVal* FrameAddr,
    const SpillValueIntrinsic* SI,
    const Twine& Name) const
{
    auto* BB = SI->getParent();
    auto I = SpillTyMap.find(BB);
    IGC_ASSERT_MESSAGE(I != SpillTyMap.end(), "missing?");

    auto* PtrTy = I->second->getPointerTo(SWStackAddrSpace);

    auto* Ptr = IRB.CreateBitOrPointerCast(
        FrameAddr, PtrTy, VALUE_NAME("&Frame"));

    auto IdxI = SpillIdxMap.find(SI);
    IGC_ASSERT_MESSAGE(IdxI != SpillIdxMap.end(), "missing?");

    Value* Indices[] = {
        IRB.getInt32(0),
        IRB.getInt32(*SpillSlot),
        IRB.getInt32(IdxI->second)
    };

    return IRB.CreateInBoundsGEP(I->second, Ptr, Indices, Name);
}

Value* StackFrameInfo::getFillPtr(
    IRBuilder<>& IRB,
    RTBuilder::SWStackPtrVal* FrameAddr,
    const FillValueIntrinsic* FI,
    const Twine& Name) const
{
    auto I = FillTyMap.find(FI->getFunction());
    IGC_ASSERT_MESSAGE(I != FillTyMap.end(), "missing?");

    auto* PtrTy = I->second->getPointerTo(SWStackAddrSpace);

    auto* Ptr = IRB.CreateBitOrPointerCast(
        FrameAddr, PtrTy, VALUE_NAME("&Frame"));

    auto IdxI = FillIdxMap.find(FI);
    IGC_ASSERT_MESSAGE(IdxI != FillIdxMap.end(), "missing?");

    Value* Indices[] = {
        IRB.getInt32(0),
        IRB.getInt32(*SpillSlot),
        IRB.getInt32(IdxI->second)
    };

    return IRB.CreateInBoundsGEP(I->second, Ptr, Indices, Name);
}

Value* StackFrameInfo::getAllocaPtr(
    IRBuilder<>& IRB,
    RTBuilder::SWStackPtrVal* FrameAddr,
    const AllocaInst* AI,
    const Twine& Name) const
{
    auto* PtrTy = AllocaStructTy->getPointerTo(SWStackAddrSpace);

    auto* Ptr = IRB.CreateBitOrPointerCast(
        FrameAddr, PtrTy, VALUE_NAME("&Frame"));

    auto IdxI = AllocaIdxMap.find(AI);
    IGC_ASSERT_MESSAGE(IdxI != AllocaIdxMap.end(), "missing?");

    Value* Indices[] = {
        IRB.getInt32(0),
        IRB.getInt32(*AllocaSlot),
        IRB.getInt32(IdxI->second)
    };

    return IRB.CreateInBoundsGEP(AllocaStructTy, Ptr, Indices, Name);
}

void StackFrameInfo::finalize()
{
    // Create all the whole frame types (See Note [Stack Layout])
    ArgumentSlot = 0;
    AllocaSlot   = 1;
    SpillSlot    = 2;

    auto& C = RootFunction->getContext();

    Type* ArgumentTy = nullptr;
    if (FuncType == RayGen)
    {
        // No args for raygen.  Stub out an empty type.
        ArgumentTy = StructType::get(C, true);
    }
    else
    {
        ArgumentTy = getArgumentType();
    }

    Type* CurAllocaStructTy = AllocaStructTy;
    auto mkSpillType = [&](StructType* SpillTy)
    {
        SmallVector<Type*, 4> Tys{
            ArgumentTy,
            CurAllocaStructTy,
            SpillTy
        };

        auto* Ty = StructType::create(
            RootFunction->getContext(), Tys, "IGC::Frame", true);

        return Ty;
    };

    auto mkAllocaType = [&](StructType* AllocaTy)
    {
        SmallVector<Type*, 4> Tys{
            ArgumentTy,
            AllocaTy,
        };

        auto* Ty = StructType::create(
            RootFunction->getContext(), Tys, "IGC::Frame", true);

        return Ty;
    };

    AllocaStructTy = mkAllocaType(AllocaStructTy);

    RTSWTypes.FullFrameTys.push_back(AllocaStructTy);

    // Update the spill map with the whole struct
    for (auto& [BB, SpillTy] : SpillTyMap)
    {
        auto* FrameTy = mkSpillType(SpillTy);
        IGC_ASSERT(nullptr != BB);
        IGC_ASSERT_MESSAGE(BB->getModule()->getDataLayout().getTypeAllocSize(FrameTy) <= getFrameSize(), "too big?");
        SpillTyMap[BB] = FrameTy;
        RTSWTypes.FullFrameTys.push_back(FrameTy);
    }

    // Update the spill map with the whole struct
    for (auto& [F, FillTy] : FillTyMap)
    {
        auto* FrameTy = mkSpillType(FillTy);
        IGC_ASSERT(nullptr != F);
        IGC_ASSERT_MESSAGE(F->getParent()->getDataLayout().getTypeAllocSize(FrameTy) <= getFrameSize(), "too big?");
        FillTyMap[F] = FrameTy;
        RTSWTypes.FullFrameTys.push_back(FrameTy);
    }

    // The below code is for debugging purposes.
    if (skipRecording())
        return;

    // patch up the offsets from all data in the stack frame and write it out
    // to metadata.  The metadata will be read at the end of compilation to
    // dump this information out to the *output.yaml file.
    for (auto& Alloca : AllocaEntries)
        Alloca.Offset += getAllocasOffset();

    for (auto& UnionEntry : SpillEntries)
    {
        for (auto& Entry : UnionEntry.Entries)
            Entry.Offset += getSpillOffset();
    }

    ModuleMetaData* ModMD = Ctx.getModuleMetaData();
    auto& FuncMD = ModMD->FuncMD;

    auto Entry = FuncMD.find(const_cast<Function*>(RootFunction));
    IGC_ASSERT_MESSAGE((Entry != FuncMD.end()), "Missing metadata?");

    auto &rtInfo = Entry->second.rtInfo;

    // Raygen shaders doen't have a return IP because there's nothing to return
    // to once raygen is done.
    if (FuncType != RayGen)
    {
        StackFrameEntry RetIP;
        RetIP.Name = "Return IP";
        RetIP.Offset = TraceRayRTArgs::getReturnIPOffset();
        // represent that we may have a pointer or an ID there for now.
        RetIP.TypeRepr = "i8 addrspace(1)* | i64";
        RetIP.EntryType = ENTRY_RETURN_IP;
        RetIP.Size = sizeof(TraceRayRTArgs::ReturnIP);

        rtInfo.Entries.push_back(RetIP);
    }

    for (auto& Arg : ArgumentEntries)
        rtInfo.Entries.push_back(Arg);

    for (auto& Alloca : AllocaEntries)
        rtInfo.Entries.push_back(Alloca);

    rtInfo.SpillUnions = SpillEntries;
}