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/SmallSet.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
18 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/IR/Constant.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Target/TargetFrameLowering.h"
33 #include "llvm/Target/TargetIntrinsicInfo.h"
34 #include "llvm/Target/TargetLowering.h"
36 #define DEBUG_TYPE "irtranslator"
40 char IRTranslator::ID = 0;
41 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
43 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
44 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
47 static void reportTranslationError(MachineFunction &MF,
48 const TargetPassConfig &TPC,
49 OptimizationRemarkEmitter &ORE,
50 OptimizationRemarkMissed &R) {
51 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
53 // Print the function name explicitly if we don't have a debug location (which
54 // makes the diagnostic less useful) or if we're going to emit a raw error.
55 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
56 R << (" (in function: " + MF.getName() + ")").str();
58 if (TPC.isGlobalISelAbortEnabled())
59 report_fatal_error(R.getMsg());
64 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
65 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
68 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<TargetPassConfig>();
70 MachineFunctionPass::getAnalysisUsage(AU);
74 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
75 unsigned &ValReg = ValToVReg[&Val];
80 // Fill ValRegsSequence with the sequence of registers
81 // we need to concat together to produce the value.
82 assert(Val.getType()->isSized() &&
83 "Don't know how to create an empty vreg");
84 unsigned VReg = MRI->createGenericVirtualRegister(LLT{*Val.getType(), *DL});
87 if (auto CV = dyn_cast<Constant>(&Val)) {
88 bool Success = translate(*CV, VReg);
90 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
92 &MF->getFunction()->getEntryBlock());
93 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
94 reportTranslationError(*MF, *TPC, *ORE, R);
102 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
103 if (FrameIndices.find(&AI) != FrameIndices.end())
104 return FrameIndices[&AI];
106 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
108 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
110 // Always allocate at least one byte.
111 Size = std::max(Size, 1u);
113 unsigned Alignment = AI.getAlignment();
115 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
117 int &FI = FrameIndices[&AI];
118 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
122 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
123 unsigned Alignment = 0;
124 Type *ValTy = nullptr;
125 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
126 Alignment = SI->getAlignment();
127 ValTy = SI->getValueOperand()->getType();
128 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
129 Alignment = LI->getAlignment();
130 ValTy = LI->getType();
132 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
133 R << "unable to translate memop: " << ore::NV("Opcode", &I);
134 reportTranslationError(*MF, *TPC, *ORE, R);
138 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
141 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
142 MachineBasicBlock *&MBB = BBToMBB[&BB];
144 MBB = MF->CreateMachineBasicBlock(&BB);
147 if (BB.hasAddressTaken())
148 MBB->setHasAddressTaken();
153 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
154 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
155 MachinePreds[Edge].push_back(NewPred);
158 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
159 MachineIRBuilder &MIRBuilder) {
160 // FIXME: handle signed/unsigned wrapping flags.
162 // Get or create a virtual register for each value.
163 // Unless the value is a Constant => loadimm cst?
164 // or inline constant each time?
165 // Creation of a virtual register needs to have a size.
166 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
167 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
168 unsigned Res = getOrCreateVReg(U);
169 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
173 bool IRTranslator::translateCompare(const User &U,
174 MachineIRBuilder &MIRBuilder) {
175 const CmpInst *CI = dyn_cast<CmpInst>(&U);
176 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
177 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
178 unsigned Res = getOrCreateVReg(U);
179 CmpInst::Predicate Pred =
180 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
181 cast<ConstantExpr>(U).getPredicate());
183 if (CmpInst::isIntPredicate(Pred))
184 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
186 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
191 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
192 const ReturnInst &RI = cast<ReturnInst>(U);
193 const Value *Ret = RI.getReturnValue();
194 // The target may mess up with the insertion point, but
195 // this is not important as a return is the last instruction
196 // of the block anyway.
197 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
200 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
201 const BranchInst &BrInst = cast<BranchInst>(U);
203 if (!BrInst.isUnconditional()) {
204 // We want a G_BRCOND to the true BB followed by an unconditional branch.
205 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
206 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
207 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
208 MIRBuilder.buildBrCond(Tst, TrueBB);
211 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
212 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
213 MIRBuilder.buildBr(TgtBB);
216 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
217 for (const BasicBlock *Succ : BrInst.successors())
218 CurBB.addSuccessor(&getOrCreateBB(*Succ));
222 bool IRTranslator::translateSwitch(const User &U,
223 MachineIRBuilder &MIRBuilder) {
224 // For now, just translate as a chain of conditional branches.
225 // FIXME: could we share most of the logic/code in
226 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
227 // At first sight, it seems most of the logic in there is independent of
228 // SelectionDAG-specifics and a lot of work went in to optimize switch
229 // lowering in there.
231 const SwitchInst &SwInst = cast<SwitchInst>(U);
232 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
233 const BasicBlock *OrigBB = SwInst.getParent();
235 LLT LLTi1 = LLT(*Type::getInt1Ty(U.getContext()), *DL);
236 for (auto &CaseIt : SwInst.cases()) {
237 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
238 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
239 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
240 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
241 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
242 MachineBasicBlock &TrueMBB = getOrCreateBB(*TrueBB);
244 MIRBuilder.buildBrCond(Tst, TrueMBB);
245 CurMBB.addSuccessor(&TrueMBB);
246 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
248 MachineBasicBlock *FalseMBB =
249 MF->CreateMachineBasicBlock(SwInst.getParent());
250 MF->push_back(FalseMBB);
251 MIRBuilder.buildBr(*FalseMBB);
252 CurMBB.addSuccessor(FalseMBB);
254 MIRBuilder.setMBB(*FalseMBB);
256 // handle default case
257 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
258 MachineBasicBlock &DefaultMBB = getOrCreateBB(*DefaultBB);
259 MIRBuilder.buildBr(DefaultMBB);
260 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
261 CurMBB.addSuccessor(&DefaultMBB);
262 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
267 bool IRTranslator::translateIndirectBr(const User &U,
268 MachineIRBuilder &MIRBuilder) {
269 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
271 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
272 MIRBuilder.buildBrIndirect(Tgt);
275 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
276 for (const BasicBlock *Succ : BrInst.successors())
277 CurBB.addSuccessor(&getOrCreateBB(*Succ));
282 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
283 const LoadInst &LI = cast<LoadInst>(U);
285 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
286 : MachineMemOperand::MONone;
287 Flags |= MachineMemOperand::MOLoad;
289 unsigned Res = getOrCreateVReg(LI);
290 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
291 LLT VTy{*LI.getType(), *DL}, PTy{*LI.getPointerOperand()->getType(), *DL};
292 MIRBuilder.buildLoad(
294 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
295 Flags, DL->getTypeStoreSize(LI.getType()),
296 getMemOpAlignment(LI), AAMDNodes(), nullptr,
297 LI.getSynchScope(), LI.getOrdering()));
301 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
302 const StoreInst &SI = cast<StoreInst>(U);
303 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
304 : MachineMemOperand::MONone;
305 Flags |= MachineMemOperand::MOStore;
307 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
308 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
309 LLT VTy{*SI.getValueOperand()->getType(), *DL},
310 PTy{*SI.getPointerOperand()->getType(), *DL};
312 MIRBuilder.buildStore(
314 *MF->getMachineMemOperand(
315 MachinePointerInfo(SI.getPointerOperand()), Flags,
316 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
317 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
322 bool IRTranslator::translateExtractValue(const User &U,
323 MachineIRBuilder &MIRBuilder) {
324 const Value *Src = U.getOperand(0);
325 Type *Int32Ty = Type::getInt32Ty(U.getContext());
326 SmallVector<Value *, 1> Indices;
328 // getIndexedOffsetInType is designed for GEPs, so the first index is the
329 // usual array element rather than looking into the actual aggregate.
330 Indices.push_back(ConstantInt::get(Int32Ty, 0));
332 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
333 for (auto Idx : EVI->indices())
334 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
336 for (unsigned i = 1; i < U.getNumOperands(); ++i)
337 Indices.push_back(U.getOperand(i));
340 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
342 unsigned Res = getOrCreateVReg(U);
343 MIRBuilder.buildExtract(Res, Offset, getOrCreateVReg(*Src));
348 bool IRTranslator::translateInsertValue(const User &U,
349 MachineIRBuilder &MIRBuilder) {
350 const Value *Src = U.getOperand(0);
351 Type *Int32Ty = Type::getInt32Ty(U.getContext());
352 SmallVector<Value *, 1> Indices;
354 // getIndexedOffsetInType is designed for GEPs, so the first index is the
355 // usual array element rather than looking into the actual aggregate.
356 Indices.push_back(ConstantInt::get(Int32Ty, 0));
358 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
359 for (auto Idx : IVI->indices())
360 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
362 for (unsigned i = 2; i < U.getNumOperands(); ++i)
363 Indices.push_back(U.getOperand(i));
366 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
368 unsigned Res = getOrCreateVReg(U);
369 const Value &Inserted = *U.getOperand(1);
370 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
376 bool IRTranslator::translateSelect(const User &U,
377 MachineIRBuilder &MIRBuilder) {
378 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
379 getOrCreateVReg(*U.getOperand(1)),
380 getOrCreateVReg(*U.getOperand(2)));
384 bool IRTranslator::translateBitCast(const User &U,
385 MachineIRBuilder &MIRBuilder) {
386 if (LLT{*U.getOperand(0)->getType(), *DL} == LLT{*U.getType(), *DL}) {
387 unsigned &Reg = ValToVReg[&U];
389 MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0)));
391 Reg = getOrCreateVReg(*U.getOperand(0));
394 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
397 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
398 MachineIRBuilder &MIRBuilder) {
399 unsigned Op = getOrCreateVReg(*U.getOperand(0));
400 unsigned Res = getOrCreateVReg(U);
401 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
405 bool IRTranslator::translateGetElementPtr(const User &U,
406 MachineIRBuilder &MIRBuilder) {
407 // FIXME: support vector GEPs.
408 if (U.getType()->isVectorTy())
411 Value &Op0 = *U.getOperand(0);
412 unsigned BaseReg = getOrCreateVReg(Op0);
413 LLT PtrTy{*Op0.getType(), *DL};
414 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
415 LLT OffsetTy = LLT::scalar(PtrSize);
418 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
420 const Value *Idx = GTI.getOperand();
421 if (StructType *StTy = GTI.getStructTypeOrNull()) {
422 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
423 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
426 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
428 // If this is a scalar constant or a splat vector of constants,
429 // handle it quickly.
430 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
431 Offset += ElementSize * CI->getSExtValue();
436 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
437 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
438 MIRBuilder.buildConstant(OffsetReg, Offset);
439 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
441 BaseReg = NewBaseReg;
445 // N = N + Idx * ElementSize;
446 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
447 MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
449 unsigned IdxReg = getOrCreateVReg(*Idx);
450 if (MRI->getType(IdxReg) != OffsetTy) {
451 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
452 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
456 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
457 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
459 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
460 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
461 BaseReg = NewBaseReg;
466 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
467 MIRBuilder.buildConstant(OffsetReg, Offset);
468 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
472 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
476 bool IRTranslator::translateMemfunc(const CallInst &CI,
477 MachineIRBuilder &MIRBuilder,
479 LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL};
480 Type *DstTy = CI.getArgOperand(0)->getType();
481 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
482 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
485 SmallVector<CallLowering::ArgInfo, 8> Args;
486 for (int i = 0; i < 3; ++i) {
487 const auto &Arg = CI.getArgOperand(i);
488 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
493 case Intrinsic::memmove:
494 case Intrinsic::memcpy: {
495 Type *SrcTy = CI.getArgOperand(1)->getType();
496 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
498 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
501 case Intrinsic::memset:
508 return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
509 CallLowering::ArgInfo(0, CI.getType()), Args);
512 void IRTranslator::getStackGuard(unsigned DstReg,
513 MachineIRBuilder &MIRBuilder) {
514 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
515 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
516 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
519 auto &TLI = *MF->getSubtarget().getTargetLowering();
520 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
524 MachinePointerInfo MPInfo(Global);
525 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
526 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
527 MachineMemOperand::MODereferenceable;
529 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
530 DL->getPointerABIAlignment());
531 MIB.setMemRefs(MemRefs, MemRefs + 1);
534 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
535 MachineIRBuilder &MIRBuilder) {
536 LLT Ty{*CI.getOperand(0)->getType(), *DL};
537 LLT s1 = LLT::scalar(1);
538 unsigned Width = Ty.getSizeInBits();
539 unsigned Res = MRI->createGenericVirtualRegister(Ty);
540 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
541 auto MIB = MIRBuilder.buildInstr(Op)
544 .addUse(getOrCreateVReg(*CI.getOperand(0)))
545 .addUse(getOrCreateVReg(*CI.getOperand(1)));
547 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
548 unsigned Zero = MRI->createGenericVirtualRegister(s1);
549 EntryBuilder.buildConstant(Zero, 0);
553 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
557 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
558 MachineIRBuilder &MIRBuilder) {
562 case Intrinsic::lifetime_start:
563 case Intrinsic::lifetime_end:
564 // Stack coloring is not enabled in O0 (which we care about now) so we can
565 // drop these. Make sure someone notices when we start compiling at higher
567 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
570 case Intrinsic::dbg_declare: {
571 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
572 assert(DI.getVariable() && "Missing variable");
574 const Value *Address = DI.getAddress();
575 if (!Address || isa<UndefValue>(Address)) {
576 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
580 unsigned Reg = getOrCreateVReg(*Address);
581 auto RegDef = MRI->def_instr_begin(Reg);
582 assert(DI.getVariable()->isValidLocationForIntrinsic(
583 MIRBuilder.getDebugLoc()) &&
584 "Expected inlined-at fields to agree");
586 if (RegDef != MRI->def_instr_end() &&
587 RegDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
588 MIRBuilder.buildFIDbgValue(RegDef->getOperand(1).getIndex(),
589 DI.getVariable(), DI.getExpression());
591 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
594 case Intrinsic::vaend:
595 // No target I know of cares about va_end. Certainly no in-tree target
596 // does. Simplest intrinsic ever!
598 case Intrinsic::vastart: {
599 auto &TLI = *MF->getSubtarget().getTargetLowering();
600 Value *Ptr = CI.getArgOperand(0);
601 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
603 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
604 .addUse(getOrCreateVReg(*Ptr))
605 .addMemOperand(MF->getMachineMemOperand(
606 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
609 case Intrinsic::dbg_value: {
610 // This form of DBG_VALUE is target-independent.
611 const DbgValueInst &DI = cast<DbgValueInst>(CI);
612 const Value *V = DI.getValue();
613 assert(DI.getVariable()->isValidLocationForIntrinsic(
614 MIRBuilder.getDebugLoc()) &&
615 "Expected inlined-at fields to agree");
617 // Currently the optimizer can produce this; insert an undef to
618 // help debugging. Probably the optimizer should not do this.
619 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
621 } else if (const auto *CI = dyn_cast<Constant>(V)) {
622 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
625 unsigned Reg = getOrCreateVReg(*V);
626 // FIXME: This does not handle register-indirect values at offset 0. The
627 // direct/indirect thing shouldn't really be handled by something as
628 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
629 // pretty baked in right now.
630 if (DI.getOffset() != 0)
631 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
634 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
639 case Intrinsic::uadd_with_overflow:
640 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
641 case Intrinsic::sadd_with_overflow:
642 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
643 case Intrinsic::usub_with_overflow:
644 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
645 case Intrinsic::ssub_with_overflow:
646 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
647 case Intrinsic::umul_with_overflow:
648 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
649 case Intrinsic::smul_with_overflow:
650 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
652 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
653 .addDef(getOrCreateVReg(CI))
654 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
655 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
657 case Intrinsic::memcpy:
658 case Intrinsic::memmove:
659 case Intrinsic::memset:
660 return translateMemfunc(CI, MIRBuilder, ID);
661 case Intrinsic::eh_typeid_for: {
662 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
663 unsigned Reg = getOrCreateVReg(CI);
664 unsigned TypeID = MF->getTypeIDFor(GV);
665 MIRBuilder.buildConstant(Reg, TypeID);
668 case Intrinsic::objectsize: {
669 // If we don't know by now, we're never going to know.
670 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
672 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
675 case Intrinsic::stackguard:
676 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
678 case Intrinsic::stackprotector: {
679 LLT PtrTy{*CI.getArgOperand(0)->getType(), *DL};
680 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
681 getStackGuard(GuardVal, MIRBuilder);
683 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
684 MIRBuilder.buildStore(
685 GuardVal, getOrCreateVReg(*Slot),
686 *MF->getMachineMemOperand(
687 MachinePointerInfo::getFixedStack(*MF,
688 getOrCreateFrameIndex(*Slot)),
689 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
690 PtrTy.getSizeInBits() / 8, 8));
697 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
698 const CallInst &CI = cast<CallInst>(U);
699 auto TII = MF->getTarget().getIntrinsicInfo();
700 const Function *F = CI.getCalledFunction();
702 if (CI.isInlineAsm())
705 if (!F || !F->isIntrinsic()) {
706 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
707 SmallVector<unsigned, 8> Args;
708 for (auto &Arg: CI.arg_operands())
709 Args.push_back(getOrCreateVReg(*Arg));
711 return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
712 return getOrCreateVReg(*CI.getCalledValue());
716 Intrinsic::ID ID = F->getIntrinsicID();
717 if (TII && ID == Intrinsic::not_intrinsic)
718 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
720 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
722 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
725 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
726 MachineInstrBuilder MIB =
727 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
729 for (auto &Arg : CI.arg_operands()) {
730 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
731 MIB.addImm(CI->getSExtValue());
733 MIB.addUse(getOrCreateVReg(*Arg));
738 bool IRTranslator::translateInvoke(const User &U,
739 MachineIRBuilder &MIRBuilder) {
740 const InvokeInst &I = cast<InvokeInst>(U);
741 MCContext &Context = MF->getContext();
743 const BasicBlock *ReturnBB = I.getSuccessor(0);
744 const BasicBlock *EHPadBB = I.getSuccessor(1);
746 const Value *Callee(I.getCalledValue());
747 const Function *Fn = dyn_cast<Function>(Callee);
748 if (isa<InlineAsm>(Callee))
751 // FIXME: support invoking patchpoint and statepoint intrinsics.
752 if (Fn && Fn->isIntrinsic())
755 // FIXME: support whatever these are.
756 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
759 // FIXME: support Windows exception handling.
760 if (!isa<LandingPadInst>(EHPadBB->front()))
764 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
765 // the region covered by the try.
766 MCSymbol *BeginSymbol = Context.createTempSymbol();
767 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
769 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
770 SmallVector<unsigned, 8> Args;
771 for (auto &Arg: I.arg_operands())
772 Args.push_back(getOrCreateVReg(*Arg));
774 CLI->lowerCall(MIRBuilder, I, Res, Args,
775 [&]() { return getOrCreateVReg(*I.getCalledValue()); });
777 MCSymbol *EndSymbol = Context.createTempSymbol();
778 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
780 // FIXME: track probabilities.
781 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
782 &ReturnMBB = getOrCreateBB(*ReturnBB);
783 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
784 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
785 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
786 MIRBuilder.buildBr(ReturnMBB);
791 bool IRTranslator::translateLandingPad(const User &U,
792 MachineIRBuilder &MIRBuilder) {
793 const LandingPadInst &LP = cast<LandingPadInst>(U);
795 MachineBasicBlock &MBB = MIRBuilder.getMBB();
796 addLandingPadInfo(LP, MBB);
800 // If there aren't registers to copy the values into (e.g., during SjLj
801 // exceptions), then don't bother.
802 auto &TLI = *MF->getSubtarget().getTargetLowering();
803 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
804 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
805 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
808 // If landingpad's return type is token type, we don't create DAG nodes
809 // for its exception pointer and selector value. The extraction of exception
810 // pointer or selector value from token type landingpads is not currently
812 if (LP.getType()->isTokenTy())
815 // Add a label to mark the beginning of the landing pad. Deletion of the
816 // landing pad can thus be detected via the MachineModuleInfo.
817 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
818 .addSym(MF->addLandingPad(&MBB));
820 SmallVector<LLT, 2> Tys;
821 for (Type *Ty : cast<StructType>(LP.getType())->elements())
822 Tys.push_back(LLT{*Ty, *DL});
823 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
825 // Mark exception register as live in.
826 SmallVector<unsigned, 2> Regs;
827 SmallVector<uint64_t, 2> Offsets;
828 if (unsigned Reg = TLI.getExceptionPointerRegister(PersonalityFn)) {
830 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]);
831 MIRBuilder.buildCopy(VReg, Reg);
832 Regs.push_back(VReg);
833 Offsets.push_back(0);
836 if (unsigned Reg = TLI.getExceptionSelectorRegister(PersonalityFn)) {
839 // N.b. the exception selector register always has pointer type and may not
840 // match the actual IR-level type in the landingpad so an extra cast is
842 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
843 MIRBuilder.buildCopy(PtrVReg, Reg);
845 unsigned VReg = MRI->createGenericVirtualRegister(Tys[1]);
846 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT)
849 Regs.push_back(VReg);
850 Offsets.push_back(Tys[0].getSizeInBits());
853 MIRBuilder.buildSequence(getOrCreateVReg(LP), Regs, Offsets);
857 bool IRTranslator::translateAlloca(const User &U,
858 MachineIRBuilder &MIRBuilder) {
859 auto &AI = cast<AllocaInst>(U);
861 if (AI.isStaticAlloca()) {
862 unsigned Res = getOrCreateVReg(AI);
863 int FI = getOrCreateFrameIndex(AI);
864 MIRBuilder.buildFrameIndex(Res, FI);
868 // Now we're in the harder dynamic case.
869 Type *Ty = AI.getAllocatedType();
871 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
873 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
875 LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
876 if (MRI->getType(NumElts) != IntPtrTy) {
877 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
878 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
882 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
883 unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
884 MIRBuilder.buildConstant(TySize, -DL->getTypeAllocSize(Ty));
885 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
887 LLT PtrTy = LLT{*AI.getType(), *DL};
888 auto &TLI = *MF->getSubtarget().getTargetLowering();
889 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
891 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
892 MIRBuilder.buildCopy(SPTmp, SPReg);
894 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
895 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
897 // Handle alignment. We have to realign if the allocation granule was smaller
898 // than stack alignment, or the specific alloca requires more than stack
900 unsigned StackAlign =
901 MF->getSubtarget().getFrameLowering()->getStackAlignment();
902 Align = std::max(Align, StackAlign);
903 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
904 // Round the size of the allocation up to the stack alignment size
905 // by add SA-1 to the size. This doesn't overflow because we're computing
906 // an address inside an alloca.
907 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
908 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
909 AllocTmp = AlignedAlloc;
912 MIRBuilder.buildCopy(SPReg, AllocTmp);
913 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
915 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
916 assert(MF->getFrameInfo().hasVarSizedObjects());
920 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
921 // FIXME: We may need more info about the type. Because of how LLT works,
922 // we're completely discarding the i64/double distinction here (amongst
923 // others). Fortunately the ABIs I know of where that matters don't use va_arg
924 // anyway but that's not guaranteed.
925 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
926 .addDef(getOrCreateVReg(U))
927 .addUse(getOrCreateVReg(*U.getOperand(0)))
928 .addImm(DL->getABITypeAlignment(U.getType()));
932 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
933 const PHINode &PI = cast<PHINode>(U);
934 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
935 MIB.addDef(getOrCreateVReg(PI));
937 PendingPHIs.emplace_back(&PI, MIB.getInstr());
941 void IRTranslator::finishPendingPhis() {
942 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
943 const PHINode *PI = Phi.first;
944 MachineInstrBuilder MIB(*MF, Phi.second);
946 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
947 // won't create extra control flow here, otherwise we need to find the
948 // dominating predecessor here (or perhaps force the weirder IRTranslators
949 // to provide a simple boundary).
950 SmallSet<const BasicBlock *, 4> HandledPreds;
952 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
953 auto IRPred = PI->getIncomingBlock(i);
954 if (HandledPreds.count(IRPred))
957 HandledPreds.insert(IRPred);
958 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
959 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
960 assert(Pred->isSuccessor(MIB->getParent()) &&
961 "incorrect CFG at MachineBasicBlock level");
969 bool IRTranslator::translate(const Instruction &Inst) {
970 CurBuilder.setDebugLoc(Inst.getDebugLoc());
971 switch(Inst.getOpcode()) {
972 #define HANDLE_INST(NUM, OPCODE, CLASS) \
973 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
974 #include "llvm/IR/Instruction.def"
976 if (!TPC->isGlobalISelAbortEnabled())
978 llvm_unreachable("unknown opcode");
982 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
983 if (auto CI = dyn_cast<ConstantInt>(&C))
984 EntryBuilder.buildConstant(Reg, *CI);
985 else if (auto CF = dyn_cast<ConstantFP>(&C))
986 EntryBuilder.buildFConstant(Reg, *CF);
987 else if (isa<UndefValue>(C))
988 EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg);
989 else if (isa<ConstantPointerNull>(C))
990 EntryBuilder.buildConstant(Reg, 0);
991 else if (auto GV = dyn_cast<GlobalValue>(&C))
992 EntryBuilder.buildGlobalValue(Reg, GV);
993 else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
994 switch(CE->getOpcode()) {
995 #define HANDLE_INST(NUM, OPCODE, CLASS) \
996 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
997 #include "llvm/IR/Instruction.def"
999 if (!TPC->isGlobalISelAbortEnabled())
1001 llvm_unreachable("unknown opcode");
1003 } else if (!TPC->isGlobalISelAbortEnabled())
1006 llvm_unreachable("unhandled constant kind");
1011 void IRTranslator::finalizeFunction() {
1012 // Release the memory used by the different maps we
1013 // needed during the translation.
1014 PendingPHIs.clear();
1016 FrameIndices.clear();
1018 MachinePreds.clear();
1021 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1023 const Function &F = *MF->getFunction();
1026 CLI = MF->getSubtarget().getCallLowering();
1027 CurBuilder.setMF(*MF);
1028 EntryBuilder.setMF(*MF);
1029 MRI = &MF->getRegInfo();
1030 DL = &F.getParent()->getDataLayout();
1031 TPC = &getAnalysis<TargetPassConfig>();
1032 ORE = make_unique<OptimizationRemarkEmitter>(&F);
1034 assert(PendingPHIs.empty() && "stale PHIs");
1036 // Setup a separate basic-block for the arguments and constants, falling
1037 // through to the IR-level Function's entry block.
1038 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1039 MF->push_back(EntryBB);
1040 EntryBB->addSuccessor(&getOrCreateBB(F.front()));
1041 EntryBuilder.setMBB(*EntryBB);
1043 // Lower the actual args into this basic block.
1044 SmallVector<unsigned, 8> VRegArgs;
1045 for (const Argument &Arg: F.args())
1046 VRegArgs.push_back(getOrCreateVReg(Arg));
1047 bool Succeeded = CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs);
1049 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", DebugLoc(),
1050 &MF->getFunction()->getEntryBlock());
1051 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1052 reportTranslationError(*MF, *TPC, *ORE, R);
1057 // And translate the function!
1058 for (const BasicBlock &BB: F) {
1059 MachineBasicBlock &MBB = getOrCreateBB(BB);
1060 // Set the insertion point of all the following translations to
1061 // the end of this basic block.
1062 CurBuilder.setMBB(MBB);
1064 for (const Instruction &Inst: BB) {
1065 Succeeded &= translate(Inst);
1067 std::string InstStrStorage;
1068 raw_string_ostream InstStr(InstStrStorage);
1071 OptimizationRemarkMissed R("gisel-irtranslator", "IRTranslatorFailure: ",
1073 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1074 << ": '" << InstStr.str() << "'";
1075 reportTranslationError(*MF, *TPC, *ORE, R);
1082 finishPendingPhis();
1084 // Now that the MachineFrameInfo has been configured, no further changes to
1085 // the reserved registers are possible.
1086 MRI->freezeReservedRegs(*MF);
1088 // Merge the argument lowering and constants block with its single
1089 // successor, the LLVM-IR entry block. We want the basic block to
1091 assert(EntryBB->succ_size() == 1 &&
1092 "Custom BB used for lowering should have only one successor");
1093 // Get the successor of the current entry block.
1094 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1095 assert(NewEntryBB.pred_size() == 1 &&
1096 "LLVM-IR entry block has a predecessor!?");
1097 // Move all the instruction from the current entry block to the
1099 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1102 // Update the live-in information for the new entry block.
1103 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1104 NewEntryBB.addLiveIn(LiveIn);
1105 NewEntryBB.sortUniqueLiveIns();
1107 // Get rid of the now empty basic block.
1108 EntryBB->removeSuccessor(&NewEntryBB);
1109 MF->remove(EntryBB);
1110 MF->DeleteMachineBasicBlock(EntryBB);
1112 assert(&MF->front() == &NewEntryBB &&
1113 "New entry wasn't next in the list of basic block!");