LLVM 24.0.0git
SPIRVPreLegalizer.cpp
Go to the documentation of this file.
1//===-- SPIRVPreLegalizer.cpp - prepare IR for legalization -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// The pass prepares IR for legalization: it assigns SPIR-V types to registers
10// and removes intrinsics which holded these types during IR translation.
11// Also it processes constants and registers them in GR to avoid duplication.
12//
13//===----------------------------------------------------------------------===//
14
15#include "SPIRV.h"
16#include "SPIRVSubtarget.h"
17#include "SPIRVUtils.h"
25#include "llvm/IR/Analysis.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/IntrinsicsSPIRV.h"
31
32#define DEBUG_TYPE "spirv-prelegalizer"
33
34using namespace llvm;
35using namespace llvm::MIPatternMatch;
36
37namespace {
38class SPIRVPreLegalizerLegacy : public MachineFunctionPass {
39public:
40 static char ID;
41 SPIRVPreLegalizerLegacy() : MachineFunctionPass(ID) {}
42 bool runOnMachineFunction(MachineFunction &MF) override;
43 void getAnalysisUsage(AnalysisUsage &AU) const override;
44};
45} // namespace
46
47void SPIRVPreLegalizerLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
48 AU.addRequired<MachineDominatorTreeWrapperPass>();
49 AU.addPreserved<GISelValueTrackingAnalysisLegacy>();
51}
52
56 MI->eraseFromParent();
57}
58
59static void
61 const SPIRVSubtarget &STI,
62 DenseMap<MachineInstr *, Type *> &TargetExtConstTypes) {
64 DenseMap<MachineInstr *, Register> RegsAlreadyAddedToDT;
65 SmallVector<MachineInstr *, 10> ToErase, ToEraseComposites;
66 for (MachineBasicBlock &MBB : MF) {
67 for (MachineInstr &MI : MBB) {
68 if (!isSpvIntrinsic(MI, Intrinsic::spv_track_constant))
69 continue;
70 ToErase.push_back(&MI);
71 Register SrcReg = MI.getOperand(2).getReg();
72 auto *Const =
74 MI.getOperand(3).getMetadata()->getOperand(0))
75 ->getValue());
76 if (auto *GV = dyn_cast<GlobalValue>(Const)) {
77 Register Reg = GR->find(GV, &MF);
78 if (!Reg.isValid()) {
79 GR->add(GV, MRI.getVRegDef(SrcReg));
80 GR->addGlobalObject(GV, &MF, SrcReg);
81 } else
82 RegsAlreadyAddedToDT[&MI] = Reg;
83 } else {
84 Register Reg = GR->find(Const, &MF);
85 if (!Reg.isValid()) {
86 if (auto *ConstVec = dyn_cast<ConstantDataVector>(Const)) {
87 auto *BuildVec = MRI.getVRegDef(SrcReg);
88 assert(BuildVec &&
89 BuildVec->getOpcode() == TargetOpcode::G_BUILD_VECTOR);
90 GR->add(Const, BuildVec);
91 for (unsigned i = 0; i < ConstVec->getNumElements(); ++i) {
92 // Ensure that OpConstantComposite reuses a constant when it's
93 // already created and available in the same machine function.
94 Constant *ElemConst = ConstVec->getElementAsConstant(i);
95 Register ElemReg = GR->find(ElemConst, &MF);
96 if (!ElemReg.isValid())
97 GR->add(ElemConst,
98 MRI.getVRegDef(BuildVec->getOperand(1 + i).getReg()));
99 else
100 BuildVec->getOperand(1 + i).setReg(ElemReg);
101 }
102 }
103 if (Const->getType()->isTargetExtTy()) {
104 // remember association so that we can restore it when assign types
105 MachineInstr *SrcMI = MRI.getVRegDef(SrcReg);
106 if (SrcMI)
107 GR->add(Const, SrcMI);
108 if (SrcMI && (SrcMI->getOpcode() == TargetOpcode::G_CONSTANT ||
109 SrcMI->getOpcode() == TargetOpcode::G_IMPLICIT_DEF))
110 TargetExtConstTypes[SrcMI] = Const->getType();
111 if (Const->isNullValue()) {
112 MachineBasicBlock &DepMBB = MF.front();
113 MachineIRBuilder MIB(DepMBB, DepMBB.getFirstNonPHI());
115 Const->getType(), MIB, SPIRV::AccessQualifier::ReadWrite,
116 true);
117 assert(SrcMI && "Expected source instruction to be valid");
118 SrcMI->setDesc(STI.getInstrInfo()->get(SPIRV::OpConstantNull));
120 GR->getSPIRVTypeID(ExtType), false));
121 }
122 }
123 } else {
124 RegsAlreadyAddedToDT[&MI] = Reg;
125 // This MI is unused and will be removed. If the MI uses
126 // const_composite, it will be unused and should be removed too.
127 assert(MI.getOperand(2).isReg() && "Reg operand is expected");
128 MachineInstr *SrcMI = MRI.getVRegDef(MI.getOperand(2).getReg());
129 if (SrcMI && isSpvIntrinsic(*SrcMI, Intrinsic::spv_const_composite))
130 ToEraseComposites.push_back(SrcMI);
131 }
132 }
133 }
134 }
135 for (MachineInstr *MI : ToErase) {
136 Register Reg = MI->getOperand(2).getReg();
137 auto It = RegsAlreadyAddedToDT.find(MI);
138 if (It != RegsAlreadyAddedToDT.end())
139 Reg = It->second;
140 auto *RC = MRI.getRegClassOrNull(MI->getOperand(0).getReg());
141 if (!MRI.getRegClassOrNull(Reg) && RC)
142 MRI.setRegClass(Reg, RC);
143 MRI.replaceRegWith(MI->getOperand(0).getReg(), Reg);
145 }
146 for (MachineInstr *MI : ToEraseComposites)
148}
149
152 MachineIRBuilder MIB) {
154 for (MachineBasicBlock &MBB : MF) {
155 for (MachineInstr &MI : MBB) {
156 if (!isSpvIntrinsic(MI, Intrinsic::spv_assign_name))
157 continue;
158 const MDNode *MD = MI.getOperand(2).getMetadata();
159 StringRef ValueName = cast<MDString>(MD->getOperand(0))->getString();
160 if (ValueName.size() > 0) {
161 MIB.setInsertPt(*MI.getParent(), MI);
162 buildOpName(MI.getOperand(1).getReg(), ValueName, MIB);
163 }
164 ToErase.push_back(&MI);
165 }
166 for (MachineInstr *MI : ToErase)
168 ToErase.clear();
169 }
170}
171
174 for (MachineRegisterInfo::use_instr_iterator I = MRI->use_instr_begin(Reg),
175 IE = MRI->use_instr_end();
176 I != IE; ++I) {
177 MachineInstr *UseMI = &*I;
178 if ((isSpvIntrinsic(*UseMI, Intrinsic::spv_assign_ptr_type) ||
179 isSpvIntrinsic(*UseMI, Intrinsic::spv_assign_type)) &&
180 UseMI->getOperand(1).getReg() == Reg)
181 return UseMI;
182 }
183 return nullptr;
184}
185
187 Register ResVReg, Register OpReg) {
188 SPIRVTypeInst ResType = GR->getSPIRVTypeForVReg(ResVReg);
189 SPIRVTypeInst OpType = GR->getSPIRVTypeForVReg(OpReg);
190 assert(ResType && OpType && "Operand types are expected");
191 if (!GR->isBitcastCompatible(ResType, OpType))
192 report_fatal_error("incompatible result and operand types in a bitcast");
194 if (!MRI->getRegClassOrNull(ResVReg))
195 MRI->setRegClass(ResVReg, GR->getRegClass(ResType));
196 if (ResType == OpType)
197 MIB.buildInstr(TargetOpcode::COPY).addDef(ResVReg).addUse(OpReg);
198 else
199 MIB.buildInstr(SPIRV::OpBitcast)
200 .addDef(ResVReg)
201 .addUse(GR->getSPIRVTypeID(ResType))
202 .addUse(OpReg);
203}
204
205// We lower G_BITCAST to OpBitcast here to avoid a MachineVerifier error.
206// The verifier checks if the source and destination LLTs of a G_BITCAST are
207// different, but this check is too strict for SPIR-V's typed pointers, which
208// may have the same LLT but different SPIRV type (e.g. pointers to different
209// pointee types). By lowering to OpBitcast here, we bypass the verifier's
210// check. See discussion in https://github.com/llvm/llvm-project/pull/110270
211// for more context.
212//
213// We also handle the llvm.spv.bitcast intrinsic here. If the source and
214// destination SPIR-V types are the same, we lower it to a COPY to enable
215// further optimizations like copy propagation.
217 MachineIRBuilder MIB) {
219 for (MachineBasicBlock &MBB : MF) {
220 for (MachineInstr &MI : MBB) {
221 if (isSpvIntrinsic(MI, Intrinsic::spv_bitcast)) {
222 Register DstReg = MI.getOperand(0).getReg();
223 Register SrcReg = MI.getOperand(2).getReg();
224 SPIRVTypeInst DstType = GR->getSPIRVTypeForVReg(DstReg);
225 assert(
226 DstType &&
227 "Expected destination SPIR-V type to have been assigned already.");
228 SPIRVTypeInst SrcType = GR->getSPIRVTypeForVReg(SrcReg);
229 assert(SrcType &&
230 "Expected source SPIR-V type to have been assigned already.");
231 if (DstType == SrcType) {
232 MIB.setInsertPt(*MI.getParent(), MI);
233 MIB.buildCopy(DstReg, SrcReg);
234 ToErase.push_back(&MI);
235 continue;
236 }
237 }
238
239 if (MI.getOpcode() != TargetOpcode::G_BITCAST)
240 continue;
241
242 MIB.setInsertPt(*MI.getParent(), MI);
243 buildOpBitcast(GR, MIB, MI.getOperand(0).getReg(),
244 MI.getOperand(1).getReg());
245 ToErase.push_back(&MI);
246 }
247 }
248 for (MachineInstr *MI : ToErase)
250}
251
253 MachineIRBuilder MIB) {
254 // Get access to information about available extensions
255 const SPIRVSubtarget *ST =
256 static_cast<const SPIRVSubtarget *>(&MIB.getMF().getSubtarget());
258 for (MachineBasicBlock &MBB : MF) {
259 for (MachineInstr &MI : MBB) {
260 if (!isSpvIntrinsic(MI, Intrinsic::spv_ptrcast))
261 continue;
262 assert(MI.getOperand(2).isReg());
263 MIB.setInsertPt(*MI.getParent(), MI);
264 ToErase.push_back(&MI);
265 Register Def = MI.getOperand(0).getReg();
266 Register Source = MI.getOperand(2).getReg();
267 Type *ElemTy = getMDOperandAsType(MI.getOperand(3).getMetadata(), 0);
268 auto SC =
270 ST->canUseExtension(
271 SPIRV::Extension::SPV_INTEL_function_pointers)
272 ? SPIRV::StorageClass::CodeSectionINTEL
273 : addressSpaceToStorageClass(MI.getOperand(4).getImm(), *ST);
274 SPIRVTypeInst AssignedPtrType =
276
277 // If the ptrcast would be redundant, replace all uses with the source
278 // register.
280 // For untyped pointers the SPIR-V pointer type does not encode the
281 // pointee, so two pointers with different element types share the same
282 // pointer type. The element type still matters because it selects the
283 // Base Type operand of OpUntyped*AccessChainKHR. Treat the cast as
284 // redundant only when the source already carries the same element type.
285 // Otherwise keep a distinct register so the element type is preserved.
286 bool Redundant =
287 AssignedPtrType->getOpcode() == SPIRV::OpTypeUntypedPointerKHR
288 ? GR->getUntypedPtrElementType(Source) ==
290 SPIRV::AccessQualifier::ReadWrite,
291 /*EmitIR=*/true)
292 : GR->getSPIRVTypeForVReg(Source) == AssignedPtrType;
293 if (Redundant) {
294 // Erase Def's assign type instruction if we are going to replace Def.
295 if (MachineInstr *AssignMI = findAssignTypeInstr(Def, MRI))
296 ToErase.push_back(AssignMI);
297 MRI->replaceRegWith(Def, Source);
298 } else {
299 if (!GR->getSPIRVTypeForVReg(Def, &MF))
300 GR->assignSPIRVTypeToVReg(AssignedPtrType, Def, MF);
301 MIB.buildBitcast(Def, Source);
302 }
303 }
304 }
305 for (MachineInstr *MI : ToErase)
307}
308
309// Translating GV, IRTranslator sometimes generates following IR:
310// %1 = G_GLOBAL_VALUE
311// %2 = COPY %1
312// %3 = G_ADDRSPACE_CAST %2
313//
314// or
315//
316// %1 = G_ZEXT %2
317// G_MEMCPY ... %2 ...
318//
319// New registers have no SPIRV type and no register class info.
320//
321// Set SPIRV type for GV, propagate it from GV to other instructions,
322// also set register classes.
326 MachineIRBuilder &MIB) {
327 SPIRVTypeInst SpvType = nullptr;
328 assert(MI && "Machine instr is expected");
329 if (MI->getOperand(0).isReg()) {
330 Register Reg = MI->getOperand(0).getReg();
331 SpvType = GR->getSPIRVTypeForVReg(Reg);
332 if (!SpvType) {
333 MIB.setInsertPt(*MI->getParent(), MI);
334 switch (MI->getOpcode()) {
335 case TargetOpcode::G_FCONSTANT:
336 case TargetOpcode::G_CONSTANT: {
337 Type *Ty = MI->getOperand(1).getCImm()->getType();
338 SpvType = GR->getOrCreateSPIRVType(
339 Ty, MIB, SPIRV::AccessQualifier::ReadWrite, true);
340 break;
341 }
342 case TargetOpcode::G_GLOBAL_VALUE: {
343 const GlobalValue *Global = MI->getOperand(1).getGlobal();
345 unsigned AddrSpace = Global->getType()->getAddressSpace();
346 // Function pointers use CodeSectionINTEL storage class in SPIR-V when
347 // the SPV_INTEL_function_pointers extension is enabled.
348 const SPIRVSubtarget &ST = MIB.getMF().getSubtarget<SPIRVSubtarget>();
349 if (isa<Function>(Global) &&
350 ST.canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
351 AddrSpace =
352 storageClassToAddressSpace(SPIRV::StorageClass::CodeSectionINTEL);
353 auto *Ty = TypedPointerType::get(ElementTy, AddrSpace);
354 SpvType = GR->getOrCreateSPIRVType(
355 Ty, MIB, SPIRV::AccessQualifier::ReadWrite, true);
356 break;
357 }
358 case TargetOpcode::G_ANYEXT:
359 case TargetOpcode::G_SEXT:
360 case TargetOpcode::G_ZEXT: {
361 if (MI->getOperand(1).isReg()) {
362 if (MachineInstr *DefInstr =
363 MRI.getVRegDef(MI->getOperand(1).getReg())) {
364 SPIRVTypeInst Def = propagateSPIRVType(DefInstr, GR, MRI, MIB);
365 if (Def && !GR->isAggregateType(Def)) {
366 unsigned CurrentBW = GR->getScalarOrVectorBitWidth(Def);
367 unsigned ExpectedBW =
368 std::max(MRI.getType(Reg).getScalarSizeInBits(), CurrentBW);
369 unsigned NumElements = GR->getScalarOrVectorComponentCount(Def);
370 SpvType = GR->getOrCreateSPIRVIntegerType(ExpectedBW, MIB);
371 if (NumElements > 1)
372 SpvType = GR->getOrCreateSPIRVVectorType(SpvType, NumElements,
373 MIB, true);
374 }
375 }
376 }
377 break;
378 }
379 case TargetOpcode::G_PTRTOINT:
380 SpvType = GR->getOrCreateSPIRVIntegerType(
381 MRI.getType(Reg).getScalarSizeInBits(), MIB);
382 break;
383 case TargetOpcode::G_TRUNC:
384 case TargetOpcode::G_ADDRSPACE_CAST:
385 case TargetOpcode::G_PTR_ADD:
386 case TargetOpcode::COPY: {
387 MachineOperand &Op = MI->getOperand(1);
388 MachineInstr *Def = Op.isReg() ? MRI.getVRegDef(Op.getReg()) : nullptr;
389 if (Def)
390 SpvType = propagateSPIRVType(Def, GR, MRI, MIB);
391 break;
392 }
393 default:
394 break;
395 }
396 if (SpvType) {
397 // check if the address space needs correction
398 LLT RegType = MRI.getType(Reg);
399 if (SpvType.isPointer() && RegType.isPointer() &&
401 RegType.getAddressSpace()) {
402 // Don't correct CodeSectionINTEL back to Function for function
403 // pointer G_GLOBAL_VALUE - the LLVM register has address space 0
404 // but the SPIR-V type was intentionally set to CodeSectionINTEL.
405 bool SkipCorrection =
406 MI->getOpcode() == TargetOpcode::G_GLOBAL_VALUE &&
407 GR->getPointerStorageClass(SpvType) ==
408 SPIRV::StorageClass::CodeSectionINTEL;
409 if (!SkipCorrection) {
410 const SPIRVSubtarget &ST =
411 MI->getParent()->getParent()->getSubtarget<SPIRVSubtarget>();
412 auto TSC =
413 addressSpaceToStorageClass(RegType.getAddressSpace(), ST);
414 SpvType = GR->changePointerStorageClass(SpvType, TSC, *MI);
415 }
416 }
417 GR->assignSPIRVTypeToVReg(SpvType, Reg, MIB.getMF());
418 }
419 if (!MRI.getRegClassOrNull(Reg))
420 MRI.setRegClass(Reg, SpvType ? GR->getRegClass(SpvType)
421 : &SPIRV::iIDRegClass);
422 }
423 }
424 return SpvType;
425}
426
427// To support current approach and limitations wrt. bit width here we widen a
428// scalar register with a bit width greater than 1 to valid sizes and cap it to
429// 128 width.
430static unsigned widenBitWidthToNextPow2(unsigned BitWidth) {
431 if (BitWidth == 1)
432 return 1; // No need to widen 1-bit values
433 return std::min(std::max<unsigned>(PowerOf2Ceil(BitWidth), 8u), 128u);
434}
435
436static std::optional<unsigned>
438 LLT Ty = MRI.getType(Reg);
439 if (!Ty.isScalar())
440 return std::nullopt;
441 unsigned W = Ty.getScalarSizeInBits();
442 // <= and not == because widenBitWidthToNextPow2 caps at 128.
443 if (widenBitWidthToNextPow2(W) <= W)
444 return std::nullopt;
445 return W;
446}
447
449 LLT RegType = MRI.getType(Reg);
450 if (!RegType.isScalar())
451 return;
452 unsigned CurrentWidth = RegType.getScalarSizeInBits();
453 unsigned NewWidth = widenBitWidthToNextPow2(CurrentWidth);
454 if (NewWidth != CurrentWidth)
455 MRI.setType(Reg, LLT::scalar(NewWidth));
456}
457
458static void widenCImmType(MachineOperand &MOP) {
459 const ConstantInt *CImmVal = MOP.getCImm();
460 unsigned CurrentWidth = CImmVal->getBitWidth();
461 unsigned NewWidth = widenBitWidthToNextPow2(CurrentWidth);
462 if (NewWidth != CurrentWidth) {
463 // Replace the immediate value with the widened version
464 MOP.setCImm(ConstantInt::get(CImmVal->getType()->getContext(),
465 CImmVal->getValue().zextOrTrunc(NewWidth)));
466 }
467}
468
470 MachineBasicBlock &MBB = *Def->getParent();
472 Def->getNextNode() ? Def->getNextNode()->getIterator() : MBB.end();
473 // Skip all the PHI and debug instructions.
474 while (DefIt != MBB.end() &&
475 (DefIt->isPHI() || DefIt->isDebugOrPseudoInstr()))
476 DefIt = std::next(DefIt);
477 MIB.setInsertPt(MBB, DefIt);
478}
479
480namespace llvm {
484 assert((Ty || SpvType) && "Either LLVM or SPIRV type is expected.");
485 MachineInstr *Def = MRI.getVRegDef(Reg);
486 setInsertPtAfterDef(MIB, Def);
487 if (!SpvType)
488 SpvType = GR->getOrCreateSPIRVType(Ty, MIB,
489 SPIRV::AccessQualifier::ReadWrite, true);
490 if (!MRI.getRegClassOrNull(Reg))
491 MRI.setRegClass(Reg, GR->getRegClass(SpvType));
492 if (!MRI.getType(Reg).isValid())
493 MRI.setType(Reg, GR->getRegType(SpvType));
494 GR->assignSPIRVTypeToVReg(SpvType, Reg, MIB.getMF());
495}
496
499 SPIRVTypeInst KnownResType) {
500 MIB.setInsertPt(*MI.getParent(), MI.getIterator());
501 for (auto &Op : MI.operands()) {
502 if (!Op.isReg() || Op.isDef())
503 continue;
504 Register OpReg = Op.getReg();
505 SPIRVTypeInst SpvType = GR->getSPIRVTypeForVReg(OpReg);
506 if (!SpvType && KnownResType) {
507 SpvType = KnownResType;
508 GR->assignSPIRVTypeToVReg(KnownResType, OpReg, *MI.getMF());
509 }
510 assert(SpvType);
511 if (!MRI.getRegClassOrNull(OpReg))
512 MRI.setRegClass(OpReg, GR->getRegClass(SpvType));
513 if (!MRI.getType(OpReg).isValid())
514 MRI.setType(OpReg, GR->getRegType(SpvType));
515 }
516}
517} // namespace llvm
518
519// Sign-sensitive integer ops: their result depends on the value of the input
520// sign bit at position (width-1). On sub-pow2 widths the general widening
521// loop is a pure LLT relabel, which leaves the sign bit at the *original*
522// position instead of the widened MSB. These ops therefore need an explicit
523// G_SEXT_INREG on each value operand to move the sign bit up.
524//
525// Signed-vs-unsigned G_ICMP is distinguished by its predicate operand.
526//
527// TODO: follow-up PRs will add the remaining sign-sensitive opcodes
528// (e.g. G_SADDSAT/G_SSUBSAT, signed overflow ops).
529static bool isSignSensitiveOp(const MachineInstr &MI) {
530 switch (MI.getOpcode()) {
531 case TargetOpcode::G_ASHR:
532 case TargetOpcode::G_SDIV:
533 case TargetOpcode::G_SREM:
534 case TargetOpcode::G_SITOFP:
535 case TargetOpcode::G_SMIN:
536 case TargetOpcode::G_SMAX:
537 return true;
538 case TargetOpcode::G_ICMP:
539 return CmpInst::isSigned(
540 static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate()));
541 default:
542 return false;
543 }
544}
545
547 // Width before widening of each sign-sensitive value-operand vreg (one entry
548 // per vreg).
550 // Sign-sensitive ops whose value operand(s) need replacing, ordered for
551 // reproducible vreg numbering.
553 // Keyed by instruction, not vreg: G_TRUNC handling can replace the source.
555};
556
557// G_CTTZ_ZERO_POISON is absent because its low bits are known non-zero, G_CTLS
558// because the backend does not select it.
559static bool isWidthSensitiveBitCountOp(unsigned Opcode) {
560 switch (Opcode) {
561 case TargetOpcode::G_CTLZ:
562 case TargetOpcode::G_CTLZ_ZERO_POISON:
563 case TargetOpcode::G_CTTZ:
564 case TargetOpcode::G_CTPOP:
565 return true;
566 default:
567 return false;
568 }
569}
570
571// Collect ops whose semantics depend on the operand width along with their
572// pre-widening widths, before later passes retype those vregs to pow2 LLTs
573// and the original width is no longer recoverable.
574static NarrowWideningInfo
577 auto RecordIfNarrow = [&](Register Reg) {
578 std::optional<unsigned> W = getNarrowScalarWidth(Reg, MRI);
579 if (!W)
580 return false;
581 Info.OrigWidth.try_emplace(Reg, *W);
582 return true;
583 };
584 for (MachineBasicBlock &MBB : MF) {
585 for (MachineInstr &MI : MBB) {
586 if (isWidthSensitiveBitCountOp(MI.getOpcode())) {
587 if (std::optional<unsigned> W =
588 getNarrowScalarWidth(MI.getOperand(1).getReg(), MRI))
589 Info.BitCountWorklist.emplace_back(&MI, *W);
590 continue;
591 }
592 if (!isSignSensitiveOp(MI))
593 continue;
594 bool NeedsRewrite = false;
595 for (const MachineOperand &MO : MI.all_uses())
596 NeedsRewrite = RecordIfNarrow(MO.getReg()) || NeedsRewrite;
597 if (NeedsRewrite) {
598 Info.SignSensitiveWorklist.push_back(&MI);
599 // Record the result too so it gets masked.
600 RecordIfNarrow(MI.getOperand(0).getReg());
601 }
602 }
603 }
604 return Info;
605}
606
607// For every recorded sign-sensitive op, insert G_SEXT_INREG on each value
608// operand whose original width was narrower than the widened pow2 width and
609// retype the operand's vreg LLT in place to the widened width.
610//
611// Info must have been populated by recordNarrowOperandWidths before
612// other passes retyped the vregs; otherwise the narrow widths needed here
613// are lost.
614//
615// TODO: handle vector operands.
617 MachineIRBuilder &MIB,
619 const NarrowWideningInfo &Info) {
620 // Emit G_SEXT_INREG from Reg's recorded narrow width; retypes Reg to the
621 // widened width and returns the sign-extended vreg.
622 auto SignExtendReg = [&](Register Reg, unsigned OldW,
624 unsigned NewW = widenBitWidthToNextPow2(OldW);
625 LLT NewLLT = LLT::scalar(NewW);
626 MIB.setInsertPt(*MI.getParent(), MI.getIterator());
627 SPIRVTypeInst SpvTy = GR->getOrCreateSPIRVIntegerType(NewW, MIB);
628 Register SExted = MRI.createGenericVirtualRegister(NewLLT);
629 GR->assignSPIRVTypeToVReg(SpvTy, SExted, MF);
630 MRI.setRegClass(SExted, GR->getRegClass(SpvTy));
631 MRI.setType(Reg, NewLLT);
632 MIB.buildSExtInReg(SExted, Reg, OldW);
633 return SExted;
634 };
635
636 // The wide op yields a sign-extended value, mask it back to OldW bits because
637 // later users assume the upper bits are zero.
638 auto MaskResult = [&](MachineInstr &MI, unsigned OldW) {
639 Register DstReg = MI.getOperand(0).getReg();
640 widenScalarType(DstReg, MRI);
642 SPIRVTypeInst SpvTy =
644 Register Result = createVirtualRegister(SpvTy, GR, MIB);
645 MI.getOperand(0).setReg(Result);
646 setInsertPtAfterDef(MIB, &MI);
647 MIB.buildZExtInReg(DstReg, Result, OldW);
648 };
649
650 // TODO: when the same narrow vreg feeds multiple sign-sensitive ops (e.g.
651 // sdiv %x, %y and srem %x, %y), emit one shared G_SEXT_INREG instead of one
652 // per use.
653 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
654 for (MachineInstr *MI : Info.SignSensitiveWorklist) {
655 for (const MachineOperand &MO : MI->all_uses()) {
656 Register Reg = MO.getReg();
657 auto It = Info.OrigWidth.find(Reg);
658 if (It == Info.OrigWidth.end())
659 continue;
660 // substituteRegister fills every slot holding Reg at once: SignExtendReg
661 // retypes Reg in place, so a second sext would read the widened width.
662 MI->substituteRegister(Reg, SignExtendReg(Reg, It->second, *MI),
663 /*SubIdx=*/0, TRI);
664 }
665 Register Dst = MI->getOperand(0).getReg();
666 if (auto It = Info.OrigWidth.find(Dst); It != Info.OrigWidth.end())
667 MaskResult(*MI, It->second);
668 }
669}
670
671// LegalizerHelper::widenScalar has the same cases but cannot be reached: the
672// relabel retypes every narrow scalar to a pow2 LLT, so no illegal narrow type
673// ever reaches the legalizer.
674//
675// TODO: handle vector operands.
678 const NarrowWideningInfo &Info) {
679 for (auto [MI, OldWidth] : Info.BitCountWorklist) {
680 Register SrcReg = MI->getOperand(1).getReg();
681 unsigned NewWidth = widenBitWidthToNextPow2(OldWidth);
682 LLT NewTy = LLT::scalar(NewWidth);
683 widenScalarType(SrcReg, MRI);
685 SPIRVTypeInst SpvTy = GR->getOrCreateSPIRVIntegerType(NewWidth, MIB);
686
687 // The G_TRUNC lowering masks its result to the narrow width, so a source
688 // coming from it needs no second mask.
689 APInt Cst;
690 bool HighBitsAlreadyZero =
691 mi_match(SrcReg, MRI, m_GAnd(m_Reg(), m_ICst(Cst))) &&
692 Cst.isSubsetOf(APInt::getLowBitsSet(Cst.getBitWidth(), OldWidth));
693 auto ClearHighBits = [&](unsigned Width) -> Register {
694 if (HighBitsAlreadyZero)
695 return SrcReg;
696 Register Masked = createVirtualRegister(SpvTy, GR, MIB);
697 MIB.buildZExtInReg(Masked, SrcReg, Width);
698 return Masked;
699 };
700
702 switch (MI->getOpcode()) {
703 case TargetOpcode::G_CTLZ_ZERO_POISON: {
704 // Shifting up to the widened MSB moves the poison out too, so no
705 // adjustment.
706 Input = createVirtualRegister(SpvTy, GR, MIB);
707 auto Diff = MIB.buildConstant(NewTy, NewWidth - OldWidth);
708 MIB.buildShl(Input, SrcReg, Diff);
709 break;
710 }
711 case TargetOpcode::G_CTTZ: {
712 // Keeps an all-zero narrow value counting exactly OldWidth zeros.
713 Input = createVirtualRegister(SpvTy, GR, MIB);
714 auto TopBit =
715 MIB.buildConstant(NewTy, APInt::getOneBitSet(NewWidth, OldWidth));
716 MIB.buildOr(Input, SrcReg, TopBit);
717 break;
718 }
719 case TargetOpcode::G_CTPOP:
720 Input = ClearHighBits(OldWidth);
721 break;
722 case TargetOpcode::G_CTLZ: {
723 // Clearing the extra bits adds leading zeros the count has to drop.
724 Input = ClearHighBits(OldWidth);
725 Register DstReg = MI->getOperand(0).getReg();
726 widenScalarType(DstReg, MRI);
727 Register Count = createVirtualRegister(SpvTy, GR, MIB);
728 MI->getOperand(0).setReg(Count);
730 auto Diff = MIB.buildConstant(NewTy, NewWidth - OldWidth);
731 MIB.buildSub(DstReg, Count, Diff);
732 break;
733 }
734 default:
735 llvm_unreachable("unexpected width-sensitive bit-count opcode");
736 }
737 MI->getOperand(1).setReg(Input);
738 }
739}
740
741static void
744 DenseMap<MachineInstr *, Type *> &TargetExtConstTypes,
745 const MachineDominatorTree &MDT) {
746 // Get access to information about available extensions
747 const SPIRVSubtarget *ST =
748 static_cast<const SPIRVSubtarget *>(&MIB.getMF().getSubtarget());
749
752 DenseMap<MachineInstr *, Register> RegsAlreadyAddedToDT;
753
754 bool IsExtendedInts =
755 ST->canUseExtension(
756 SPIRV::Extension::SPV_ALTERA_arbitrary_precision_integers) ||
757 ST->canUseExtension(SPIRV::Extension::SPV_KHR_bit_instructions) ||
758 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_int4);
759
760 if (!IsExtendedInts) {
761 // Without arbitrary precision integer extensions, SPIR-V only supports
762 // integer widths of 8, 16, 32, 64. Non-standard widths (e.g., i24, i40)
763 // must be widened to the next power of two.
764 //
765 // Record the original widths of width-sensitive operands before either
766 // the G_TRUNC handling or the general widening loop retypes vregs, then
767 // rewrite those ops after G_TRUNC processing using the recorded widths.
769
770 // G_TRUNC requires special handling because its semantics depend on the
771 // original destination width. For example:
772 // %dst:s24 = G_TRUNC %src:s64
773 // After widening s24 to s32, we cannot simply do:
774 // %dst:s32 = G_TRUNC %src:s64
775 // because this would keep 32 bits instead of 24. Instead, we insert a
776 // G_AND to mask the value to the original width:
777 // %mask:s64 = G_CONSTANT 0xFFFFFF ; 24-bit mask
778 // %masked:s64 = G_AND %src:s64, %mask
779 // %dst:s32 = G_TRUNC %masked:s64
780 // If src and dst widen to the same size, G_TRUNC is replaced entirely:
781 // %mask:s64 = G_CONSTANT 0xFFFFFFFFFF ; 40-bit mask
782 // %dst:s64 = G_AND %src:s64, %mask
783 SmallVector<MachineInstr *, 8> TruncToRemove;
784 for (MachineBasicBlock &MBB : MF) {
785 for (MachineInstr &MI : MBB) {
786 unsigned MIOp = MI.getOpcode();
787 if (MIOp != TargetOpcode::G_TRUNC)
788 continue;
789 assert(MI.getNumOperands() == 2);
790 assert(MI.getOperand(0).isReg());
791 assert(MI.getOperand(1).isReg());
792
793 Register DstReg = MI.getOperand(0).getReg();
794 Register SrcReg = MI.getOperand(1).getReg();
795
796 LLT DstTy = MRI.getType(DstReg);
797 LLT SrcTy = MRI.getType(SrcReg);
798 assert((DstTy.isScalar() || DstTy.isVector()) &&
799 (SrcTy.isScalar() || SrcTy.isVector()) &&
800 "Expected scalar or vector G_TRUNC types");
801 assert(DstTy.isVector() == SrcTy.isVector() &&
802 "Expected matching scalar/vector G_TRUNC types");
803 assert((!DstTy.isVector() ||
804 DstTy.getElementCount() == SrcTy.getElementCount()) &&
805 "Expected equal vector element counts");
806
807 unsigned OriginalDstWidth = DstTy.getScalarSizeInBits();
808 unsigned OriginalSrcWidth = SrcTy.getScalarSizeInBits();
809
810 unsigned NewDstWidth = widenBitWidthToNextPow2(OriginalDstWidth);
811 unsigned NewSrcWidth = widenBitWidthToNextPow2(OriginalSrcWidth);
812 LLT NewDstTy = DstTy.changeElementSize(NewDstWidth);
813 LLT NewSrcTy = SrcTy.changeElementSize(NewSrcWidth);
814
815 // No Dst width change means no truncation semantics change, but the
816 // source still needs a legal type.
817 if (OriginalDstWidth == NewDstWidth) {
818 MRI.setType(SrcReg, NewSrcTy);
819 continue;
820 }
821
822 MRI.setType(SrcReg, NewSrcTy);
823 MRI.setType(DstReg, NewDstTy);
824
825 MIB.setInsertPt(MBB, MI.getIterator());
826 APInt Mask = APInt::getLowBitsSet(NewSrcWidth, OriginalDstWidth);
827 MachineInstrBuilder MaskReg =
828 DstTy.isVector()
830 NewSrcTy,
832 : MIB.buildConstant(NewSrcTy, Mask);
833 Register MaskedReg = MRI.createGenericVirtualRegister(NewSrcTy);
834 MIB.buildAnd(MaskedReg, SrcReg, MaskReg);
835
836 if (NewSrcWidth == NewDstWidth) {
837 // Rekey OrigWidth from DstReg to MaskedReg so widenSignSensitiveOps
838 // still sees the narrow original width after replaceRegWith.
839 if (auto It = WideningInfo.OrigWidth.find(DstReg);
840 It != WideningInfo.OrigWidth.end()) {
841 unsigned W = It->second;
842 WideningInfo.OrigWidth.erase(It);
843 WideningInfo.OrigWidth.try_emplace(MaskedReg, W);
844 }
845 MRI.replaceRegWith(DstReg, MaskedReg);
846 TruncToRemove.push_back(&MI);
847 } else {
848 MI.getOperand(1).setReg(MaskedReg);
849 }
850 }
851 }
852 for (MachineInstr *MI : TruncToRemove)
853 MI->eraseFromParent();
854
855 widenSignSensitiveOps(MF, GR, MIB, MRI, WideningInfo);
856 widenBitCountOps(GR, MIB, MRI, WideningInfo);
857 }
858
859 for (MachineBasicBlock *MBB : post_order(&MF)) {
860 if (MBB->empty())
861 continue;
862
863 bool ReachedBegin = false;
864 for (auto MII = std::prev(MBB->end()), Begin = MBB->begin();
865 !ReachedBegin;) {
866 MachineInstr &MI = *MII;
867 unsigned MIOp = MI.getOpcode();
868
869 if (!IsExtendedInts) {
870 // validate bit width of scalar registers and constant immediates
871 for (auto &MOP : MI.operands()) {
872 if (MOP.isReg())
873 widenScalarType(MOP.getReg(), MRI);
874 else if (MOP.isCImm())
875 widenCImmType(MOP);
876 }
877 }
878
879 if (isSpvIntrinsic(MI, Intrinsic::spv_assign_ptr_type)) {
880 Register Reg = MI.getOperand(1).getReg();
881 MIB.setInsertPt(*MI.getParent(), MI.getIterator());
882 Type *ElementTy = getMDOperandAsType(MI.getOperand(2).getMetadata(), 0);
883 auto SC = addressSpaceToStorageClass(MI.getOperand(3).getImm(), *ST);
884 if (SC == SPIRV::StorageClass::Function &&
885 isa<FunctionType>(ElementTy) &&
886 ST->canUseExtension(SPIRV::Extension::SPV_INTEL_function_pointers))
887 SC = SPIRV::StorageClass::CodeSectionINTEL;
888 SPIRVTypeInst AssignedPtrType =
889 GR->getOrCreateSPIRVPointerType(ElementTy, MI, SC);
890
891 // For untyped pointers, store the element type for later use.
892 if (ST->canUseExtension(SPIRV::Extension::SPV_KHR_untyped_pointers) &&
893 !ST->isShader()) {
894 SPIRVTypeInst ElemSpvType = GR->getOrCreateSPIRVType(
895 ElementTy, MIB, SPIRV::AccessQualifier::ReadWrite,
896 /*EmitIR=*/true);
897 GR->setUntypedPtrElementType(Reg, ElemSpvType);
898 }
899
900 // The intrinsic also carries vector-of-pointer values produced by
901 // scalarized vector GEPs; wrap the pointer in OpTypeVector to match
902 // the vreg's LLT.
903 LLT RegTy = MRI.getType(Reg);
904 if (RegTy.isValid() && RegTy.isVector())
905 AssignedPtrType = GR->getOrCreateSPIRVVectorType(
906 AssignedPtrType, RegTy.getNumElements(), MIB,
907 /*EmitIR=*/true);
908 MachineInstr *Def = MRI.getVRegDef(Reg);
909 assert(Def && "Expecting an instruction that defines the register");
910 // G_GLOBAL_VALUE already has type info.
911 if (Def->getOpcode() != TargetOpcode::G_GLOBAL_VALUE)
912 updateRegType(Reg, nullptr, AssignedPtrType, GR, MIB,
913 MF.getRegInfo());
914 ToErase.push_back(&MI);
915 } else if (isSpvIntrinsic(MI, Intrinsic::spv_assign_type)) {
916 Register Reg = MI.getOperand(1).getReg();
917 Type *Ty = getMDOperandAsType(MI.getOperand(2).getMetadata(), 0);
918 MachineInstr *Def = MRI.getVRegDef(Reg);
919 assert(Def && "Expecting an instruction that defines the register");
920 // G_GLOBAL_VALUE already has type info.
921 if (Def->getOpcode() != TargetOpcode::G_GLOBAL_VALUE)
922 updateRegType(Reg, Ty, nullptr, GR, MIB, MF.getRegInfo());
923 if (Def->getOpcode() == TargetOpcode::COPY && isVector1(Ty))
925 Ty, nullptr, GR, MIB, MF.getRegInfo());
926 ToErase.push_back(&MI);
927 } else if (MIOp == TargetOpcode::FAKE_USE && MI.getNumOperands() > 0) {
928 MachineInstr *MdMI = MI.getPrevNode();
929 if (MdMI && isSpvIntrinsic(*MdMI, Intrinsic::spv_value_md)) {
930 // It's an internal service info from before IRTranslator passes.
931 MachineInstr *Def = getVRegDef(MRI, MI.getOperand(0).getReg());
932 for (unsigned I = 1, E = MI.getNumOperands(); I != E && Def; ++I)
933 if (getVRegDef(MRI, MI.getOperand(I).getReg()) != Def)
934 Def = nullptr;
935 if (Def) {
936 const MDNode *MD = MdMI->getOperand(1).getMetadata();
938 cast<MDString>(MD->getOperand(1))->getString();
939 const MDNode *TypeMD = cast<MDNode>(MD->getOperand(0));
940 Type *ValueTy = getMDOperandAsType(TypeMD, 0);
941 GR->addValueAttrs(Def, std::make_pair(ValueTy, ValueName.str()));
942 // Type results that nothing extracts.
943 auto *STy = dyn_cast<StructType>(ValueTy);
944 if (STy && STy->getNumElements() == Def->getNumDefs())
945 for (auto [Op, ElemTy] : zip(Def->defs(), STy->elements()))
946 if (!GR->getSPIRVTypeForVReg(Op.getReg()))
947 updateRegType(Op.getReg(), ElemTy, nullptr, GR, MIB, MRI);
948 }
949 ToErase.push_back(MdMI);
950 }
951 ToErase.push_back(&MI);
952 } else if (MIOp == TargetOpcode::G_CONSTANT ||
953 MIOp == TargetOpcode::G_FCONSTANT ||
954 MIOp == TargetOpcode::G_BUILD_VECTOR) {
955 // %rc = G_CONSTANT ty Val
956 // Ensure %rc has a valid SPIR-V type assigned in the Global Registry.
957 Register Reg = MI.getOperand(0).getReg();
958 bool NeedAssignType = !GR->getSPIRVTypeForVReg(Reg);
959 Type *Ty = nullptr;
960 if (MIOp == TargetOpcode::G_CONSTANT) {
961 auto TargetExtIt = TargetExtConstTypes.find(&MI);
962 Ty = TargetExtIt == TargetExtConstTypes.end()
963 ? MI.getOperand(1).getCImm()->getType()
964 : TargetExtIt->second;
965 const ConstantInt *OpCI = MI.getOperand(1).getCImm();
966 // TODO: we may wish to analyze here if OpCI is zero and LLT RegType =
967 // MRI.getType(Reg); RegType.isPointer() is true, so that we observe
968 // at this point not i64/i32 constant but null pointer in the
969 // corresponding address space of RegType.getAddressSpace(). This may
970 // help to successfully validate the case when a OpConstantComposite's
971 // constituent has type that does not match Result Type of
972 // OpConstantComposite (see, for example,
973 // pointers/PtrCast-null-in-OpSpecConstantOp.ll).
974 Register PrimaryReg = GR->find(OpCI, &MF);
975 if (!PrimaryReg.isValid()) {
976 GR->add(OpCI, &MI);
977 } else if (PrimaryReg != Reg &&
978 MRI.getType(Reg) == MRI.getType(PrimaryReg)) {
979 auto *RCReg = MRI.getRegClassOrNull(Reg);
980 auto *RCPrimary = MRI.getRegClassOrNull(PrimaryReg);
981 // Folded constants can live in non-entry blocks.
982 if ((!RCReg || RCPrimary == RCReg) &&
983 MDT.dominates(MRI.getVRegDef(PrimaryReg), &MI)) {
984 RegsAlreadyAddedToDT[&MI] = PrimaryReg;
985 ToErase.push_back(&MI);
986 NeedAssignType = false;
987 }
988 }
989 } else if (MIOp == TargetOpcode::G_FCONSTANT) {
990 Ty = MI.getOperand(1).getFPImm()->getType();
991 } else {
992 assert(MIOp == TargetOpcode::G_BUILD_VECTOR);
993 Type *ElemTy = nullptr;
994 MachineInstr *ElemMI = MRI.getVRegDef(MI.getOperand(1).getReg());
995 assert(ElemMI);
996
997 if (ElemMI->getOpcode() == TargetOpcode::G_CONSTANT) {
998 ElemTy = ElemMI->getOperand(1).getCImm()->getType();
999 } else if (ElemMI->getOpcode() == TargetOpcode::G_FCONSTANT) {
1000 ElemTy = ElemMI->getOperand(1).getFPImm()->getType();
1001 } else {
1002 if (SPIRVTypeInst ElemSpvType =
1003 GR->getSPIRVTypeForVReg(MI.getOperand(1).getReg(), &MF))
1004 ElemTy = const_cast<Type *>(GR->getTypeForSPIRVType(ElemSpvType));
1005 }
1006 if (ElemTy)
1007 Ty = VectorType::get(
1008 ElemTy, MI.getNumExplicitOperands() - MI.getNumExplicitDefs(),
1009 false);
1010 else
1011 NeedAssignType = false;
1012 }
1013 if (NeedAssignType)
1014 updateRegType(Reg, Ty, nullptr, GR, MIB, MRI);
1015 } else if (MIOp == TargetOpcode::G_GLOBAL_VALUE) {
1016 propagateSPIRVType(&MI, GR, MRI, MIB);
1017 }
1018
1019 if (MII == Begin)
1020 ReachedBegin = true;
1021 else
1022 --MII;
1023 }
1024 }
1025 for (MachineInstr *MI : ToErase) {
1026 auto It = RegsAlreadyAddedToDT.find(MI);
1027 if (It != RegsAlreadyAddedToDT.end())
1028 MRI.replaceRegWith(MI->getOperand(0).getReg(), It->second);
1030 }
1031
1032 // Address the case when IRTranslator introduces instructions with new
1033 // registers without associated SPIRV type.
1034 for (MachineBasicBlock &MBB : MF) {
1035 for (MachineInstr &MI : MBB) {
1036 switch (MI.getOpcode()) {
1037 case TargetOpcode::G_TRUNC:
1038 case TargetOpcode::G_ANYEXT:
1039 case TargetOpcode::G_SEXT:
1040 case TargetOpcode::G_ZEXT:
1041 case TargetOpcode::G_PTRTOINT:
1042 case TargetOpcode::COPY:
1043 case TargetOpcode::G_ADDRSPACE_CAST:
1044 propagateSPIRVType(&MI, GR, MRI, MIB);
1045 break;
1046 }
1047 }
1048 }
1049}
1050
1053 MachineIRBuilder MIB) {
1055 for (MachineBasicBlock &MBB : MF)
1056 for (MachineInstr &MI : MBB)
1057 if (isTypeFoldingSupported(MI.getOpcode()))
1058 processInstr(MI, MIB, MRI, GR, nullptr);
1059}
1060
1061static Register
1063 SmallVector<unsigned, 4> *Ops = nullptr) {
1064 Register DefReg;
1065 unsigned StartOp = InlineAsm::MIOp_FirstOperand,
1066 AsmDescOp = InlineAsm::MIOp_FirstOperand;
1067 for (unsigned Idx = StartOp, MISz = MI->getNumOperands(); Idx != MISz;
1068 ++Idx) {
1069 const MachineOperand &MO = MI->getOperand(Idx);
1070 if (MO.isMetadata())
1071 continue;
1072 if (Idx == AsmDescOp && MO.isImm()) {
1073 // compute the index of the next operand descriptor
1074 const InlineAsm::Flag F(MO.getImm());
1075 AsmDescOp += 1 + F.getNumOperandRegisters();
1076 continue;
1077 }
1078 if (MO.isReg() && MO.isDef()) {
1079 if (!Ops)
1080 return MO.getReg();
1081 DefReg = MO.getReg();
1082 } else if (Ops) {
1083 Ops->push_back(Idx);
1084 }
1085 }
1086 return DefReg;
1087}
1088
1089static void
1091 const SPIRVSubtarget &ST, MachineIRBuilder MIRBuilder,
1092 const SmallVector<MachineInstr *> &ToProcess) {
1094 Register AsmTargetReg;
1095 for (unsigned i = 0, Sz = ToProcess.size(); i + 1 < Sz; i += 2) {
1096 MachineInstr *I1 = ToProcess[i], *I2 = ToProcess[i + 1];
1097 assert(isSpvIntrinsic(*I1, Intrinsic::spv_inline_asm) && I2->isInlineAsm());
1098 MIRBuilder.setInsertPt(*I2->getParent(), *I2);
1099
1100 if (!AsmTargetReg.isValid()) {
1101 // define vendor specific assembly target or dialect
1102 AsmTargetReg = MRI.createGenericVirtualRegister(LLT::scalar(32));
1103 MRI.setRegClass(AsmTargetReg, &SPIRV::iIDRegClass);
1104 auto AsmTargetMIB =
1105 MIRBuilder.buildInstr(SPIRV::OpAsmTargetINTEL).addDef(AsmTargetReg);
1106 addStringImm(ST.getTargetTripleAsStr(), AsmTargetMIB);
1107 GR->add(AsmTargetMIB.getInstr(), AsmTargetMIB);
1108 }
1109
1110 // create types
1111 const MDNode *IAMD = I1->getOperand(1).getMetadata();
1114 for (const auto &ArgTy : FTy->params())
1115 ArgTypes.push_back(GR->getOrCreateSPIRVType(
1116 ArgTy, MIRBuilder, SPIRV::AccessQualifier::ReadWrite, true));
1117 SPIRVTypeInst RetType =
1118 GR->getOrCreateSPIRVType(FTy->getReturnType(), MIRBuilder,
1119 SPIRV::AccessQualifier::ReadWrite, true);
1121 FTy, RetType, ArgTypes, MIRBuilder);
1122
1123 // define vendor specific assembly instructions string
1124 Register AsmReg = MRI.createGenericVirtualRegister(LLT::scalar(32));
1125 MRI.setRegClass(AsmReg, &SPIRV::iIDRegClass);
1126 auto AsmMIB = MIRBuilder.buildInstr(SPIRV::OpAsmINTEL)
1127 .addDef(AsmReg)
1128 .addUse(GR->getSPIRVTypeID(RetType))
1129 .addUse(GR->getSPIRVTypeID(FuncType))
1130 .addUse(AsmTargetReg);
1131 // inline asm string:
1132 addStringImm(I2->getOperand(InlineAsm::MIOp_AsmString).getSymbolName(),
1133 AsmMIB);
1134 // inline asm constraint string:
1135 addStringImm(cast<MDString>(I1->getOperand(2).getMetadata()->getOperand(0))
1136 ->getString(),
1137 AsmMIB);
1138 GR->add(AsmMIB.getInstr(), AsmMIB);
1139
1140 // calls the inline assembly instruction
1141 unsigned ExtraInfo = I2->getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1142 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1143 MIRBuilder.buildInstr(SPIRV::OpDecorate)
1144 .addUse(AsmReg)
1145 .addImm(static_cast<uint32_t>(SPIRV::Decoration::SideEffectsINTEL));
1146
1148 if (!DefReg.isValid()) {
1149 DefReg = MRI.createGenericVirtualRegister(LLT::scalar(32));
1150 MRI.setRegClass(DefReg, &SPIRV::iIDRegClass);
1151 SPIRVTypeInst VoidType = GR->getOrCreateSPIRVType(
1152 Type::getVoidTy(MF.getFunction().getContext()), MIRBuilder,
1153 SPIRV::AccessQualifier::ReadWrite, true);
1154 GR->assignSPIRVTypeToVReg(VoidType, DefReg, MF);
1155 }
1156
1157 auto AsmCall = MIRBuilder.buildInstr(SPIRV::OpAsmCallINTEL)
1158 .addDef(DefReg)
1159 .addUse(GR->getSPIRVTypeID(RetType))
1160 .addUse(AsmReg);
1161 for (unsigned IntrIdx = 3; IntrIdx < I1->getNumOperands(); ++IntrIdx)
1162 AsmCall.addUse(I1->getOperand(IntrIdx).getReg());
1163 AsmCall->setDebugLoc(I2->getDebugLoc());
1164
1165 // IRTranslator gets a bit confused when lowering inline ASM with outputs
1166 // and inserts a spurious COPY & TRUNC as registers are assumed to be i64;
1167 // we have to clean that up here to prevent erroneous trunc casts either on
1168 // a struct (for multiple outputs) or same width integers to get lowered
1169 // into SPIR-V
1170 if (MRI.hasOneUse(DefReg)) {
1171 MachineInstr &CopyMI = *MRI.use_instr_begin(DefReg);
1172 if (CopyMI.getOpcode() == TargetOpcode::COPY) {
1173 Register CopyDst = CopyMI.getOperand(0).getReg();
1174 if (MRI.hasOneUse(CopyDst)) {
1175 MachineInstr &TruncMI = *MRI.use_instr_begin(CopyDst);
1176 if (TruncMI.getOpcode() == TargetOpcode::G_TRUNC) {
1177 MRI.setType(DefReg, GR->getRegType(RetType));
1178 Register TruncReg = TruncMI.defs().begin()->getReg();
1179 MRI.replaceRegWith(TruncReg, DefReg);
1180 invalidateAndEraseMI(GR, &TruncMI);
1181 invalidateAndEraseMI(GR, &CopyMI);
1182 }
1183 }
1184 }
1185 }
1186 }
1187 for (MachineInstr *MI : ToProcess)
1189}
1190
1192 const SPIRVSubtarget &ST,
1193 MachineIRBuilder MIRBuilder) {
1195 for (MachineBasicBlock &MBB : MF) {
1196 for (MachineInstr &MI : MBB) {
1197 if (isSpvIntrinsic(MI, Intrinsic::spv_inline_asm) ||
1198 MI.getOpcode() == TargetOpcode::INLINEASM)
1199 ToProcess.push_back(&MI);
1200 }
1201 }
1202 if (ToProcess.size() == 0)
1203 return;
1204
1205 if (!ST.canUseExtension(SPIRV::Extension::SPV_INTEL_inline_assembly))
1206 report_fatal_error("Inline assembly instructions require the "
1207 "following SPIR-V extension: SPV_INTEL_inline_assembly",
1208 false);
1209
1210 insertInlineAsmProcess(MF, GR, ST, MIRBuilder, ToProcess);
1211}
1212
1214 MachineIRBuilder MIB) {
1217 for (MachineBasicBlock &MBB : MF) {
1218 for (MachineInstr &MI : MBB) {
1219 if (!isSpvIntrinsic(MI, Intrinsic::spv_assign_decoration) &&
1220 !isSpvIntrinsic(MI, Intrinsic::spv_assign_aliasing_decoration) &&
1221 !isSpvIntrinsic(MI, Intrinsic::spv_assign_fpmaxerror_decoration))
1222 continue;
1223 MIB.setInsertPt(*MI.getParent(), MI.getNextNode());
1224 if (isSpvIntrinsic(MI, Intrinsic::spv_assign_decoration)) {
1225 buildOpSpirvDecorations(MI.getOperand(1).getReg(), MIB,
1226 MI.getOperand(2).getMetadata(), ST);
1227 } else if (isSpvIntrinsic(MI,
1228 Intrinsic::spv_assign_fpmaxerror_decoration)) {
1230 MI.getOperand(2).getMetadata()->getOperand(0));
1231 uint32_t OpValue = OpV->getValueAPF().bitcastToAPInt().getZExtValue();
1232
1233 buildOpDecorate(MI.getOperand(1).getReg(), MIB,
1234 SPIRV::Decoration::FPMaxErrorDecorationINTEL,
1235 {OpValue});
1236 } else {
1237 GR->buildMemAliasingOpDecorate(MI.getOperand(1).getReg(), MIB,
1238 MI.getOperand(2).getImm(),
1239 MI.getOperand(3).getMetadata());
1240 }
1241
1242 ToErase.push_back(&MI);
1243 }
1244 }
1245 for (MachineInstr *MI : ToErase)
1247}
1248
1249// Returns the value of the switch case operand in Reg. The case value stays a
1250// G_CONSTANT until the module emits a SPIR-V constant for the same value, at
1251// which point the case register is replaced with the one defining that
1252// constant, which keeps its value in literal operands rather than in a CImm.
1254 const MachineRegisterInfo &MRI,
1255 LLVMContext &Ctx) {
1256 APInt Val;
1257 if (mi_match(Reg, MRI, m_ICst(Val)))
1258 return ConstantInt::get(Ctx, Val);
1259
1260 const MachineInstr *Def = nullptr;
1261 if (!mi_match(Reg, MRI, m_MInstr(Def)))
1262 llvm_unreachable("Switch case operand has no definition");
1263
1264 LLT Ty = MRI.getType(Reg);
1265 assert(Ty.isValid() && "Expected a typed switch case value");
1266 Val = APInt(Ty.getScalarSizeInBits(), 0);
1267
1268 switch (Def->getOpcode()) {
1269 case SPIRV::OpConstantNull:
1270 case SPIRV::OpConstantI:
1271 // The operands after the type are 32-bit literal words, least significant
1272 // first, as written by addNumImm(). OpConstantNull carries none, so it
1273 // decodes to zero without a case of its own.
1274 for (unsigned I = 2, E = Def->getNumExplicitOperands(); I != E; ++I) {
1275 uint32_t Word = static_cast<uint32_t>(Def->getOperand(I).getImm());
1276 Val |= APInt(Val.getBitWidth(), Word).shl((I - 2) * 32);
1277 }
1278 break;
1279 default:
1280 llvm_unreachable("Unexpected definition of a switch case value");
1281 }
1282 return ConstantInt::get(Ctx, Val);
1283}
1284
1285// LLVM allows the switches to use registers as cases, while SPIR-V required
1286// those to be immediate values. This function replaces such operands with the
1287// equivalent immediate constant.
1290 MachineIRBuilder MIB) {
1292 LLVMContext &Ctx = MF.getFunction().getContext();
1293 for (MachineBasicBlock &MBB : MF) {
1294 for (MachineInstr &MI : MBB) {
1295 if (!isSpvIntrinsic(MI, Intrinsic::spv_switch))
1296 continue;
1297
1299 NewOperands.push_back(MI.getOperand(0)); // Opcode
1300 NewOperands.push_back(MI.getOperand(1)); // Condition
1301 NewOperands.push_back(MI.getOperand(2)); // Default
1302 for (unsigned i = 3; i < MI.getNumOperands(); i += 2) {
1303 Register Reg = MI.getOperand(i).getReg();
1304 NewOperands.push_back(
1306
1307 NewOperands.push_back(MI.getOperand(i + 1));
1308 }
1309
1310 assert(MI.getNumOperands() == NewOperands.size());
1311 while (MI.getNumOperands() > 0)
1312 MI.removeOperand(0);
1313 for (auto &MO : NewOperands)
1314 MI.addOperand(MO);
1315 }
1316 }
1317}
1318
1319// Some instructions are used during CodeGen but should never be emitted.
1320// Cleaning up those.
1322 SPIRVGlobalRegistry *GR) {
1324 for (MachineBasicBlock &MBB : MF) {
1325 for (MachineInstr &MI : MBB) {
1326 if (isSpvIntrinsic(MI, Intrinsic::spv_track_constant) ||
1327 MI.getOpcode() == TargetOpcode::G_BRINDIRECT)
1328 ToEraseMI.push_back(&MI);
1329 }
1330 }
1331
1332 for (MachineInstr *MI : ToEraseMI)
1334}
1335
1336// Find all usages of G_BLOCK_ADDR in our intrinsics and replace those
1337// operands/registers by the actual MBB it references.
1339 MachineIRBuilder MIB) {
1340 // Gather the reverse-mapping BB -> MBB.
1342 for (MachineBasicBlock &MBB : MF)
1343 BB2MBB[MBB.getBasicBlock()] = &MBB;
1344
1345 // Gather instructions requiring patching. For now, only those can use
1346 // G_BLOCK_ADDR.
1347 SmallVector<MachineInstr *, 8> InstructionsToPatch;
1348 for (MachineBasicBlock &MBB : MF) {
1349 for (MachineInstr &MI : MBB) {
1350 if (isSpvIntrinsic(MI, Intrinsic::spv_switch) ||
1351 isSpvIntrinsic(MI, Intrinsic::spv_loop_merge) ||
1352 isSpvIntrinsic(MI, Intrinsic::spv_selection_merge))
1353 InstructionsToPatch.push_back(&MI);
1354 }
1355 }
1356
1357 // For each instruction to fix, we replace all the G_BLOCK_ADDR operands by
1358 // the actual MBB it references. Once those references have been updated, we
1359 // can cleanup remaining G_BLOCK_ADDR references.
1360 SmallPtrSet<MachineBasicBlock *, 8> ClearAddressTaken;
1363 for (MachineInstr *MI : InstructionsToPatch) {
1365 for (unsigned i = 0; i < MI->getNumOperands(); ++i) {
1366 // The operand is not a register, keep as-is.
1367 if (!MI->getOperand(i).isReg()) {
1368 NewOps.push_back(MI->getOperand(i));
1369 continue;
1370 }
1371
1372 Register Reg = MI->getOperand(i).getReg();
1373 MachineInstr *BuildMBB = MRI.getVRegDef(Reg);
1374 // The register is not the result of G_BLOCK_ADDR, keep as-is.
1375 if (!BuildMBB || BuildMBB->getOpcode() != TargetOpcode::G_BLOCK_ADDR) {
1376 NewOps.push_back(MI->getOperand(i));
1377 continue;
1378 }
1379
1380 assert(BuildMBB && BuildMBB->getOpcode() == TargetOpcode::G_BLOCK_ADDR &&
1381 BuildMBB->getOperand(1).isBlockAddress() &&
1382 BuildMBB->getOperand(1).getBlockAddress());
1383 BasicBlock *BB =
1384 BuildMBB->getOperand(1).getBlockAddress()->getBasicBlock();
1385 auto It = BB2MBB.find(BB);
1386 if (It == BB2MBB.end())
1387 report_fatal_error("cannot find a machine basic block by a basic block "
1388 "in a switch statement");
1389 MachineBasicBlock *ReferencedBlock = It->second;
1390 NewOps.push_back(MachineOperand::CreateMBB(ReferencedBlock));
1391
1392 ClearAddressTaken.insert(ReferencedBlock);
1393 ToEraseMI.insert(BuildMBB);
1394 }
1395
1396 // Replace the operands.
1397 assert(MI->getNumOperands() == NewOps.size());
1398 while (MI->getNumOperands() > 0)
1399 MI->removeOperand(0);
1400 for (auto &MO : NewOps)
1401 MI->addOperand(MO);
1402
1403 if (MachineInstr *Next = MI->getNextNode()) {
1404 if (isSpvIntrinsic(*Next, Intrinsic::spv_track_constant)) {
1405 ToEraseMI.insert(Next);
1406 Next = MI->getNextNode();
1407 }
1408 if (Next && Next->getOpcode() == TargetOpcode::G_BRINDIRECT)
1409 ToEraseMI.insert(Next);
1410 }
1411 }
1412
1413 // BlockAddress operands were used to keep information between passes,
1414 // let's undo the "address taken" status to reflect that Succ doesn't
1415 // actually correspond to an IR-level basic block.
1416 for (MachineBasicBlock *Succ : ClearAddressTaken)
1417 Succ->setAddressTakenIRBlock(nullptr);
1418
1419 // If we just delete G_BLOCK_ADDR instructions with BlockAddress operands,
1420 // this leaves their BasicBlock counterparts in a "address taken" status. This
1421 // would make AsmPrinter to generate a series of unneeded labels of a "Address
1422 // of block that was removed by CodeGen" kind. Let's first ensure that we
1423 // don't have a dangling BlockAddress constants by zapping the BlockAddress
1424 // nodes, and only after that proceed with erasing G_BLOCK_ADDR instructions.
1425 Constant *Replacement =
1426 ConstantInt::get(Type::getInt32Ty(MF.getFunction().getContext()), 1);
1427 for (MachineInstr *BlockAddrI : ToEraseMI) {
1428 if (BlockAddrI->getOpcode() == TargetOpcode::G_BLOCK_ADDR) {
1429 BlockAddress *BA = const_cast<BlockAddress *>(
1430 BlockAddrI->getOperand(1).getBlockAddress());
1432 ConstantExpr::getIntToPtr(Replacement, BA->getType()));
1433 BA->destroyConstant();
1434 }
1435 invalidateAndEraseMI(GR, BlockAddrI);
1436 }
1437}
1438
1440 if (MBB.empty())
1441 return MBB.getNextNode() != nullptr;
1442
1443 // Branching SPIR-V intrinsics are not detected by this generic method.
1444 // Thus, we can only trust negative result.
1445 if (!MBB.canFallThrough())
1446 return false;
1447
1448 // Otherwise, we must manually check if we have a SPIR-V intrinsic which
1449 // prevent an implicit fallthrough.
1450 for (MachineBasicBlock::reverse_iterator It = MBB.rbegin(), E = MBB.rend();
1451 It != E; ++It) {
1452 if (isSpvIntrinsic(*It, Intrinsic::spv_switch))
1453 return false;
1454 }
1455 return true;
1456}
1457
1459 MachineIRBuilder MIB) {
1460 // It is valid for MachineBasicBlocks to not finish with a branch instruction.
1461 // In such cases, they will simply fallthrough their immediate successor.
1462 for (MachineBasicBlock &MBB : MF) {
1464 continue;
1465
1466 assert(MBB.succ_size() == 1);
1467 MIB.setInsertPt(MBB, MBB.end());
1468 MIB.buildBr(**MBB.successors().begin());
1469 }
1470}
1471
1473 const MachineDominatorTree &MDT) {
1474 // Initialize the type registry.
1475 const SPIRVSubtarget &ST = MF.getSubtarget<SPIRVSubtarget>();
1476 SPIRVGlobalRegistry *GR = ST.getSPIRVGlobalRegistry();
1477 GR->setCurrentFunc(MF);
1478 MachineIRBuilder MIB(MF);
1479 // a registry of target extension constants
1480 DenseMap<MachineInstr *, Type *> TargetExtConstTypes;
1481 // to keep record of tracked constants
1482 addConstantsToTrack(MF, GR, ST, TargetExtConstTypes);
1483 foldConstantsIntoIntrinsics(MF, GR, MIB);
1484 insertBitcasts(MF, GR, MIB);
1485 generateAssignInstrs(MF, GR, MIB, TargetExtConstTypes, MDT);
1486
1487 processSwitchesConstants(MF, GR, MIB);
1488 processBlockAddr(MF, GR, MIB);
1490
1491 processInstrsWithTypeFolding(MF, GR, MIB);
1493 insertSpirvDecorations(MF, GR, MIB);
1494 insertInlineAsm(MF, GR, ST, MIB);
1495 lowerBitcasts(MF, GR, MIB);
1496
1497 return true;
1498}
1499
1500INITIALIZE_PASS(SPIRVPreLegalizerLegacy, DEBUG_TYPE, "SPIRV pre legalizer",
1501 false, false)
1502
1503char SPIRVPreLegalizerLegacy::ID = 0;
1504
1505FunctionPass *llvm::createSPIRVPreLegalizerLegacyPass() {
1506 return new SPIRVPreLegalizerLegacy();
1507}
1508
1509bool SPIRVPreLegalizerLegacy::runOnMachineFunction(MachineFunction &MF) {
1510 return runPreLegalizer(
1511 MF, getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree());
1512}
1513
1514PreservedAnalyses
MachineInstrBuilder & UseMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
This file contains the simple types necessary to represent the attributes associated with functions a...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Provides analysis for continuously CSEing during GISel passes.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Provides analysis for querying information about KnownBits during GISel passes.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
MachineRegisterInfo & MRI
static DominatorTree getDomTree(Function &F)
static std::optional< unsigned > getNarrowScalarWidth(Register Reg, const MachineRegisterInfo &MRI)
static Register collectInlineAsmInstrOperands(MachineInstr *MI, SmallVector< unsigned, 4 > *Ops=nullptr)
static void insertInlineAsm(MachineFunction &MF, SPIRVGlobalRegistry *GR, const SPIRVSubtarget &ST, MachineIRBuilder MIRBuilder)
static void cleanupHelperInstructions(MachineFunction &MF, SPIRVGlobalRegistry *GR)
static void insertInlineAsmProcess(MachineFunction &MF, SPIRVGlobalRegistry *GR, const SPIRVSubtarget &ST, MachineIRBuilder MIRBuilder, const SmallVector< MachineInstr * > &ToProcess)
static NarrowWideningInfo recordNarrowOperandWidths(MachineFunction &MF, const MachineRegisterInfo &MRI)
static void removeImplicitFallthroughs(MachineFunction &MF, MachineIRBuilder MIB)
static unsigned widenBitWidthToNextPow2(unsigned BitWidth)
static void generateAssignInstrs(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB, DenseMap< MachineInstr *, Type * > &TargetExtConstTypes, const MachineDominatorTree &MDT)
static void setInsertPtAfterDef(MachineIRBuilder &MIB, MachineInstr *Def)
static bool isWidthSensitiveBitCountOp(unsigned Opcode)
static bool isImplicitFallthrough(MachineBasicBlock &MBB)
static void insertSpirvDecorations(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void insertBitcasts(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void processInstrsWithTypeFolding(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static bool runPreLegalizer(MachineFunction &MF, const MachineDominatorTree &MDT)
static void processSwitchesConstants(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void lowerBitcasts(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static MachineInstr * findAssignTypeInstr(Register Reg, MachineRegisterInfo *MRI)
static void widenCImmType(MachineOperand &MOP)
static void widenSignSensitiveOps(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIB, MachineRegisterInfo &MRI, const NarrowWideningInfo &Info)
static void buildOpBitcast(SPIRVGlobalRegistry *GR, MachineIRBuilder &MIB, Register ResVReg, Register OpReg)
static void processBlockAddr(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void widenBitCountOps(SPIRVGlobalRegistry *GR, MachineIRBuilder &MIB, MachineRegisterInfo &MRI, const NarrowWideningInfo &Info)
static void widenScalarType(Register Reg, MachineRegisterInfo &MRI)
static const ConstantInt * getSwitchCaseValue(Register Reg, const MachineRegisterInfo &MRI, LLVMContext &Ctx)
static void foldConstantsIntoIntrinsics(MachineFunction &MF, SPIRVGlobalRegistry *GR, MachineIRBuilder MIB)
static void addConstantsToTrack(MachineFunction &MF, SPIRVGlobalRegistry *GR, const SPIRVSubtarget &STI, DenseMap< MachineInstr *, Type * > &TargetExtConstTypes)
static SPIRVTypeInst propagateSPIRVType(MachineInstr *MI, SPIRVGlobalRegistry *GR, MachineRegisterInfo &MRI, MachineIRBuilder &MIB)
static bool isSignSensitiveOp(const MachineInstr &MI)
static void invalidateAndEraseMI(SPIRVGlobalRegistry *GR, MachineInstr *MI)
The Input class is used to parse a yaml document into in-memory structs and vectors.
APInt bitcastToAPInt() const
Definition APFloat.h:1508
Class for arbitrary precision integers.
Definition APInt.h:78
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
The address of a basic block.
Definition Constants.h:1088
BasicBlock * getBasicBlock() const
Definition Constants.h:1125
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValueAPF() const
Definition Constants.h:463
This is the shared class of boolean and integer constants.
Definition Constants.h:87
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI void destroyConstant()
Called if some element of this constant is no longer valid.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
constexpr unsigned getScalarSizeInBits() const
constexpr bool isScalar() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
constexpr ElementCount getElementCount() const
LLT changeElementSize(unsigned NewEltSize) const
If this type is a vector, return a vector with the same number of elements but the new element size.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
MachineInstrBundleIterator< MachineInstr, true > reverse_iterator
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineBasicBlock & front() const
Helper class to build MachineInstr.
MachineInstrBuilder buildBr(MachineBasicBlock &Dest)
Build and insert G_BR Dest.
void setInsertPt(MachineBasicBlock &MBB, MachineBasicBlock::iterator II)
Set the insertion point before the specified position.
MachineInstrBuilder buildZExtInReg(const DstOp &Res, const SrcOp &Op, int64_t ImmOp)
Build and inserts Res = G_AND Op, LowBitsSet(ImmOp) Since there is no G_ZEXT_INREG like G_SEXT_INREG,...
MachineInstrBuilder buildAnd(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1)
Build and insert Res = G_AND Op0, Op1.
MachineInstrBuilder buildSub(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_SUB Op0, Op1.
MachineInstrBuilder buildShl(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
MachineInstrBuilder buildInstr(unsigned Opcode)
Build and insert <empty> = Opcode <empty>.
MachineInstrBuilder buildBuildVectorConstant(const DstOp &Res, ArrayRef< APInt > Ops)
Build and insert Res = G_BUILD_VECTOR Op0, ... where each OpN is built with G_CONSTANT.
MachineFunction & getMF()
Getter for the function we currently build.
void setInstrAndDebugLoc(MachineInstr &MI)
Set the insertion point to before MI, and set the debug loc to MI's loc.
MachineInstrBuilder buildBitcast(const DstOp &Dst, const SrcOp &Src)
Build and insert Dst = G_BITCAST Src.
MachineRegisterInfo * getMRI()
Getter for MRI.
MachineInstrBuilder buildOr(const DstOp &Dst, const SrcOp &Src0, const SrcOp &Src1, std::optional< unsigned > Flags=std::nullopt)
Build and insert Res = G_OR Op0, Op1.
MachineInstrBuilder buildCopy(const DstOp &Res, const SrcOp &Op)
Build and insert Res = COPY Op.
virtual MachineInstrBuilder buildConstant(const DstOp &Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
MachineInstrBuilder buildSExtInReg(const DstOp &Res, const SrcOp &Op, int64_t ImmOp)
Build and insert Res = G_SEXT_INREG Op, ImmOp.
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
const MachineOperand & getOperand(unsigned i) const
void setDebugLoc(DebugLoc DL)
Replace current source information with new such.
MachineOperand class - Representation of each machine instruction operand.
const ConstantInt * getCImm() const
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
const MDNode * getMetadata() const
static MachineOperand CreateCImm(const ConstantInt *CI)
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isMetadata() const
isMetadata - Tests if this is a MO_Metadata operand.
const BlockAddress * getBlockAddress() const
void setCImm(const ConstantInt *CI)
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
static MachineOperand CreateMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, false, false, true > use_instr_iterator
use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses of the specified register,...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isValid() const
Definition Register.h:109
void assignSPIRVTypeToVReg(SPIRVTypeInst Type, Register VReg, const MachineFunction &MF)
SPIRVTypeInst getOrCreateOpTypeFunctionWithArgs(const Type *Ty, SPIRVTypeInst RetType, const SmallVectorImpl< SPIRVTypeInst > &ArgTypes, MachineIRBuilder &MIRBuilder)
const TargetRegisterClass * getRegClass(SPIRVTypeInst SpvType) const
SPIRVTypeInst getOrCreateSPIRVPointerType(const Type *BaseType, MachineIRBuilder &MIRBuilder, SPIRV::StorageClass::StorageClass SC, bool ForceTyped=false, bool EmitIR=true)
bool isAggregateType(SPIRVTypeInst Type) const
unsigned getScalarOrVectorBitWidth(SPIRVTypeInst Type) const
void setUntypedPtrElementType(Register Reg, SPIRVTypeInst ElemType)
SPIRVTypeInst getOrCreateSPIRVIntegerType(unsigned BitWidth, MachineIRBuilder &MIRBuilder)
SPIRVTypeInst getOrCreateSPIRVVectorType(SPIRVTypeInst BaseType, unsigned NumElements, MachineIRBuilder &MIRBuilder, bool EmitIR)
unsigned getScalarOrVectorComponentCount(Register VReg) const
const Type * getTypeForSPIRVType(SPIRVTypeInst Ty) const
bool isBitcastCompatible(SPIRVTypeInst Type1, SPIRVTypeInst Type2) const
LLT getRegType(SPIRVTypeInst SpvType) const
void invalidateMachineInstr(MachineInstr *MI)
Register getSPIRVTypeID(SPIRVTypeInst SpirvType) const
SPIRVTypeInst changePointerStorageClass(SPIRVTypeInst PtrType, SPIRV::StorageClass::StorageClass SC, MachineInstr &I)
void addGlobalObject(const Value *V, const MachineFunction *MF, Register R)
SPIRVTypeInst getOrCreateSPIRVType(const Type *Type, MachineInstr &I, SPIRV::AccessQualifier::AccessQualifier AQ, bool EmitIR)
SPIRVTypeInst getSPIRVTypeForVReg(Register VReg, const MachineFunction *MF=nullptr) const
Type * getDeducedGlobalValueType(const GlobalValue *Global)
void addValueAttrs(MachineInstr *Key, std::pair< Type *, std::string > Val)
void buildMemAliasingOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, uint32_t Dec, const MDNode *GVarMD)
SPIRV::StorageClass::StorageClass getPointerStorageClass(Register VReg) const
SPIRVTypeInst getUntypedPtrElementType(Register Reg) const
bool add(SPIRV::IRHandle Handle, const MachineInstr *MI)
Register find(SPIRV::IRHandle Handle, const MachineFunction *MF)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const SPIRVInstrInfo * getInstrInfo() const override
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
static LLVM_ABI TypedPointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
IteratorT begin() const
Pass manager infrastructure for declaring and invalidating analyses.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
operand_type_match m_Reg()
ConstantMatch< APInt > m_ICst(APInt &Cst)
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
BinaryOp_match< LHS, RHS, TargetOpcode::G_AND, true > m_GAnd(const LHS &L, const RHS &R)
bind_ty< MachineInstr * > m_MInstr(MachineInstr *&MI)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:708
This is an optimization pass for GlobalISel generic memory operations.
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
StringMapEntry< Value * > ValueName
Definition Value.h:56
void addStringImm(StringRef Str, MCInst &Inst)
bool isTypeFoldingSupported(unsigned Opcode)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Register createVirtualRegister(SPIRVTypeInst SpvType, SPIRVGlobalRegistry *GR, MachineRegisterInfo *MRI, const MachineFunction &MF)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void updateRegType(Register Reg, Type *Ty, SPIRVTypeInst SpirvTy, SPIRVGlobalRegistry *GR, MachineIRBuilder &MIB, MachineRegisterInfo &MRI)
Helper external function for assigning a SPIRV type to a register, ensuring the register class and ty...
void buildOpDecorate(Register Reg, MachineIRBuilder &MIRBuilder, SPIRV::Decoration::Decoration Dec, ArrayRef< uint32_t > DecArgs, StringRef StrImm)
constexpr unsigned storageClassToAddressSpace(SPIRV::StorageClass::StorageClass SC)
Definition SPIRVUtils.h:234
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void buildOpName(Register Target, StringRef Name, MachineIRBuilder &MIRBuilder)
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
Type * toTypedPointer(Type *Ty)
Definition SPIRVUtils.h:472
bool isVector1(Type *Ty)
Definition SPIRVUtils.h:505
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
auto post_order(const T &G)
Post-order traversal of a graph.
MachineInstr * passCopy(MachineInstr *Def, const MachineRegisterInfo *MRI)
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...
Definition Casting.h:547
@ Global
Append to llvm.global_dtors.
SPIRV::StorageClass::StorageClass addressSpaceToStorageClass(unsigned AddrSpace, const SPIRVSubtarget &STI)
void buildOpSpirvDecorations(Register Reg, MachineIRBuilder &MIRBuilder, const MDNode *GVarMD, const SPIRVSubtarget &ST)
void processInstr(MachineInstr &MI, MachineIRBuilder &MIB, MachineRegisterInfo &MRI, SPIRVGlobalRegistry *GR, SPIRVTypeInst KnownResType)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Type * getMDOperandAsType(const MDNode *N, unsigned I)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
FunctionPass * createSPIRVPreLegalizerLegacyPass()
bool isSpvIntrinsic(const MachineInstr &MI, Intrinsic::ID IntrinsicID)
MachineInstr * getVRegDef(MachineRegisterInfo &MRI, Register Reg)
SmallVector< MachineInstr * > SignSensitiveWorklist
DenseMap< Register, unsigned > OrigWidth
SmallVector< std::pair< MachineInstr *, unsigned > > BitCountWorklist