File: MCSOptimization.cpp

package info (click to toggle)
intel-graphics-compiler2 2.20.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 107,552 kB
  • sloc: cpp: 807,012; lisp: 287,936; ansic: 16,397; python: 4,010; yacc: 2,588; lex: 1,666; pascal: 313; sh: 186; makefile: 37
file content (236 lines) | stat: -rw-r--r-- 9,021 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
/*========================== begin_copyright_notice ============================

Copyright (C) 2017-2021 Intel Corporation

SPDX-License-Identifier: MIT

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

#include "MCSOptimization.hpp"
#include "IGCPassSupport.h"
#include "GenISAIntrinsics/GenIntrinsicInst.h"
#include "Compiler/CodeGenPublic.h"
#include "Compiler/CISACodeGen/ShaderCodeGen.hpp"
#include <set>
#include "common/LLVMWarningsPush.hpp"
#include "llvm/IR/Function.h"
#include <llvm/IR/InstVisitor.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/Casting.h>
#include "common/LLVMWarningsPop.hpp"
#include "common/IGCIRBuilder.h"
#include "common/igc_regkeys.hpp"
#include "Probe/Assertion.h"

using namespace llvm;
using namespace IGC;
/************************************************************************
This transformation is not safe in general. It can be applied only in those case:
-We know that the resouce is MCS compressed
-We need to know that we don't access out of bound sample index
************************************************************************/
class MCSOptimization : public FunctionPass, public InstVisitor<MCSOptimization> {
public:
  MCSOptimization() : FunctionPass(ID) {}
  bool runOnFunction(Function &F);
  void visitCallInst(llvm::CallInst &I);
  void getAnalysisUsage(llvm::AnalysisUsage &AU) const { AU.addRequired<CodeGenContextWrapper>(); }
  virtual llvm::StringRef getPassName() const { return "MCSOptimization"; }

  static char ID;
  bool m_changed = false;

private:
  bool shaderSamplesCompressedSurfaces(CodeGenContext *ctx) {
    ModuleMetaData *modMD = ctx->getModuleMetaData();
    for (unsigned int i = 0; i < NUM_SHADER_RESOURCE_VIEW_SIZE; i++) {
      if (modMD->m_ShaderResourceViewMcsMask[i] != 0) {
        return true;
      }
    }
    return false;
  }

protected:
};

char MCSOptimization::ID = 0;

bool MCSOptimization::runOnFunction(Function &F) {

  if (IGC_IS_FLAG_ENABLED(DisableMCSOpt)) {
    return false;
  }
  m_changed = false;
  visit(F);
  return m_changed;
}

void MCSOptimization::visitCallInst(llvm::CallInst &I) {
  Function *F = I.getParent()->getParent();
  IGCIRBuilder<> IRB(F->getContext());

  if (LdmcsInstrinsic *ldMcs = dyn_cast<LdmcsInstrinsic>(&I)) {
    CodeGenContext *ctx = getAnalysis<CodeGenContextWrapper>().getCodeGenContext();

    {
      if (!shaderSamplesCompressedSurfaces(ctx)) {
        return;
      }

      llvm::Value *textureArgValue = ldMcs->getTextureValue();
      uint textureIndex;
      if (textureArgValue->getType()->isPointerTy()) {
        uint addrSpace = textureArgValue->getType()->getPointerAddressSpace();
        uint bufferIndex = 0;
        bool directIdx = false;
        DecodeAS4GFXResource(addrSpace, directIdx, bufferIndex);
        textureIndex = bufferIndex;
      } else {
        textureIndex = int_cast<uint>(GetImmediateVal(textureArgValue));
      }

      const unsigned int shaderResourceViewMcsMaskIndex = textureIndex / BITS_PER_QWORD;
      const unsigned long long resourceViewMcsMaskElement =
          ctx->getModuleMetaData()->m_ShaderResourceViewMcsMask[shaderResourceViewMcsMaskIndex];
      const unsigned int resourceViewMaskTextureBit = textureIndex % BITS_PER_QWORD;
      IGC_ASSERT_MESSAGE(textureIndex <= 127, "Texture index is incorrectly extracted from ld_mcs");

      unsigned long long resultBit = resourceViewMcsMaskElement >> resourceViewMaskTextureBit;
      if ((resultBit & 1) == 0) {
        return;
      }
    }
    ExtractElementInst *EEI = nullptr;
    for (auto useItr : ldMcs->users()) {
      if (ExtractElementInst *ee1 = dyn_cast<ExtractElementInst>(useItr)) {
        if (ConstantInt *channel = dyn_cast<ConstantInt>(ee1->getOperand(1))) {
          if (channel->isZero()) {
            EEI = ee1;
            break;
          }
        }
      }
    }

    if (EEI != nullptr) {
      if (EEI->hasOneUse())
        return; // only one use of EEI -- noOptimization

      LdmsInstrinsic *firstUse = nullptr;

      for (auto it = EEI->getIterator(); it != EEI->getParent()->end(); ++it) {
        if (LdmsInstrinsic *ldmsIntr = dyn_cast<LdmsInstrinsic>(&*it)) {
          if (ldmsIntr->getOperand(1) == dyn_cast<Value>(EEI)) {
            // first use and in the def's BB
            firstUse = ldmsIntr;
            break;
          }
        }
      }

      if (!firstUse)
        return;

      // collect all blocks where this EEI insts is getting used
      std::set<BasicBlock *> useBlocks;
      for (auto BitcastUses = EEI->user_begin(); BitcastUses != EEI->user_end(); BitcastUses++) {
        Instruction *ldmsInst = dyn_cast<Instruction>(*BitcastUses);
        if (ldmsInst) {
          if (dyn_cast<ConstantInt>(ldmsInst->getOperand(0))) {
            useBlocks.insert(ldmsInst->getParent());
          } else {
            return;
          }
        }
      }

      // iterate over useBlocks.
      // For each useBlock, collect all the ldms insts present within the use block corresponding to this EEI
      for (auto BB : useBlocks) {
        std::vector<LdmsInstrinsic *> ldmsInstsToMove;
        std::vector<LdmsInstrinsic *> ldmsInstsToClub;
        for (auto inst = BB->begin(); inst != BB->end(); inst++) {
          if (LdmsInstrinsic *ldmsIntr = dyn_cast<LdmsInstrinsic>(inst)) {
            if (ldmsIntr->getOperand(1) == dyn_cast<Value>(EEI)) {
              if (ldmsIntr == firstUse)
                continue; // don't move the first use into the then block , need it for phi Node
              ldmsInstsToMove.push_back(ldmsIntr);
            }
          }
        }

        // this is added because clubbing all ld2dms into a single then block
        // increases register pressure and causes spilling
        int instClubThreshold =
            IGC_GET_FLAG_VALUE(ld2dmsInstsClubbingThreshold); // # ld2dms insts that can be moved into the then block
        // int instClubThreshold = 2;
        bool allInstsWillBeMoved = false;

        while (!allInstsWillBeMoved) {
          ldmsInstsToClub.clear();
          // Threshold is more than # of insts that are to be moved. So move all.
          if (instClubThreshold >= static_cast<int>(ldmsInstsToMove.size())) {
            ldmsInstsToClub = ldmsInstsToMove;
            allInstsWillBeMoved = true;
          } else {
            // pick the first 0-threshold # of insts and move them only
            for (int i = 0; i < instClubThreshold; i++) {
              ldmsInstsToClub.push_back(ldmsInstsToMove[i]);
            }
            ldmsInstsToMove.erase(ldmsInstsToMove.begin(), ldmsInstsToMove.begin() + instClubThreshold);
          }

          // split the block into a new then block
          BasicBlock *ldmsUseBB = nullptr; // second entry to the phi node
          BasicBlock *thenBlock = nullptr;
          IGCLLVM::TerminatorInst *thenBlockTerminator = nullptr;
          if (ldmsInstsToClub.size() != 0) {
            LdmsInstrinsic *ldmsUse = ldmsInstsToClub[0];
            ldmsUseBB = ldmsUse->getParent();
            IRB.SetInsertPoint(ldmsUse);
            Value *ValueisMCSNotZero = nullptr;
            for (unsigned int i = 0; i < ldmsUse->getNumMcsOperands(); i++) {
              Value *mcs = firstUse->getMcsOperand(i);
              Value *cnd1 = IRB.CreateICmpNE(mcs, ConstantInt::get(mcs->getType(), 0));
              if (ValueisMCSNotZero == nullptr) {
                ValueisMCSNotZero = cnd1;
              } else {
                ValueisMCSNotZero = IRB.CreateOr(ValueisMCSNotZero, cnd1);
              }
            }
            thenBlockTerminator = SplitBlockAndInsertIfThen(ValueisMCSNotZero, ldmsUse, false);
            thenBlock = thenBlockTerminator->getParent();
          }

          // Move the collected ldms insts into the then block and insert their phi nodes in the successor of the then
          // block
          if (thenBlockTerminator) {
            for (auto instToMove : ldmsInstsToClub) {
              instToMove->moveBefore(thenBlockTerminator);
              IRB.SetInsertPoint(&*(thenBlockTerminator->getSuccessor(0)->begin()));
              PHINode *PN = IRB.CreatePHI(instToMove->getType(), 2);
              instToMove->replaceAllUsesWith(PN);
              PN->addIncoming(instToMove, thenBlock);
              PN->addIncoming(firstUse, ldmsUseBB);
              m_changed = true;
            }
          }
        }
      }
      m_changed = true;
    }
  }
}

namespace IGC {
// Optimize ld2ms message assuming resources are always compressed"
#define PASS_FLAG "igc-mcs-optimization"
#define PASS_DESCRIPTION "This is an optimization pass for ld2dms message "
#define PASS_CFG_ONLY false
#define PASS_ANALYSIS true
IGC_INITIALIZE_PASS_BEGIN(MCSOptimization, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)
IGC_INITIALIZE_PASS_END(MCSOptimization, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)

FunctionPass *CreateMCSOptimization() { return new MCSOptimization(); }
} // namespace IGC