1 //===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- C++ -*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file implements the IRTranslator class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
19 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/IR/Constant.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/Target/TargetFrameLowering.h"
34 #include "llvm/Target/TargetIntrinsicInfo.h"
35 #include "llvm/Target/TargetLowering.h"
37 #define DEBUG_TYPE "irtranslator"
41 char IRTranslator::ID = 0;
42 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
44 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
45 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
48 static void reportTranslationError(MachineFunction &MF,
49 const TargetPassConfig &TPC,
50 OptimizationRemarkEmitter &ORE,
51 OptimizationRemarkMissed &R) {
52 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
54 // Print the function name explicitly if we don't have a debug location (which
55 // makes the diagnostic less useful) or if we're going to emit a raw error.
56 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
57 R << (" (in function: " + MF.getName() + ")").str();
59 if (TPC.isGlobalISelAbortEnabled())
60 report_fatal_error(R.getMsg());
65 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
66 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
69 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<TargetPassConfig>();
71 MachineFunctionPass::getAnalysisUsage(AU);
75 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
76 unsigned &ValReg = ValToVReg[&Val];
81 // Fill ValRegsSequence with the sequence of registers
82 // we need to concat together to produce the value.
83 assert(Val.getType()->isSized() &&
84 "Don't know how to create an empty vreg");
85 unsigned VReg = MRI->createGenericVirtualRegister(LLT{*Val.getType(), *DL});
88 if (auto CV = dyn_cast<Constant>(&Val)) {
89 bool Success = translate(*CV, VReg);
91 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
92 MF->getFunction()->getSubprogram(),
93 &MF->getFunction()->getEntryBlock());
94 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
95 reportTranslationError(*MF, *TPC, *ORE, R);
103 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
104 if (FrameIndices.find(&AI) != FrameIndices.end())
105 return FrameIndices[&AI];
107 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
109 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
111 // Always allocate at least one byte.
112 Size = std::max(Size, 1u);
114 unsigned Alignment = AI.getAlignment();
116 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
118 int &FI = FrameIndices[&AI];
119 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
123 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
124 unsigned Alignment = 0;
125 Type *ValTy = nullptr;
126 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
127 Alignment = SI->getAlignment();
128 ValTy = SI->getValueOperand()->getType();
129 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
130 Alignment = LI->getAlignment();
131 ValTy = LI->getType();
133 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
134 R << "unable to translate memop: " << ore::NV("Opcode", &I);
135 reportTranslationError(*MF, *TPC, *ORE, R);
139 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
142 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
143 MachineBasicBlock *&MBB = BBToMBB[&BB];
145 MBB = MF->CreateMachineBasicBlock(&BB);
148 if (BB.hasAddressTaken())
149 MBB->setHasAddressTaken();
154 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
155 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
156 MachinePreds[Edge].push_back(NewPred);
159 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
160 MachineIRBuilder &MIRBuilder) {
161 // FIXME: handle signed/unsigned wrapping flags.
163 // Get or create a virtual register for each value.
164 // Unless the value is a Constant => loadimm cst?
165 // or inline constant each time?
166 // Creation of a virtual register needs to have a size.
167 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
168 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
169 unsigned Res = getOrCreateVReg(U);
170 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
174 bool IRTranslator::translateCompare(const User &U,
175 MachineIRBuilder &MIRBuilder) {
176 const CmpInst *CI = dyn_cast<CmpInst>(&U);
177 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
178 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
179 unsigned Res = getOrCreateVReg(U);
180 CmpInst::Predicate Pred =
181 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
182 cast<ConstantExpr>(U).getPredicate());
184 if (CmpInst::isIntPredicate(Pred))
185 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
187 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
192 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
193 const ReturnInst &RI = cast<ReturnInst>(U);
194 const Value *Ret = RI.getReturnValue();
195 // The target may mess up with the insertion point, but
196 // this is not important as a return is the last instruction
197 // of the block anyway.
198 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
201 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
202 const BranchInst &BrInst = cast<BranchInst>(U);
204 if (!BrInst.isUnconditional()) {
205 // We want a G_BRCOND to the true BB followed by an unconditional branch.
206 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
207 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
208 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
209 MIRBuilder.buildBrCond(Tst, TrueBB);
212 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
213 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
214 MIRBuilder.buildBr(TgtBB);
217 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
218 for (const BasicBlock *Succ : BrInst.successors())
219 CurBB.addSuccessor(&getOrCreateBB(*Succ));
223 bool IRTranslator::translateSwitch(const User &U,
224 MachineIRBuilder &MIRBuilder) {
225 // For now, just translate as a chain of conditional branches.
226 // FIXME: could we share most of the logic/code in
227 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
228 // At first sight, it seems most of the logic in there is independent of
229 // SelectionDAG-specifics and a lot of work went in to optimize switch
230 // lowering in there.
232 const SwitchInst &SwInst = cast<SwitchInst>(U);
233 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
234 const BasicBlock *OrigBB = SwInst.getParent();
236 LLT LLTi1 = LLT(*Type::getInt1Ty(U.getContext()), *DL);
237 for (auto &CaseIt : SwInst.cases()) {
238 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
239 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
240 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
241 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
242 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
243 MachineBasicBlock &TrueMBB = getOrCreateBB(*TrueBB);
245 MIRBuilder.buildBrCond(Tst, TrueMBB);
246 CurMBB.addSuccessor(&TrueMBB);
247 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
249 MachineBasicBlock *FalseMBB =
250 MF->CreateMachineBasicBlock(SwInst.getParent());
251 MF->push_back(FalseMBB);
252 MIRBuilder.buildBr(*FalseMBB);
253 CurMBB.addSuccessor(FalseMBB);
255 MIRBuilder.setMBB(*FalseMBB);
257 // handle default case
258 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
259 MachineBasicBlock &DefaultMBB = getOrCreateBB(*DefaultBB);
260 MIRBuilder.buildBr(DefaultMBB);
261 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
262 CurMBB.addSuccessor(&DefaultMBB);
263 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
268 bool IRTranslator::translateIndirectBr(const User &U,
269 MachineIRBuilder &MIRBuilder) {
270 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
272 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
273 MIRBuilder.buildBrIndirect(Tgt);
276 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
277 for (const BasicBlock *Succ : BrInst.successors())
278 CurBB.addSuccessor(&getOrCreateBB(*Succ));
283 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
284 const LoadInst &LI = cast<LoadInst>(U);
286 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
287 : MachineMemOperand::MONone;
288 Flags |= MachineMemOperand::MOLoad;
290 unsigned Res = getOrCreateVReg(LI);
291 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
292 LLT VTy{*LI.getType(), *DL}, PTy{*LI.getPointerOperand()->getType(), *DL};
293 MIRBuilder.buildLoad(
295 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
296 Flags, DL->getTypeStoreSize(LI.getType()),
297 getMemOpAlignment(LI), AAMDNodes(), nullptr,
298 LI.getSynchScope(), LI.getOrdering()));
302 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
303 const StoreInst &SI = cast<StoreInst>(U);
304 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
305 : MachineMemOperand::MONone;
306 Flags |= MachineMemOperand::MOStore;
308 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
309 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
310 LLT VTy{*SI.getValueOperand()->getType(), *DL},
311 PTy{*SI.getPointerOperand()->getType(), *DL};
313 MIRBuilder.buildStore(
315 *MF->getMachineMemOperand(
316 MachinePointerInfo(SI.getPointerOperand()), Flags,
317 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
318 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
323 bool IRTranslator::translateExtractValue(const User &U,
324 MachineIRBuilder &MIRBuilder) {
325 const Value *Src = U.getOperand(0);
326 Type *Int32Ty = Type::getInt32Ty(U.getContext());
327 SmallVector<Value *, 1> Indices;
329 // getIndexedOffsetInType is designed for GEPs, so the first index is the
330 // usual array element rather than looking into the actual aggregate.
331 Indices.push_back(ConstantInt::get(Int32Ty, 0));
333 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
334 for (auto Idx : EVI->indices())
335 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
337 for (unsigned i = 1; i < U.getNumOperands(); ++i)
338 Indices.push_back(U.getOperand(i));
341 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
343 unsigned Res = getOrCreateVReg(U);
344 MIRBuilder.buildExtract(Res, Offset, getOrCreateVReg(*Src));
349 bool IRTranslator::translateInsertValue(const User &U,
350 MachineIRBuilder &MIRBuilder) {
351 const Value *Src = U.getOperand(0);
352 Type *Int32Ty = Type::getInt32Ty(U.getContext());
353 SmallVector<Value *, 1> Indices;
355 // getIndexedOffsetInType is designed for GEPs, so the first index is the
356 // usual array element rather than looking into the actual aggregate.
357 Indices.push_back(ConstantInt::get(Int32Ty, 0));
359 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
360 for (auto Idx : IVI->indices())
361 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
363 for (unsigned i = 2; i < U.getNumOperands(); ++i)
364 Indices.push_back(U.getOperand(i));
367 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
369 unsigned Res = getOrCreateVReg(U);
370 const Value &Inserted = *U.getOperand(1);
371 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
377 bool IRTranslator::translateSelect(const User &U,
378 MachineIRBuilder &MIRBuilder) {
379 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
380 getOrCreateVReg(*U.getOperand(1)),
381 getOrCreateVReg(*U.getOperand(2)));
385 bool IRTranslator::translateBitCast(const User &U,
386 MachineIRBuilder &MIRBuilder) {
387 if (LLT{*U.getOperand(0)->getType(), *DL} == LLT{*U.getType(), *DL}) {
388 unsigned &Reg = ValToVReg[&U];
390 MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0)));
392 Reg = getOrCreateVReg(*U.getOperand(0));
395 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
398 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
399 MachineIRBuilder &MIRBuilder) {
400 unsigned Op = getOrCreateVReg(*U.getOperand(0));
401 unsigned Res = getOrCreateVReg(U);
402 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
406 bool IRTranslator::translateGetElementPtr(const User &U,
407 MachineIRBuilder &MIRBuilder) {
408 // FIXME: support vector GEPs.
409 if (U.getType()->isVectorTy())
412 Value &Op0 = *U.getOperand(0);
413 unsigned BaseReg = getOrCreateVReg(Op0);
414 LLT PtrTy{*Op0.getType(), *DL};
415 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
416 LLT OffsetTy = LLT::scalar(PtrSize);
419 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
421 const Value *Idx = GTI.getOperand();
422 if (StructType *StTy = GTI.getStructTypeOrNull()) {
423 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
424 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
427 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
429 // If this is a scalar constant or a splat vector of constants,
430 // handle it quickly.
431 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
432 Offset += ElementSize * CI->getSExtValue();
437 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
438 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
439 MIRBuilder.buildConstant(OffsetReg, Offset);
440 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
442 BaseReg = NewBaseReg;
446 // N = N + Idx * ElementSize;
447 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
448 MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
450 unsigned IdxReg = getOrCreateVReg(*Idx);
451 if (MRI->getType(IdxReg) != OffsetTy) {
452 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
453 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
457 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
458 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
460 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
461 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
462 BaseReg = NewBaseReg;
467 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
468 MIRBuilder.buildConstant(OffsetReg, Offset);
469 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
473 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
477 bool IRTranslator::translateMemfunc(const CallInst &CI,
478 MachineIRBuilder &MIRBuilder,
480 LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL};
481 Type *DstTy = CI.getArgOperand(0)->getType();
482 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
483 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
486 SmallVector<CallLowering::ArgInfo, 8> Args;
487 for (int i = 0; i < 3; ++i) {
488 const auto &Arg = CI.getArgOperand(i);
489 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
494 case Intrinsic::memmove:
495 case Intrinsic::memcpy: {
496 Type *SrcTy = CI.getArgOperand(1)->getType();
497 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
499 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
502 case Intrinsic::memset:
509 return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
510 CallLowering::ArgInfo(0, CI.getType()), Args);
513 void IRTranslator::getStackGuard(unsigned DstReg,
514 MachineIRBuilder &MIRBuilder) {
515 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
516 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
517 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
520 auto &TLI = *MF->getSubtarget().getTargetLowering();
521 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
525 MachinePointerInfo MPInfo(Global);
526 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
527 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
528 MachineMemOperand::MODereferenceable;
530 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
531 DL->getPointerABIAlignment());
532 MIB.setMemRefs(MemRefs, MemRefs + 1);
535 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
536 MachineIRBuilder &MIRBuilder) {
537 LLT Ty{*CI.getOperand(0)->getType(), *DL};
538 LLT s1 = LLT::scalar(1);
539 unsigned Width = Ty.getSizeInBits();
540 unsigned Res = MRI->createGenericVirtualRegister(Ty);
541 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
542 auto MIB = MIRBuilder.buildInstr(Op)
545 .addUse(getOrCreateVReg(*CI.getOperand(0)))
546 .addUse(getOrCreateVReg(*CI.getOperand(1)));
548 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
549 unsigned Zero = MRI->createGenericVirtualRegister(s1);
550 EntryBuilder.buildConstant(Zero, 0);
554 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
558 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
559 MachineIRBuilder &MIRBuilder) {
563 case Intrinsic::lifetime_start:
564 case Intrinsic::lifetime_end:
565 // Stack coloring is not enabled in O0 (which we care about now) so we can
566 // drop these. Make sure someone notices when we start compiling at higher
568 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
571 case Intrinsic::dbg_declare: {
572 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
573 assert(DI.getVariable() && "Missing variable");
575 const Value *Address = DI.getAddress();
576 if (!Address || isa<UndefValue>(Address)) {
577 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
581 unsigned Reg = getOrCreateVReg(*Address);
582 auto RegDef = MRI->def_instr_begin(Reg);
583 assert(DI.getVariable()->isValidLocationForIntrinsic(
584 MIRBuilder.getDebugLoc()) &&
585 "Expected inlined-at fields to agree");
587 if (RegDef != MRI->def_instr_end() &&
588 RegDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
589 MIRBuilder.buildFIDbgValue(RegDef->getOperand(1).getIndex(),
590 DI.getVariable(), DI.getExpression());
592 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
595 case Intrinsic::vaend:
596 // No target I know of cares about va_end. Certainly no in-tree target
597 // does. Simplest intrinsic ever!
599 case Intrinsic::vastart: {
600 auto &TLI = *MF->getSubtarget().getTargetLowering();
601 Value *Ptr = CI.getArgOperand(0);
602 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
604 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
605 .addUse(getOrCreateVReg(*Ptr))
606 .addMemOperand(MF->getMachineMemOperand(
607 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
610 case Intrinsic::dbg_value: {
611 // This form of DBG_VALUE is target-independent.
612 const DbgValueInst &DI = cast<DbgValueInst>(CI);
613 const Value *V = DI.getValue();
614 assert(DI.getVariable()->isValidLocationForIntrinsic(
615 MIRBuilder.getDebugLoc()) &&
616 "Expected inlined-at fields to agree");
618 // Currently the optimizer can produce this; insert an undef to
619 // help debugging. Probably the optimizer should not do this.
620 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
622 } else if (const auto *CI = dyn_cast<Constant>(V)) {
623 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
626 unsigned Reg = getOrCreateVReg(*V);
627 // FIXME: This does not handle register-indirect values at offset 0. The
628 // direct/indirect thing shouldn't really be handled by something as
629 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
630 // pretty baked in right now.
631 if (DI.getOffset() != 0)
632 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
635 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
640 case Intrinsic::uadd_with_overflow:
641 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
642 case Intrinsic::sadd_with_overflow:
643 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
644 case Intrinsic::usub_with_overflow:
645 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
646 case Intrinsic::ssub_with_overflow:
647 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
648 case Intrinsic::umul_with_overflow:
649 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
650 case Intrinsic::smul_with_overflow:
651 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
653 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
654 .addDef(getOrCreateVReg(CI))
655 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
656 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
658 case Intrinsic::memcpy:
659 case Intrinsic::memmove:
660 case Intrinsic::memset:
661 return translateMemfunc(CI, MIRBuilder, ID);
662 case Intrinsic::eh_typeid_for: {
663 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
664 unsigned Reg = getOrCreateVReg(CI);
665 unsigned TypeID = MF->getTypeIDFor(GV);
666 MIRBuilder.buildConstant(Reg, TypeID);
669 case Intrinsic::objectsize: {
670 // If we don't know by now, we're never going to know.
671 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
673 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
676 case Intrinsic::stackguard:
677 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
679 case Intrinsic::stackprotector: {
680 LLT PtrTy{*CI.getArgOperand(0)->getType(), *DL};
681 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
682 getStackGuard(GuardVal, MIRBuilder);
684 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
685 MIRBuilder.buildStore(
686 GuardVal, getOrCreateVReg(*Slot),
687 *MF->getMachineMemOperand(
688 MachinePointerInfo::getFixedStack(*MF,
689 getOrCreateFrameIndex(*Slot)),
690 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
691 PtrTy.getSizeInBits() / 8, 8));
698 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
699 const CallInst &CI = cast<CallInst>(U);
700 auto TII = MF->getTarget().getIntrinsicInfo();
701 const Function *F = CI.getCalledFunction();
703 if (CI.isInlineAsm())
706 if (!F || !F->isIntrinsic()) {
707 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
708 SmallVector<unsigned, 8> Args;
709 for (auto &Arg: CI.arg_operands())
710 Args.push_back(getOrCreateVReg(*Arg));
712 return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
713 return getOrCreateVReg(*CI.getCalledValue());
717 Intrinsic::ID ID = F->getIntrinsicID();
718 if (TII && ID == Intrinsic::not_intrinsic)
719 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
721 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
723 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
726 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
727 MachineInstrBuilder MIB =
728 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
730 for (auto &Arg : CI.arg_operands()) {
731 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
732 MIB.addImm(CI->getSExtValue());
734 MIB.addUse(getOrCreateVReg(*Arg));
739 bool IRTranslator::translateInvoke(const User &U,
740 MachineIRBuilder &MIRBuilder) {
741 const InvokeInst &I = cast<InvokeInst>(U);
742 MCContext &Context = MF->getContext();
744 const BasicBlock *ReturnBB = I.getSuccessor(0);
745 const BasicBlock *EHPadBB = I.getSuccessor(1);
747 const Value *Callee(I.getCalledValue());
748 const Function *Fn = dyn_cast<Function>(Callee);
749 if (isa<InlineAsm>(Callee))
752 // FIXME: support invoking patchpoint and statepoint intrinsics.
753 if (Fn && Fn->isIntrinsic())
756 // FIXME: support whatever these are.
757 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
760 // FIXME: support Windows exception handling.
761 if (!isa<LandingPadInst>(EHPadBB->front()))
765 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
766 // the region covered by the try.
767 MCSymbol *BeginSymbol = Context.createTempSymbol();
768 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
770 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
771 SmallVector<unsigned, 8> Args;
772 for (auto &Arg: I.arg_operands())
773 Args.push_back(getOrCreateVReg(*Arg));
775 CLI->lowerCall(MIRBuilder, I, Res, Args,
776 [&]() { return getOrCreateVReg(*I.getCalledValue()); });
778 MCSymbol *EndSymbol = Context.createTempSymbol();
779 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
781 // FIXME: track probabilities.
782 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
783 &ReturnMBB = getOrCreateBB(*ReturnBB);
784 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
785 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
786 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
787 MIRBuilder.buildBr(ReturnMBB);
792 bool IRTranslator::translateLandingPad(const User &U,
793 MachineIRBuilder &MIRBuilder) {
794 const LandingPadInst &LP = cast<LandingPadInst>(U);
796 MachineBasicBlock &MBB = MIRBuilder.getMBB();
797 addLandingPadInfo(LP, MBB);
801 // If there aren't registers to copy the values into (e.g., during SjLj
802 // exceptions), then don't bother.
803 auto &TLI = *MF->getSubtarget().getTargetLowering();
804 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
805 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
806 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
809 // If landingpad's return type is token type, we don't create DAG nodes
810 // for its exception pointer and selector value. The extraction of exception
811 // pointer or selector value from token type landingpads is not currently
813 if (LP.getType()->isTokenTy())
816 // Add a label to mark the beginning of the landing pad. Deletion of the
817 // landing pad can thus be detected via the MachineModuleInfo.
818 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
819 .addSym(MF->addLandingPad(&MBB));
821 SmallVector<LLT, 2> Tys;
822 for (Type *Ty : cast<StructType>(LP.getType())->elements())
823 Tys.push_back(LLT{*Ty, *DL});
824 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
826 // Mark exception register as live in.
827 SmallVector<unsigned, 2> Regs;
828 SmallVector<uint64_t, 2> Offsets;
829 if (unsigned Reg = TLI.getExceptionPointerRegister(PersonalityFn)) {
831 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]);
832 MIRBuilder.buildCopy(VReg, Reg);
833 Regs.push_back(VReg);
834 Offsets.push_back(0);
837 if (unsigned Reg = TLI.getExceptionSelectorRegister(PersonalityFn)) {
840 // N.b. the exception selector register always has pointer type and may not
841 // match the actual IR-level type in the landingpad so an extra cast is
843 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
844 MIRBuilder.buildCopy(PtrVReg, Reg);
846 unsigned VReg = MRI->createGenericVirtualRegister(Tys[1]);
847 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT)
850 Regs.push_back(VReg);
851 Offsets.push_back(Tys[0].getSizeInBits());
854 MIRBuilder.buildSequence(getOrCreateVReg(LP), Regs, Offsets);
858 bool IRTranslator::translateAlloca(const User &U,
859 MachineIRBuilder &MIRBuilder) {
860 auto &AI = cast<AllocaInst>(U);
862 if (AI.isStaticAlloca()) {
863 unsigned Res = getOrCreateVReg(AI);
864 int FI = getOrCreateFrameIndex(AI);
865 MIRBuilder.buildFrameIndex(Res, FI);
869 // Now we're in the harder dynamic case.
870 Type *Ty = AI.getAllocatedType();
872 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
874 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
876 LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
877 if (MRI->getType(NumElts) != IntPtrTy) {
878 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
879 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
883 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
884 unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
885 MIRBuilder.buildConstant(TySize, -DL->getTypeAllocSize(Ty));
886 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
888 LLT PtrTy = LLT{*AI.getType(), *DL};
889 auto &TLI = *MF->getSubtarget().getTargetLowering();
890 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
892 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
893 MIRBuilder.buildCopy(SPTmp, SPReg);
895 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
896 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
898 // Handle alignment. We have to realign if the allocation granule was smaller
899 // than stack alignment, or the specific alloca requires more than stack
901 unsigned StackAlign =
902 MF->getSubtarget().getFrameLowering()->getStackAlignment();
903 Align = std::max(Align, StackAlign);
904 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
905 // Round the size of the allocation up to the stack alignment size
906 // by add SA-1 to the size. This doesn't overflow because we're computing
907 // an address inside an alloca.
908 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
909 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
910 AllocTmp = AlignedAlloc;
913 MIRBuilder.buildCopy(SPReg, AllocTmp);
914 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
916 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
917 assert(MF->getFrameInfo().hasVarSizedObjects());
921 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
922 // FIXME: We may need more info about the type. Because of how LLT works,
923 // we're completely discarding the i64/double distinction here (amongst
924 // others). Fortunately the ABIs I know of where that matters don't use va_arg
925 // anyway but that's not guaranteed.
926 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
927 .addDef(getOrCreateVReg(U))
928 .addUse(getOrCreateVReg(*U.getOperand(0)))
929 .addImm(DL->getABITypeAlignment(U.getType()));
933 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
934 const PHINode &PI = cast<PHINode>(U);
935 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
936 MIB.addDef(getOrCreateVReg(PI));
938 PendingPHIs.emplace_back(&PI, MIB.getInstr());
942 void IRTranslator::finishPendingPhis() {
943 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
944 const PHINode *PI = Phi.first;
945 MachineInstrBuilder MIB(*MF, Phi.second);
947 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
948 // won't create extra control flow here, otherwise we need to find the
949 // dominating predecessor here (or perhaps force the weirder IRTranslators
950 // to provide a simple boundary).
951 SmallSet<const BasicBlock *, 4> HandledPreds;
953 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
954 auto IRPred = PI->getIncomingBlock(i);
955 if (HandledPreds.count(IRPred))
958 HandledPreds.insert(IRPred);
959 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
960 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
961 assert(Pred->isSuccessor(MIB->getParent()) &&
962 "incorrect CFG at MachineBasicBlock level");
970 bool IRTranslator::translate(const Instruction &Inst) {
971 CurBuilder.setDebugLoc(Inst.getDebugLoc());
972 switch(Inst.getOpcode()) {
973 #define HANDLE_INST(NUM, OPCODE, CLASS) \
974 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
975 #include "llvm/IR/Instruction.def"
977 if (!TPC->isGlobalISelAbortEnabled())
979 llvm_unreachable("unknown opcode");
983 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
984 if (auto CI = dyn_cast<ConstantInt>(&C))
985 EntryBuilder.buildConstant(Reg, *CI);
986 else if (auto CF = dyn_cast<ConstantFP>(&C))
987 EntryBuilder.buildFConstant(Reg, *CF);
988 else if (isa<UndefValue>(C))
989 EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg);
990 else if (isa<ConstantPointerNull>(C))
991 EntryBuilder.buildConstant(Reg, 0);
992 else if (auto GV = dyn_cast<GlobalValue>(&C))
993 EntryBuilder.buildGlobalValue(Reg, GV);
994 else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
995 switch(CE->getOpcode()) {
996 #define HANDLE_INST(NUM, OPCODE, CLASS) \
997 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
998 #include "llvm/IR/Instruction.def"
1000 if (!TPC->isGlobalISelAbortEnabled())
1002 llvm_unreachable("unknown opcode");
1004 } else if (!TPC->isGlobalISelAbortEnabled())
1007 llvm_unreachable("unhandled constant kind");
1012 void IRTranslator::finalizeFunction() {
1013 // Release the memory used by the different maps we
1014 // needed during the translation.
1015 PendingPHIs.clear();
1017 FrameIndices.clear();
1019 MachinePreds.clear();
1022 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1024 const Function &F = *MF->getFunction();
1027 CLI = MF->getSubtarget().getCallLowering();
1028 CurBuilder.setMF(*MF);
1029 EntryBuilder.setMF(*MF);
1030 MRI = &MF->getRegInfo();
1031 DL = &F.getParent()->getDataLayout();
1032 TPC = &getAnalysis<TargetPassConfig>();
1033 ORE = make_unique<OptimizationRemarkEmitter>(&F);
1035 assert(PendingPHIs.empty() && "stale PHIs");
1037 // Release the per-function state when we return, whether we succeeded or not.
1038 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1040 // Setup a separate basic-block for the arguments and constants, falling
1041 // through to the IR-level Function's entry block.
1042 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1043 MF->push_back(EntryBB);
1044 EntryBB->addSuccessor(&getOrCreateBB(F.front()));
1045 EntryBuilder.setMBB(*EntryBB);
1047 // Lower the actual args into this basic block.
1048 SmallVector<unsigned, 8> VRegArgs;
1049 for (const Argument &Arg: F.args())
1050 VRegArgs.push_back(getOrCreateVReg(Arg));
1051 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
1052 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1053 MF->getFunction()->getSubprogram(),
1054 &MF->getFunction()->getEntryBlock());
1055 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1056 reportTranslationError(*MF, *TPC, *ORE, R);
1060 // And translate the function!
1061 for (const BasicBlock &BB: F) {
1062 MachineBasicBlock &MBB = getOrCreateBB(BB);
1063 // Set the insertion point of all the following translations to
1064 // the end of this basic block.
1065 CurBuilder.setMBB(MBB);
1067 for (const Instruction &Inst: BB) {
1068 if (translate(Inst))
1071 std::string InstStrStorage;
1072 raw_string_ostream InstStr(InstStrStorage);
1075 OptimizationRemarkMissed R("gisel-irtranslator", "IRTranslatorFailure: ",
1077 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1078 << ": '" << InstStr.str() << "'";
1079 reportTranslationError(*MF, *TPC, *ORE, R);
1084 finishPendingPhis();
1086 // Now that the MachineFrameInfo has been configured, no further changes to
1087 // the reserved registers are possible.
1088 MRI->freezeReservedRegs(*MF);
1090 // Merge the argument lowering and constants block with its single
1091 // successor, the LLVM-IR entry block. We want the basic block to
1093 assert(EntryBB->succ_size() == 1 &&
1094 "Custom BB used for lowering should have only one successor");
1095 // Get the successor of the current entry block.
1096 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1097 assert(NewEntryBB.pred_size() == 1 &&
1098 "LLVM-IR entry block has a predecessor!?");
1099 // Move all the instruction from the current entry block to the
1101 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1104 // Update the live-in information for the new entry block.
1105 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1106 NewEntryBB.addLiveIn(LiveIn);
1107 NewEntryBB.sortUniqueLiveIns();
1109 // Get rid of the now empty basic block.
1110 EntryBB->removeSuccessor(&NewEntryBB);
1111 MF->remove(EntryBB);
1112 MF->DeleteMachineBasicBlock(EntryBB);
1114 assert(&MF->front() == &NewEntryBB &&
1115 "New entry wasn't next in the list of basic block!");