29#define DEBUG_TYPE "dxil-flatten-arrays"
34class DXILFlattenArraysLegacy :
public ModulePass {
37 bool runOnModule(
Module &M)
override;
45 Value *RootPointerOperand;
50class DXILFlattenArraysVisitor
51 :
public InstVisitor<DXILFlattenArraysVisitor, bool> {
53 DXILFlattenArraysVisitor(
55 : GlobalMap(GlobalMap) {}
63 bool visitICmpInst(
ICmpInst &ICI) {
return false; }
64 bool visitFCmpInst(
FCmpInst &FCI) {
return false; }
67 bool visitCastInst(
CastInst &CI) {
return false; }
68 bool visitBitCastInst(
BitCastInst &BCI) {
return false; }
72 bool visitPHINode(
PHINode &
PHI) {
return false; }
75 bool visitCallInst(
CallInst &ICI) {
return false; }
76 bool visitFreezeInst(
FreezeInst &FI) {
return false; }
77 static bool isMultiDimensionalArray(
Type *
T);
78 static std::pair<unsigned, Type *> getElementCountAndType(
Type *ArrayTy);
94bool DXILFlattenArraysVisitor::finish() {
95 GEPChainInfoMap.clear();
100bool DXILFlattenArraysVisitor::isMultiDimensionalArray(
Type *
T) {
106std::pair<unsigned, Type *>
107DXILFlattenArraysVisitor::getElementCountAndType(
Type *ArrayTy) {
108 unsigned TotalElements = 1;
109 Type *CurrArrayTy = ArrayTy;
111 TotalElements *= InnerArrayTy->getNumElements();
112 CurrArrayTy = InnerArrayTy->getElementType();
114 return std::make_pair(TotalElements, CurrArrayTy);
117ConstantInt *DXILFlattenArraysVisitor::genConstFlattenIndices(
120 "Indicies and dimmensions should be the same");
121 unsigned FlatIndex = 0;
122 unsigned Multiplier = 1;
124 for (
int I = Indices.
size() - 1;
I >= 0; --
I) {
125 unsigned DimSize = Dims[
I];
127 assert(CIndex &&
"This function expects all indicies to be ConstantInt");
129 Multiplier *= DimSize;
134Value *DXILFlattenArraysVisitor::genInstructionFlattenIndices(
136 if (Indices.
size() == 1)
140 unsigned Multiplier = 1;
142 for (
int I = Indices.
size() - 1;
I >= 0; --
I) {
143 unsigned DimSize = Dims[
I];
146 FlatIndex = Builder.
CreateAdd(FlatIndex, ScaledIndex);
147 Multiplier *= DimSize;
152bool DXILFlattenArraysVisitor::visitLoadInst(LoadInst &LI) {
154 for (
unsigned I = 0;
I < NumOperands; ++
I) {
157 if (CE &&
CE->getOpcode() == Instruction::GetElementPtr) {
158 GetElementPtrInst *OldGEP =
168 visitGetElementPtrInst(*OldGEP);
175bool DXILFlattenArraysVisitor::visitStoreInst(StoreInst &SI) {
176 unsigned NumOperands =
SI.getNumOperands();
177 for (
unsigned I = 0;
I < NumOperands; ++
I) {
178 Value *CurrOpperand =
SI.getOperand(
I);
180 if (CE &&
CE->getOpcode() == Instruction::GetElementPtr) {
181 GetElementPtrInst *OldGEP =
186 StoreInst *NewStore = Builder.
CreateStore(
SI.getValueOperand(), OldGEP);
188 SI.replaceAllUsesWith(NewStore);
189 SI.eraseFromParent();
190 visitGetElementPtrInst(*OldGEP);
197bool DXILFlattenArraysVisitor::visitAllocaInst(AllocaInst &AI) {
203 auto [TotalElements,
BaseType] = getElementCountAndType(ArrType);
206 AllocaInst *FlatAlloca =
214bool DXILFlattenArraysVisitor::visitGetElementPtrInst(GetElementPtrInst &
GEP) {
219 Value *PtrOperand =
GEP.getPointerOperand();
224 "Pointer operand of GEP should not be a PHI Node");
229 PtrOpGEPCE && PtrOpGEPCE->getOpcode() == Instruction::GetElementPtr) {
230 GetElementPtrInst *OldGEPI =
236 GEP.getSourceElementType(), OldGEPI, Indices,
GEP.getNoWrapFlags(),
237 GEP.getName(),
GEP.getIterator());
239 GEP.replaceAllUsesWith(NewGEPI);
240 GEP.eraseFromParent();
241 visitGetElementPtrInst(*OldGEPI);
242 visitGetElementPtrInst(*NewGEPI);
250 const DataLayout &
DL =
GEP.getDataLayout();
251 unsigned BitWidth =
DL.getIndexTypeSizeInBits(
GEP.getType());
253 [[maybe_unused]]
bool Success =
GEP.collectOffset(
265 if (!GEPChainInfoMap.contains(PtrOpGEP))
268 GEPInfo &PGEPInfo = GEPChainInfoMap[PtrOpGEP];
269 Info.RootFlattenedArrayType = PGEPInfo.RootFlattenedArrayType;
270 Info.RootPointerOperand = PGEPInfo.RootPointerOperand;
271 for (
auto &VariableOffset : PGEPInfo.VariableOffsets)
272 Info.VariableOffsets.insert(VariableOffset);
273 Info.ConstantOffset += PGEPInfo.ConstantOffset;
275 Info.RootPointerOperand = PtrOperand;
280 Type *RootTy =
GEP.getSourceElementType();
282 if (GlobalMap.contains(GlobalVar))
287 RootTy = Alloca->getAllocatedType();
288 assert(!isMultiDimensionalArray(RootTy) &&
289 "Expected root array type to be flattened");
301 bool ReplaceThisGEP =
GEP.users().empty();
304 ReplaceThisGEP =
true;
306 if (ReplaceThisGEP) {
307 unsigned BytesPerElem =
308 DL.getTypeAllocSize(
Info.RootFlattenedArrayType->getArrayElementType());
310 "Bytes per element should be a power of 2");
317 Info.ConstantOffset.udiv(BytesPerElem).getZExtValue();
318 assert(ConstantOffset < UINT32_MAX &&
319 "Constant byte offset for flat GEP index must fit within 32 bits");
321 for (
auto [VarIndex, Multiplier] :
Info.VariableOffsets) {
322 assert(Multiplier.getActiveBits() <= 32 &&
323 "The multiplier for a flat GEP index must fit within 32 bits");
324 assert(VarIndex->getType()->isIntegerTy(32) &&
325 "Expected i32-typed GEP indices");
327 if (Multiplier.getZExtValue() % BytesPerElem != 0) {
332 Builder.
getInt32(Multiplier.getZExtValue()));
337 Builder.
getInt32(Multiplier.getZExtValue() / BytesPerElem));
338 FlattenedIndex = Builder.
CreateAdd(FlattenedIndex, VI);
343 Info.RootFlattenedArrayType,
Info.RootPointerOperand,
344 {ZeroIndex, FlattenedIndex},
GEP.getNoWrapFlags(),
GEP.getName(),
350 GEP.replaceAllUsesWith(NewGEP);
351 GEP.eraseFromParent();
359 PotentiallyDeadInstrs.emplace_back(&
GEP);
363bool DXILFlattenArraysVisitor::visit(
Function &
F) {
364 bool MadeChange =
false;
365 ReversePostOrderTraversal<Function *> RPOT(&
F);
379 Elements.push_back(
Init);
382 unsigned ArrSize = ArrayTy->getNumElements();
384 for (
unsigned I = 0;
I < ArrSize; ++
I)
391 for (
unsigned I = 0;
I < ArrayConstant->getNumOperands(); ++
I) {
395 for (
unsigned I = 0;
I < DataArrayConstant->getNumElements(); ++
I) {
400 "Expected a ConstantArray or ConstantDataArray for array initializer!");
420 assert(FlattenedType->getNumElements() == FlattenedElements.
size() &&
421 "The number of collected elements should match the FlattenedType");
429 Type *OrigType =
G.getValueType();
430 if (!DXILFlattenArraysVisitor::isMultiDimensionalArray(OrigType))
435 DXILFlattenArraysVisitor::getElementCountAndType(ArrType);
442 nullptr,
G.getName() +
".1dim", &
G,
443 G.getThreadLocalMode(),
G.getAddressSpace(),
444 G.isExternallyInitialized());
452 if (
G.hasInitializer()) {
458 GlobalMap[&
G] = NewGlobal;
463 bool MadeChange =
false;
466 DXILFlattenArraysVisitor Impl(GlobalMap);
468 if (
F.isDeclaration())
470 MadeChange |= Impl.visit(
F);
472 for (
auto &[Old, New] : GlobalMap) {
473 Old->replaceAllUsesWith(New);
474 Old->eraseFromParent();
489bool DXILFlattenArraysLegacy::runOnModule(
Module &M) {
493char DXILFlattenArraysLegacy::ID = 0;
496 "DXIL Array Flattener",
false,
false)
501 return new DXILFlattenArraysLegacy();
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static Constant * transformInitializer(Constant *Init, Type *OrigType, Type *NewType, LLVMContext &Ctx)
static void collectElements(Constant *Init, SmallVectorImpl< Constant * > &Elements)
static bool flattenArrays(Module &M)
static void flattenGlobalArrays(Module &M, SmallDenseMap< GlobalVariable *, GlobalVariable * > &GlobalMap)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
Class for arbitrary precision integers.
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
void setAlignment(Align Align)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
This class represents a no-op cast from one type to another.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
This is an important base class in LLVM.
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
This instruction compares its operands according to the predicate given to the constructor.
This class represents a freeze function that returns random concrete value if an operand is either a ...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
void setUnnamedAddr(UnnamedAddr Val)
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This instruction compares its operands according to the predicate given to the constructor.
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
BasicBlock::iterator GetInsertPoint() const
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This instruction inserts a single (scalar) element into a VectorType value.
Base class for instruction visitors.
void visit(Iterator Start, Iterator End)
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
void setAlignment(Align Align)
Align getAlign() const
Return the alignment of the access that is being performed.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
A Module instance is used to store all the information related to an LLVM module.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This class represents the LLVM 'select' instruction.
This instruction constructs a fixed permutation of two input vectors.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
void setAlignment(Align Align)
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CE
Windows NT (Windows on ARM)
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
ModulePass * createDXILFlattenArraysLegacyPass()
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
A MapVector that performs no allocations if smaller than a certain size.