File: BufferBoundsChecking.cpp

package info (click to toggle)
intel-graphics-compiler 1.0.17791.18-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 102,312 kB
  • sloc: cpp: 935,343; lisp: 286,143; ansic: 16,196; python: 3,279; yacc: 2,487; lex: 1,642; pascal: 300; sh: 174; makefile: 27
file content (435 lines) | stat: -rw-r--r-- 15,732 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
/*========================== begin_copyright_notice ============================

Copyright (C) 2024 Intel Corporation

SPDX-License-Identifier: MIT

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

#include "BufferBoundsChecking.hpp"
#include "BufferBoundsCheckingPatcher.hpp"

#include "Compiler/IGCPassSupport.h"
#include "Compiler/MetaDataApi/MetaDataApi.h"

#include "common/LLVMWarningsPush.hpp"
#include "llvmWrapper/IR/Type.h"
#include "llvmWrapper/IR/Function.h"
#include <llvm/Demangle/Demangle.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/GetElementPtrTypeIterator.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Mangler.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/Regex.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include "common/LLVMWarningsPop.hpp"

#include "Compiler/Optimizer/ValueTracker.h"

using namespace llvm;
using namespace IGC;

// Register pass to igc-opt
#define PASS_FLAG "igc-buffer-bounds-checking"
#define PASS_DESCRIPTION "Buffer bounds checking"
#define PASS_CFG_ONLY false
#define PASS_ANALYSIS false
IGC_INITIALIZE_PASS_BEGIN(BufferBoundsChecking, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)
IGC_INITIALIZE_PASS_DEPENDENCY(MetaDataUtilsWrapper)
IGC_INITIALIZE_PASS_END(BufferBoundsChecking, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)

char BufferBoundsChecking::ID = 0;

BufferBoundsChecking::BufferBoundsChecking() : ModulePass(ID)
{
    initializeBufferBoundsCheckingPass(*PassRegistry::getPassRegistry());
}

bool BufferBoundsChecking::runOnModule(Module& M)
{
    modified = false;

    metadataUtils = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils();
    moduleMetadata = getAnalysis<MetaDataUtilsWrapper>().getModuleMetaData();
    auto context = getAnalysis<CodeGenContextWrapper>().getCodeGenContext();

    compileUnit = nullptr;
    if (M.debug_compile_units().begin() != M.debug_compile_units().end())
    {
        compileUnit = *M.debug_compile_units().begin();
    }

    for (auto& function : M.functions())
    {
        if (!isEntryFunc(metadataUtils, &function))
        {
            continue;
        }

        // Add implicit arg
        ImplicitArg::ArgMap argMap;
        for (const auto& arg : function.args())
        {
            if (!argumentQualifiesForChecking(&arg))
            {
                continue;
            }

            argMap[ImplicitArg::BUFFER_SIZE].insert(arg.getArgNo());
        }

        if (!argMap.empty())
        {
            ImplicitArgs::addNumberedArgs(function, argMap, metadataUtils);
            modified = true;
        }

        // Kernel args
        kernelArgs = new KernelArgs(function, &function.getParent()->getDataLayout(), metadataUtils, moduleMetadata, context->platform.getGRFSize());

        // Local and global Ids
        std::tie(localId0, localId1, localId2) = getLocalIds(function);
        std::tie(globalId0, globalId1, globalId2) = getGlobalIds(function);

        // Collect loads/stores
        loadsAndStoresToCheck.clear();
        visit(function);

        // Handle loads/stores
        for (auto& instruction : loadsAndStoresToCheck)
        {
            handleLoadStore(instruction);
        }
    }

    return modified;
}

void BufferBoundsChecking::visitLoadInst(LoadInst& load)
{
    loadsAndStoresToCheck.push_back(&load);
}

void BufferBoundsChecking::visitStoreInst(StoreInst& store)
{
    loadsAndStoresToCheck.push_back(&store);
}

std::tuple<Value*, Value*, Value*> BufferBoundsChecking::getLocalIds(Function& function)
{
    auto getOrCreateBuiltin = [&function](const char* name)
    {
        return function.getParent()->getOrInsertFunction(
            name,
            FunctionType::get(Type::getInt32Ty(function.getContext()),
            false));
    };

    return {
        CallInst::Create(getOrCreateBuiltin("__builtin_IB_get_local_id_x"), {}, "localId0", function.getEntryBlock().getFirstNonPHI()),
        CallInst::Create(getOrCreateBuiltin("__builtin_IB_get_local_id_y"), {}, "localId1", function.getEntryBlock().getFirstNonPHI()),
        CallInst::Create(getOrCreateBuiltin("__builtin_IB_get_local_id_z"), {}, "localId2", function.getEntryBlock().getFirstNonPHI()),
    };
}

std::tuple<Value*, Value*, Value*> BufferBoundsChecking::getGlobalIds(Function& function)
{
    auto builtin = function.getParent()->getOrInsertFunction(
        "__builtin_IB_get_group_id",
        FunctionType::get(Type::getInt32Ty(function.getContext()), { Type::getInt32Ty(function.getContext()) },
        false));

    return {
        CallInst::Create(builtin, { ConstantInt::get(Type::getInt32Ty(function.getContext()), 0) }, "globalId0", function.getEntryBlock().getFirstNonPHI()),
        CallInst::Create(builtin, { ConstantInt::get(Type::getInt32Ty(function.getContext()), 1) }, "globalId1", function.getEntryBlock().getFirstNonPHI()),
        CallInst::Create(builtin, { ConstantInt::get(Type::getInt32Ty(function.getContext()), 2) }, "globalId2", function.getEntryBlock().getFirstNonPHI()),
    };
}

void BufferBoundsChecking::handleLoadStore(Instruction* instruction)
{
    Value* pointer = nullptr;
    if (auto load = dyn_cast<LoadInst>(instruction))
    {
        pointer = load->getPointerOperand();
    }
    else if (auto store = dyn_cast<StoreInst>(instruction))
    {
        pointer = store->getPointerOperand();
    }
    else
    {
        IGC_ASSERT(0);
    }

    auto accessInfo = getAccessInfo(instruction, pointer);
    if (!accessInfo.bufferOffsetInBytes)
    {
        return;
    }
    createBoundsCheckingCode(instruction, accessInfo);
    modified = true;
}

bool BufferBoundsChecking::argumentQualifiesForChecking(const Argument* argument)
{
    auto pointerType = dyn_cast<PointerType>(argument->getType());
    return pointerType &&
           (pointerType->getPointerAddressSpace() == ADDRESS_SPACE_CONSTANT ||
            pointerType->getPointerAddressSpace() == ADDRESS_SPACE_GLOBAL);
}

Value* BufferBoundsChecking::createBoundsCheckingCondition(const AccessInfo& accessInfo, Instruction* insertBefore)
{
    const auto zero = ConstantInt::get(Type::getInt64Ty(insertBefore->getModule()->getContext()), 0);

    auto bufferSizePlaceholder = createBufferSizePlaceholder(accessInfo.implicitArgBufferSizeIndex, insertBefore);

    auto bufferSizeIsZero = new ICmpInst(insertBefore, ICmpInst::ICMP_EQ, bufferSizePlaceholder, zero);
    auto bufferOffsetIsGreaterOrEqualZero = new ICmpInst(insertBefore, ICmpInst::ICMP_SGE, accessInfo.bufferOffsetInBytes, zero);
    auto upperBound = BinaryOperator::Create(Instruction::Sub, bufferSizePlaceholder, accessInfo.elementSizeInBytes, "", insertBefore);
    auto bufferOffsetIsLessThanSizeMinusElemSize = new ICmpInst(insertBefore, ICmpInst::ICMP_SLT, accessInfo.bufferOffsetInBytes, upperBound);

    return BinaryOperator::Create(Instruction::Or,
        bufferSizeIsZero,
        BinaryOperator::Create(Instruction::And,
            bufferOffsetIsGreaterOrEqualZero,
            bufferOffsetIsLessThanSizeMinusElemSize,
            "",
            insertBefore),
        "",
        insertBefore);
}

Value* BufferBoundsChecking::createLoadStoreReplacement(Instruction* instruction, Instruction* insertBefore)
{
    if (auto load = dyn_cast<LoadInst>(instruction))
    {
        return Constant::getNullValue(instruction->getType());
    }
    else if (auto store = dyn_cast<StoreInst>(instruction))
    {
        return new StoreInst(store->getValueOperand(), ConstantPointerNull::get(dyn_cast<PointerType>(store->getPointerOperandType())), insertBefore);
    }
    else
    {
        IGC_ASSERT(0);
        return nullptr;
    }
}

void BufferBoundsChecking::createAssertCall(const AccessInfo& accessInfo, Instruction* insertBefore)
{
    auto M = insertBefore->getModule();

    auto assertArgs = createAssertArgs(accessInfo, insertBefore);
    auto assertArgsTypes = SmallVector<Type*, 4>{};
    std::transform(assertArgs.begin(), assertArgs.end(), std::back_inserter(assertArgsTypes), [](Value* value) { return value->getType(); });

    auto assert = cast<Function>(M->getOrInsertFunction(
        compileUnit ? "__bufferoutofbounds_assert" : "__bufferoutofbounds_assert_nodebug",
        FunctionType::get(Type::getVoidTy(M->getContext()), assertArgsTypes, false)
    ).getCallee());

    auto call = CallInst::Create(assert, assertArgs, "", insertBefore);
    call->setCallingConv(CallingConv::SPIR_FUNC);
}

SmallVector<Value*, 4> BufferBoundsChecking::createAssertArgs(const AccessInfo& accessInfo, llvm::Instruction* insertBefore)
{
    auto createGEP = [insertBefore](GlobalVariable* globalVariable)
    {
        const auto zero = ConstantInt::getSigned(Type::getInt32Ty(globalVariable->getParent()->getContext()), 0);
        auto result = GetElementPtrInst::Create(
            globalVariable->getValueType(),
            globalVariable,
            { zero, zero },
            "",
            insertBefore
        );
        result->setIsInBounds(true);
        return result;
    };

    SmallVector<Value*, 4> result;
    if (compileUnit)
    {
        result.push_back(createGEP(getOrCreateGlobalConstantString(insertBefore->getModule(), accessInfo.filename)));
        result.push_back(ConstantInt::getSigned(Type::getInt32Ty(insertBefore->getContext()), accessInfo.line));
        result.push_back(ConstantInt::getSigned(Type::getInt32Ty(insertBefore->getContext()), accessInfo.column));
        result.push_back(createGEP(getOrCreateGlobalConstantString(insertBefore->getModule(), accessInfo.bufferName)));
    }
    else
    {
        result.push_back(accessInfo.bufferAddress);
    }
    result.push_back(accessInfo.bufferOffsetInBytes);
    result.push_back(createBufferSizePlaceholder(accessInfo.implicitArgBufferSizeIndex, insertBefore));
    result.push_back(localId0);
    result.push_back(localId1);
    result.push_back(localId2);
    result.push_back(globalId0);
    result.push_back(globalId1);
    result.push_back(globalId2);

    return result;
}

GlobalVariable* BufferBoundsChecking::getOrCreateGlobalConstantString(Module* M, StringRef str)
{
    if (stringsCache.count(str) == 0)
    {
        stringsCache[str] = new GlobalVariable(
            *M,
            ArrayType::get(Type::getInt8Ty(M->getContext()), str.size() + 1),
            true,
            GlobalValue::InternalLinkage,
            ConstantDataArray::getString(M->getContext(), str, true),
            "",
            nullptr,
            GlobalValue::ThreadLocalMode::NotThreadLocal,
            ADDRESS_SPACE_CONSTANT);
        stringsCache[str]->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
    }

    return stringsCache[str];
}

void BufferBoundsChecking::createBoundsCheckingCode(Instruction* instruction, const AccessInfo& accessInfo)
{
    auto condition = createBoundsCheckingCondition(accessInfo, instruction);

    // Generate if-then-else
    Instruction* thenTerminator = nullptr;
    Instruction* elseTerminator = nullptr;
    SplitBlockAndInsertIfThenElse(condition, instruction, &thenTerminator, &elseTerminator);

    // Merge block
    auto mergeBlock = instruction->getParent();
    mergeBlock->setName("bufferboundschecking.end");

    // Valid offset
    auto thenBlock = thenTerminator->getParent();
    thenBlock->setName("bufferboundschecking.valid");
    instruction->moveBefore(thenTerminator);

    // Invalid offset
    auto elseBlock = elseTerminator->getParent();
    elseBlock->setName("bufferboundschecking.invalid");
    createAssertCall(accessInfo, elseTerminator);
    auto replacement = createLoadStoreReplacement(instruction, elseTerminator);

    // PhiNode
    if (isa<LoadInst>(instruction))
    {
        PHINode* phi = PHINode::Create(instruction->getType(), 2, "", &mergeBlock->front());
        instruction->replaceUsesOutsideBlock(phi, thenBlock);
        phi->addIncoming(instruction, thenBlock);
        phi->addIncoming(replacement, elseBlock);
    }
}

const KernelArg* BufferBoundsChecking::getKernelArg(Value* value)
{
    for (const KernelArg& arg : *kernelArgs)
    {
        if (arg.getArg() == value)
        {
            return &arg;
        }
    }
    return nullptr;
}

const KernelArg* BufferBoundsChecking::getKernelArgFromPtr(const PointerType& pointerType, Value* value)
{
    if (value == nullptr)
        return nullptr;

    // stripPointerCasts might skip addrSpaceCast, thus check if AS is still
    // the original one.
    unsigned int ptrAS = pointerType.getAddressSpace();
    if (cast<PointerType>(value->getType())->getAddressSpace() == ptrAS && !isa<Instruction>(value))
    {
        if (const KernelArg* arg = getKernelArg(value))
            return arg;
    }
    return nullptr;
}

BufferBoundsChecking::AccessInfo BufferBoundsChecking::getAccessInfo(Instruction* instruction, Value* value)
{
    auto pointerType = dyn_cast<PointerType>(value->getType());
    IGC_ASSERT_MESSAGE(pointerType, "Expected scalar Pointer (No support to vector of pointers");
    if (!pointerType || (pointerType->getAddressSpace() != ADDRESS_SPACE_GLOBAL &&
        pointerType->getAddressSpace() != ADDRESS_SPACE_CONSTANT))
    {
        return AccessInfo{};
    }

    // Track value
    auto base = ValueTracker::track(value, instruction->getFunction(), metadataUtils, moduleMetadata);
    const auto* arg = getKernelArgFromPtr(*pointerType, base);
    if (!arg)
    {
        return AccessInfo{};
    }

    auto baseAddress = new PtrToIntInst(base, Type::getInt64Ty(instruction->getContext()), "", instruction);
    auto address = new PtrToIntInst(value, Type::getInt64Ty(instruction->getContext()), "", instruction);

    auto debugLoc = instruction->getDebugLoc();

    AccessInfo result;
    result.filename = compileUnit ? compileUnit->getFilename() : "";
    result.line = debugLoc ? debugLoc->getLine() : 0;
    result.column = debugLoc ? debugLoc->getColumn() : 0;
    result.bufferName = arg->getArg()->getName();
    result.bufferAddress = baseAddress;
    result.bufferOffsetInBytes = BinaryOperator::CreateSub(address, baseAddress, "", instruction);
    result.implicitArgBufferSizeIndex = (int)std::count_if(
        instruction->getFunction()->arg_begin(),
        instruction->getFunction()->arg_begin() + arg->getAssociatedArgNo(),
        [this](const Argument& arg)
        {
            return argumentQualifiesForChecking(&arg);
        });

    Type* type = nullptr;
    if (auto load = dyn_cast<LoadInst>(instruction))
    {
        type = instruction->getType();
    }
    else if (auto store = dyn_cast<StoreInst>(instruction))
    {
        type = store->getValueOperand()->getType();
    }
    else
    {
        IGC_ASSERT(0);
    }
    result.elementSizeInBytes = ConstantInt::get(Type::getInt64Ty(instruction->getContext()),
                                          instruction->getModule()->getDataLayout().getTypeSizeInBits(type) / 8);

    return result;
}

Value* BufferBoundsChecking::createBufferSizePlaceholder(uint32_t implicitArgBufferSizeIndex, Instruction* insertBefore)
{
    if (!bufferSizePlaceholderFunction)
    {
        auto M = insertBefore->getModule();
        bufferSizePlaceholderFunction = cast<Function>(M->getOrInsertFunction(
            BufferBoundsCheckingPatcher::BUFFER_SIZE_PLACEHOLDER_FUNCTION_NAME,
            FunctionType::get(Type::getInt64Ty(M->getContext()), {Type::getInt64Ty(M->getContext())}, false)
        ).getCallee());
    }

    auto result = CallInst::Create(bufferSizePlaceholderFunction, {
            ConstantInt::getSigned(Type::getInt64Ty(insertBefore->getContext()), implicitArgBufferSizeIndex),
        }, "", insertBefore);
    result->setCallingConv(CallingConv::SPIR_FUNC);
    return result;
}