File: ScalarArgAsPointer.cpp

package info (click to toggle)
intel-graphics-compiler2 2.16.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 106,644 kB
  • sloc: cpp: 805,640; lisp: 287,672; ansic: 16,414; python: 3,952; yacc: 2,588; lex: 1,666; pascal: 313; sh: 186; makefile: 35
file content (362 lines) | stat: -rw-r--r-- 11,220 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
/*========================== begin_copyright_notice ============================

Copyright (C) 2022-2023 Intel Corporation

SPDX-License-Identifier: MIT

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

#include "AdaptorCommon/ImplicitArgs.hpp"
#include "Compiler/Optimizer/OpenCLPasses/ScalarArgAsPointer/ScalarArgAsPointer.hpp"
#include "Compiler/IGCPassSupport.h"

#include "common/LLVMWarningsPush.hpp"
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/GetElementPtrTypeIterator.h>
#include "llvm/Support/Debug.h"
#include "common/LLVMWarningsPop.hpp"

#include "Probe/Assertion.h"

using namespace llvm;
using namespace IGC;
using namespace IGC::IGCMD;

#define DEBUG_TYPE "igc-scalar-arg-as-pointer-analysis"

// Register pass to igc-opt
#define PASS_FLAG "igc-scalar-arg-as-pointer-analysis"
#define PASS_DESCRIPTION "Analyzes scalar kernel arguments used for global memory access"
#define PASS_CFG_ONLY false
#define PASS_ANALYSIS false
IGC_INITIALIZE_PASS_BEGIN(ScalarArgAsPointerAnalysis, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)
IGC_INITIALIZE_PASS_DEPENDENCY(MetaDataUtilsWrapper)
IGC_INITIALIZE_PASS_END(ScalarArgAsPointerAnalysis, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)

char ScalarArgAsPointerAnalysis::ID = 0;

ScalarArgAsPointerAnalysis::ScalarArgAsPointerAnalysis() : ModulePass(ID) {
  initializeScalarArgAsPointerAnalysisPass(*PassRegistry::getPassRegistry());
}

bool ScalarArgAsPointerAnalysis::runOnModule(Module &M) {
  DL = &M.getDataLayout();

  MDU = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils();

  bool changed = false;

  for (Function &F : M) {
    if (F.isDeclaration())
      continue;

    if (!isEntryFunc(MDU, &F))
      continue;

    changed |= analyzeFunction(F);
  }

  // Update LLVM metadata based on IGC MetadataUtils
  if (changed)
    MDU->save(M.getContext());

  return changed;
}

bool ScalarArgAsPointerAnalysis::analyzeFunction(llvm::Function &F) {
  m_matchingArgs.clear();
  m_visitedInst.clear();
  m_allocas.clear();
  m_currentFunction = &F;

  LLVM_DEBUG(dbgs() << "running for function " << F.getName() << "\n");

  visit(F);

  if (m_matchingArgs.empty())
    return false;

  FunctionMetaData &funcMD = getAnalysis<MetaDataUtilsWrapper>().getModuleMetaData()->FuncMD[&F];

  for (auto it = m_matchingArgs.begin(); it != m_matchingArgs.end(); ++it)
    funcMD.m_OpenCLArgScalarAsPointers.insert((*it)->getArgNo());

  return true;
}

void ScalarArgAsPointerAnalysis::visitStoreInst(llvm::StoreInst &I) {
  analyzeStoredArg(I);
  analyzePointer(I.getPointerOperand());
}

void ScalarArgAsPointerAnalysis::visitLoadInst(llvm::LoadInst &I) { analyzePointer(I.getPointerOperand()); }

void ScalarArgAsPointerAnalysis::visitCallInst(CallInst &CI) {
  if (auto I = dyn_cast<GenIntrinsicInst>(&CI))
    return visitGenIntrinsic(*I);

  // If function takes pointer as argument, assume it is used for access.
  for (auto it = CI.op_begin(); it != CI.op_end(); ++it) {
    if (isa<PointerType>((*it)->getType()))
      analyzePointer(*it);
  }
}

void ScalarArgAsPointerAnalysis::visitGenIntrinsic(GenIntrinsicInst &I) {
  GenISAIntrinsic::ID const id = I.getIntrinsicID();

  if (id == GenISAIntrinsic::GenISA_LSC2DBlockRead || id == GenISAIntrinsic::GenISA_LSC2DBlockPrefetch ||
      id == GenISAIntrinsic::GenISA_LSC2DBlockWrite) {
    return analyzeValue(I.getOperand(0));
  }

  if (IsStatelessMemLoadIntrinsic(id) || IsStatelessMemStoreIntrinsic(id) || IsStatelessMemAtomicIntrinsic(I, id)) {
    Value *V = GetBufferOperand(&I);

    if (!V || !isa<PointerType>(V->getType()))
      return;

    return analyzePointer(V);
  }
}

void ScalarArgAsPointerAnalysis::analyzePointer(llvm::Value *V) {
  auto *type = dyn_cast<PointerType>(V->getType());

  IGC_ASSERT_MESSAGE(type, "Value should be a pointer");

  if (type->getAddressSpace() != ADDRESS_SPACE_GLOBAL && type->getAddressSpace() != ADDRESS_SPACE_GENERIC)
    return;

  analyzeValue(V);
}

void ScalarArgAsPointerAnalysis::analyzeValue(llvm::Value *V) {
  std::shared_ptr<ScalarArgAsPointerAnalysis::ArgSet> args;

  if (auto *I = dyn_cast<Instruction>(V)) {
    args = findArgs(I);
  } else {
    args = analyzeOperand(V);
  }

  if (args) {
    LLVM_DEBUG(for (auto a : *args) {
      dbgs() << "  access from pointer ";
      V->printAsOperand(dbgs(), false);
      dbgs() << " tracks to argument ";
      a->printAsOperand(dbgs(), false);
      dbgs() << "\n";
    });
    m_matchingArgs.insert(args->begin(), args->end());
  }
}

const std::shared_ptr<ScalarArgAsPointerAnalysis::ArgSet>
ScalarArgAsPointerAnalysis::findArgs(llvm::Instruction *inst) {
  // Skip already visited instruction
  if (m_visitedInst.count(inst))
    return m_visitedInst[inst];

  // Mark as visited
  m_visitedInst.try_emplace(inst, nullptr);

  // Assume intrinsic are safe simple arithmetics.
  if (isa<CallInst>(inst) && !isa<GenIntrinsicInst>(inst))
    return nullptr;

  auto result = std::make_shared<ScalarArgAsPointerAnalysis::ArgSet>();

  if (LoadInst *LI = dyn_cast<LoadInst>(inst)) {
    if (!findStoredArgs(*LI, *result))
      return nullptr; // (1) Found indirect access, fail search
  } else {
    // Iterate and trace back operands.
    auto begin = inst->operands().begin();
    auto end = inst->operands().end();

    if (isa<SelectInst>(inst)) {
      // For select, skip condition operand (first arg)
      begin++;
    } else if (isa<GetElementPtrInst>(inst)) {
      // For GEP, use only base pointer operand (first arg)
      end = begin + 1;
    }

    for (auto it = begin; it != end; ++it) {
      auto args = analyzeOperand(*it);

      if (args)
        result->insert(args->begin(), args->end());
    }

    if (result->empty())
      return nullptr; // propagate fail
  }

  m_visitedInst[inst] = result;
  return result;
}

const std::shared_ptr<ScalarArgAsPointerAnalysis::ArgSet> ScalarArgAsPointerAnalysis::analyzeOperand(llvm::Value *op) {
  auto result = std::make_shared<ScalarArgAsPointerAnalysis::ArgSet>();

  if (Argument *arg = dyn_cast<Argument>(op)) {
    // Consider only integer arguments
    if (arg->getType()->getScalarType()->isIntegerTy()) {
      result->insert(arg);
    } else {
      // (2) Found non-compatible argument, fail
      return nullptr;
    }
  } else if (Instruction *opInst = dyn_cast<Instruction>(op)) {
    auto args = findArgs(opInst);

    if (!args)
      return nullptr; // propagate fail

    result->insert(args->begin(), args->end());
  } else if (GlobalValue *global = dyn_cast<GlobalValue>(op)) {
    Argument *arg = analyzeGlobal(global);

    if (!arg)
      return nullptr; // propagate fail

    result->insert(arg);
  }

  return result;
}

llvm::Argument *ScalarArgAsPointerAnalysis::analyzeGlobal(llvm::GlobalValue *V) {
  PointerType *type = dyn_cast<PointerType>(V->getType());
  if (!type)
    return nullptr;

  if (type->getAddressSpace() != ADDRESS_SPACE_GLOBAL)
    return nullptr;

  ImplicitArgs implicitArgs(*m_currentFunction, MDU);

  if (!implicitArgs.isImplicitArgExist(ImplicitArg::GLOBAL_BASE))
    return nullptr;

  if (m_currentFunction->arg_size() < implicitArgs.size())
    return nullptr;

  unsigned implicitArgsBaseIndex = m_currentFunction->arg_size() - implicitArgs.size();
  unsigned implicitArgIndex = implicitArgs.getArgIndex(ImplicitArg::GLOBAL_BASE);
  return std::next(m_currentFunction->arg_begin(), implicitArgsBaseIndex + implicitArgIndex);
}

void ScalarArgAsPointerAnalysis::analyzeStoredArg(llvm::StoreInst &SI) {
  // Only track stores of kernel arguments.
  Argument *A = dyn_cast<Argument>(SI.getValueOperand());
  if (!A)
    return;

  AllocaInst *AI = nullptr;
  GetElementPtrInst *GEPI = nullptr;
  if (!findAllocaWithOffset(SI.getPointerOperand(), AI, GEPI))
    return;

  uint64_t totalOffset = 0;

  if (GEPI) {
    // For store instruction offset must be constant.
    APInt offset(DL->getIndexTypeSizeInBits(GEPI->getType()), 0);
    if (!GEPI->accumulateConstantOffset(*DL, offset) || offset.isNegative())
      return;
    totalOffset += offset.getZExtValue();
  }

  m_allocas[std::pair<llvm::AllocaInst *, uint64_t>(AI, totalOffset)] = A;
}

bool ScalarArgAsPointerAnalysis::findStoredArgs(llvm::LoadInst &LI, ArgSet &args) {
  AllocaInst *AI = nullptr;
  GetElementPtrInst *GEPI = nullptr;
  if (!findAllocaWithOffset(LI.getPointerOperand(), AI, GEPI))
    return false;

  // It is possible one or more GEP operand is a variable index to array type.
  // In this case search for all possible offsets to alloca.
  using Offsets = SmallVector<uint64_t, 4>;
  Offsets offsets;
  offsets.push_back(0);

  if (GEPI) {
    for (gep_type_iterator GTI = gep_type_begin(GEPI), prevGTI = gep_type_end(GEPI); GTI != gep_type_end(GEPI);
         prevGTI = GTI++) {
      if (ConstantInt *C = dyn_cast<ConstantInt>(GTI.getOperand())) {
        if (C->isZero())
          continue;

        uint64_t offset = 0;

        if (StructType *STy = GTI.getStructTypeOrNull())
          offset = DL->getStructLayout(STy)->getElementOffset(int_cast<unsigned>(C->getZExtValue()));
        else
          offset = C->getZExtValue() * DL->getTypeAllocSize(GTI.getIndexedType()); // array or vector

        for (auto it = offsets.begin(); it != offsets.end(); ++it)
          *it += offset;
      } else {
        if (prevGTI == gep_type_end(GEPI))
          return false; // variable index at first operand, should not happen

        // gep_type_iterator is used to query indexed type. For arrays this is type
        // of single element. To get array size, we need to do query for it at
        // previous iterator step (before stepping into type indexed by array).
        ArrayType *ATy = dyn_cast<ArrayType>(prevGTI.getIndexedType());
        if (!ATy)
          return false;

        uint64_t arrayElements = ATy->getNumElements();

        uint64_t byteSize = DL->getTypeAllocSize(GTI.getIndexedType());

        Offsets tmp;
        for (auto i = 0; i < arrayElements; ++i)
          for (auto it = offsets.begin(); it != offsets.end(); ++it)
            tmp.push_back(*it + i * byteSize);

        offsets = std::move(tmp);
      }
    }
  }

  for (auto it = offsets.begin(); it != offsets.end(); ++it) {
    std::pair<llvm::AllocaInst *, uint64_t> key(AI, *it);
    if (m_allocas.count(key))
      args.insert(m_allocas[key]);
  }

  return !args.empty();
}

bool ScalarArgAsPointerAnalysis::findAllocaWithOffset(llvm::Value *V, llvm::AllocaInst *&outAI,
                                                      llvm::GetElementPtrInst *&outGEPI) {
  IGC_ASSERT_MESSAGE(dyn_cast<PointerType>(V->getType()), "Value should be a pointer");

  outGEPI = nullptr;
  Value *tmp = V;

  while (true) {
    if (BitCastInst *BCI = dyn_cast<BitCastInst>(tmp)) {
      tmp = BCI->getOperand(0);
    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(tmp)) {
      if (outGEPI)
        return false; // only one GEP instruction is supported
      outGEPI = GEPI;
      tmp = GEPI->getPointerOperand();
    } else if (AllocaInst *AI = dyn_cast<AllocaInst>(tmp)) {
      outAI = AI;
      return true;
    } else {
      return false;
    }
  }
}