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::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
175 // -0.0 - X --> G_FNEG
176 if (isa<Constant>(U.getOperand(0)) &&
177 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
178 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
179 .addDef(getOrCreateVReg(U))
180 .addUse(getOrCreateVReg(*U.getOperand(1)));
183 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
186 bool IRTranslator::translateCompare(const User &U,
187 MachineIRBuilder &MIRBuilder) {
188 const CmpInst *CI = dyn_cast<CmpInst>(&U);
189 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
190 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
191 unsigned Res = getOrCreateVReg(U);
192 CmpInst::Predicate Pred =
193 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
194 cast<ConstantExpr>(U).getPredicate());
196 if (CmpInst::isIntPredicate(Pred))
197 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
199 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
204 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
205 const ReturnInst &RI = cast<ReturnInst>(U);
206 const Value *Ret = RI.getReturnValue();
207 // The target may mess up with the insertion point, but
208 // this is not important as a return is the last instruction
209 // of the block anyway.
210 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
213 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
214 const BranchInst &BrInst = cast<BranchInst>(U);
216 if (!BrInst.isUnconditional()) {
217 // We want a G_BRCOND to the true BB followed by an unconditional branch.
218 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
219 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
220 MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
221 MIRBuilder.buildBrCond(Tst, TrueBB);
224 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
225 MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
226 MIRBuilder.buildBr(TgtBB);
229 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
230 for (const BasicBlock *Succ : BrInst.successors())
231 CurBB.addSuccessor(&getOrCreateBB(*Succ));
235 bool IRTranslator::translateSwitch(const User &U,
236 MachineIRBuilder &MIRBuilder) {
237 // For now, just translate as a chain of conditional branches.
238 // FIXME: could we share most of the logic/code in
239 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
240 // At first sight, it seems most of the logic in there is independent of
241 // SelectionDAG-specifics and a lot of work went in to optimize switch
242 // lowering in there.
244 const SwitchInst &SwInst = cast<SwitchInst>(U);
245 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
246 const BasicBlock *OrigBB = SwInst.getParent();
248 LLT LLTi1 = LLT(*Type::getInt1Ty(U.getContext()), *DL);
249 for (auto &CaseIt : SwInst.cases()) {
250 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
251 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
252 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
253 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
254 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
255 MachineBasicBlock &TrueMBB = getOrCreateBB(*TrueBB);
257 MIRBuilder.buildBrCond(Tst, TrueMBB);
258 CurMBB.addSuccessor(&TrueMBB);
259 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
261 MachineBasicBlock *FalseMBB =
262 MF->CreateMachineBasicBlock(SwInst.getParent());
263 MF->push_back(FalseMBB);
264 MIRBuilder.buildBr(*FalseMBB);
265 CurMBB.addSuccessor(FalseMBB);
267 MIRBuilder.setMBB(*FalseMBB);
269 // handle default case
270 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
271 MachineBasicBlock &DefaultMBB = getOrCreateBB(*DefaultBB);
272 MIRBuilder.buildBr(DefaultMBB);
273 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
274 CurMBB.addSuccessor(&DefaultMBB);
275 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
280 bool IRTranslator::translateIndirectBr(const User &U,
281 MachineIRBuilder &MIRBuilder) {
282 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
284 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
285 MIRBuilder.buildBrIndirect(Tgt);
288 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
289 for (const BasicBlock *Succ : BrInst.successors())
290 CurBB.addSuccessor(&getOrCreateBB(*Succ));
295 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
296 const LoadInst &LI = cast<LoadInst>(U);
298 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
299 : MachineMemOperand::MONone;
300 Flags |= MachineMemOperand::MOLoad;
302 unsigned Res = getOrCreateVReg(LI);
303 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
304 LLT VTy{*LI.getType(), *DL}, PTy{*LI.getPointerOperand()->getType(), *DL};
305 MIRBuilder.buildLoad(
307 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
308 Flags, DL->getTypeStoreSize(LI.getType()),
309 getMemOpAlignment(LI), AAMDNodes(), nullptr,
310 LI.getSynchScope(), LI.getOrdering()));
314 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
315 const StoreInst &SI = cast<StoreInst>(U);
316 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
317 : MachineMemOperand::MONone;
318 Flags |= MachineMemOperand::MOStore;
320 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
321 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
322 LLT VTy{*SI.getValueOperand()->getType(), *DL},
323 PTy{*SI.getPointerOperand()->getType(), *DL};
325 MIRBuilder.buildStore(
327 *MF->getMachineMemOperand(
328 MachinePointerInfo(SI.getPointerOperand()), Flags,
329 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
330 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
335 bool IRTranslator::translateExtractValue(const User &U,
336 MachineIRBuilder &MIRBuilder) {
337 const Value *Src = U.getOperand(0);
338 Type *Int32Ty = Type::getInt32Ty(U.getContext());
339 SmallVector<Value *, 1> Indices;
341 // getIndexedOffsetInType is designed for GEPs, so the first index is the
342 // usual array element rather than looking into the actual aggregate.
343 Indices.push_back(ConstantInt::get(Int32Ty, 0));
345 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
346 for (auto Idx : EVI->indices())
347 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
349 for (unsigned i = 1; i < U.getNumOperands(); ++i)
350 Indices.push_back(U.getOperand(i));
353 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
355 unsigned Res = getOrCreateVReg(U);
356 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
361 bool IRTranslator::translateInsertValue(const User &U,
362 MachineIRBuilder &MIRBuilder) {
363 const Value *Src = U.getOperand(0);
364 Type *Int32Ty = Type::getInt32Ty(U.getContext());
365 SmallVector<Value *, 1> Indices;
367 // getIndexedOffsetInType is designed for GEPs, so the first index is the
368 // usual array element rather than looking into the actual aggregate.
369 Indices.push_back(ConstantInt::get(Int32Ty, 0));
371 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
372 for (auto Idx : IVI->indices())
373 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
375 for (unsigned i = 2; i < U.getNumOperands(); ++i)
376 Indices.push_back(U.getOperand(i));
379 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
381 unsigned Res = getOrCreateVReg(U);
382 const Value &Inserted = *U.getOperand(1);
383 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
389 bool IRTranslator::translateSelect(const User &U,
390 MachineIRBuilder &MIRBuilder) {
391 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
392 getOrCreateVReg(*U.getOperand(1)),
393 getOrCreateVReg(*U.getOperand(2)));
397 bool IRTranslator::translateBitCast(const User &U,
398 MachineIRBuilder &MIRBuilder) {
399 if (LLT{*U.getOperand(0)->getType(), *DL} == LLT{*U.getType(), *DL}) {
400 unsigned &Reg = ValToVReg[&U];
402 MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0)));
404 Reg = getOrCreateVReg(*U.getOperand(0));
407 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
410 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
411 MachineIRBuilder &MIRBuilder) {
412 unsigned Op = getOrCreateVReg(*U.getOperand(0));
413 unsigned Res = getOrCreateVReg(U);
414 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
418 bool IRTranslator::translateGetElementPtr(const User &U,
419 MachineIRBuilder &MIRBuilder) {
420 // FIXME: support vector GEPs.
421 if (U.getType()->isVectorTy())
424 Value &Op0 = *U.getOperand(0);
425 unsigned BaseReg = getOrCreateVReg(Op0);
426 LLT PtrTy{*Op0.getType(), *DL};
427 unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
428 LLT OffsetTy = LLT::scalar(PtrSize);
431 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
433 const Value *Idx = GTI.getOperand();
434 if (StructType *StTy = GTI.getStructTypeOrNull()) {
435 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
436 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
439 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
441 // If this is a scalar constant or a splat vector of constants,
442 // handle it quickly.
443 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
444 Offset += ElementSize * CI->getSExtValue();
449 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
450 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
451 MIRBuilder.buildConstant(OffsetReg, Offset);
452 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
454 BaseReg = NewBaseReg;
458 // N = N + Idx * ElementSize;
459 unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
460 MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
462 unsigned IdxReg = getOrCreateVReg(*Idx);
463 if (MRI->getType(IdxReg) != OffsetTy) {
464 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
465 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
469 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
470 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
472 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
473 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
474 BaseReg = NewBaseReg;
479 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
480 MIRBuilder.buildConstant(OffsetReg, Offset);
481 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
485 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
489 bool IRTranslator::translateMemfunc(const CallInst &CI,
490 MachineIRBuilder &MIRBuilder,
492 LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL};
493 Type *DstTy = CI.getArgOperand(0)->getType();
494 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
495 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
498 SmallVector<CallLowering::ArgInfo, 8> Args;
499 for (int i = 0; i < 3; ++i) {
500 const auto &Arg = CI.getArgOperand(i);
501 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
506 case Intrinsic::memmove:
507 case Intrinsic::memcpy: {
508 Type *SrcTy = CI.getArgOperand(1)->getType();
509 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
511 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
514 case Intrinsic::memset:
521 return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
522 CallLowering::ArgInfo(0, CI.getType()), Args);
525 void IRTranslator::getStackGuard(unsigned DstReg,
526 MachineIRBuilder &MIRBuilder) {
527 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
528 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
529 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
532 auto &TLI = *MF->getSubtarget().getTargetLowering();
533 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
537 MachinePointerInfo MPInfo(Global);
538 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
539 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
540 MachineMemOperand::MODereferenceable;
542 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
543 DL->getPointerABIAlignment());
544 MIB.setMemRefs(MemRefs, MemRefs + 1);
547 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
548 MachineIRBuilder &MIRBuilder) {
549 LLT Ty{*CI.getOperand(0)->getType(), *DL};
550 LLT s1 = LLT::scalar(1);
551 unsigned Width = Ty.getSizeInBits();
552 unsigned Res = MRI->createGenericVirtualRegister(Ty);
553 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
554 auto MIB = MIRBuilder.buildInstr(Op)
557 .addUse(getOrCreateVReg(*CI.getOperand(0)))
558 .addUse(getOrCreateVReg(*CI.getOperand(1)));
560 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
561 unsigned Zero = MRI->createGenericVirtualRegister(s1);
562 EntryBuilder.buildConstant(Zero, 0);
566 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
570 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
571 MachineIRBuilder &MIRBuilder) {
575 case Intrinsic::lifetime_start:
576 case Intrinsic::lifetime_end:
577 // Stack coloring is not enabled in O0 (which we care about now) so we can
578 // drop these. Make sure someone notices when we start compiling at higher
580 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
583 case Intrinsic::dbg_declare: {
584 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
585 assert(DI.getVariable() && "Missing variable");
587 const Value *Address = DI.getAddress();
588 if (!Address || isa<UndefValue>(Address)) {
589 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
593 unsigned Reg = getOrCreateVReg(*Address);
594 auto RegDef = MRI->def_instr_begin(Reg);
595 assert(DI.getVariable()->isValidLocationForIntrinsic(
596 MIRBuilder.getDebugLoc()) &&
597 "Expected inlined-at fields to agree");
599 if (RegDef != MRI->def_instr_end() &&
600 RegDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
601 MIRBuilder.buildFIDbgValue(RegDef->getOperand(1).getIndex(),
602 DI.getVariable(), DI.getExpression());
604 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
607 case Intrinsic::vaend:
608 // No target I know of cares about va_end. Certainly no in-tree target
609 // does. Simplest intrinsic ever!
611 case Intrinsic::vastart: {
612 auto &TLI = *MF->getSubtarget().getTargetLowering();
613 Value *Ptr = CI.getArgOperand(0);
614 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
616 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
617 .addUse(getOrCreateVReg(*Ptr))
618 .addMemOperand(MF->getMachineMemOperand(
619 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
622 case Intrinsic::dbg_value: {
623 // This form of DBG_VALUE is target-independent.
624 const DbgValueInst &DI = cast<DbgValueInst>(CI);
625 const Value *V = DI.getValue();
626 assert(DI.getVariable()->isValidLocationForIntrinsic(
627 MIRBuilder.getDebugLoc()) &&
628 "Expected inlined-at fields to agree");
630 // Currently the optimizer can produce this; insert an undef to
631 // help debugging. Probably the optimizer should not do this.
632 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
634 } else if (const auto *CI = dyn_cast<Constant>(V)) {
635 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
638 unsigned Reg = getOrCreateVReg(*V);
639 // FIXME: This does not handle register-indirect values at offset 0. The
640 // direct/indirect thing shouldn't really be handled by something as
641 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
642 // pretty baked in right now.
643 if (DI.getOffset() != 0)
644 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
647 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
652 case Intrinsic::uadd_with_overflow:
653 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
654 case Intrinsic::sadd_with_overflow:
655 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
656 case Intrinsic::usub_with_overflow:
657 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
658 case Intrinsic::ssub_with_overflow:
659 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
660 case Intrinsic::umul_with_overflow:
661 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
662 case Intrinsic::smul_with_overflow:
663 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
665 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
666 .addDef(getOrCreateVReg(CI))
667 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
668 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
670 case Intrinsic::memcpy:
671 case Intrinsic::memmove:
672 case Intrinsic::memset:
673 return translateMemfunc(CI, MIRBuilder, ID);
674 case Intrinsic::eh_typeid_for: {
675 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
676 unsigned Reg = getOrCreateVReg(CI);
677 unsigned TypeID = MF->getTypeIDFor(GV);
678 MIRBuilder.buildConstant(Reg, TypeID);
681 case Intrinsic::objectsize: {
682 // If we don't know by now, we're never going to know.
683 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
685 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
688 case Intrinsic::stackguard:
689 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
691 case Intrinsic::stackprotector: {
692 LLT PtrTy{*CI.getArgOperand(0)->getType(), *DL};
693 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
694 getStackGuard(GuardVal, MIRBuilder);
696 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
697 MIRBuilder.buildStore(
698 GuardVal, getOrCreateVReg(*Slot),
699 *MF->getMachineMemOperand(
700 MachinePointerInfo::getFixedStack(*MF,
701 getOrCreateFrameIndex(*Slot)),
702 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
703 PtrTy.getSizeInBits() / 8, 8));
710 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
711 const CallInst &CI = cast<CallInst>(U);
712 auto TII = MF->getTarget().getIntrinsicInfo();
713 const Function *F = CI.getCalledFunction();
715 if (CI.isInlineAsm())
718 if (!F || !F->isIntrinsic()) {
719 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
720 SmallVector<unsigned, 8> Args;
721 for (auto &Arg: CI.arg_operands())
722 Args.push_back(getOrCreateVReg(*Arg));
724 return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
725 return getOrCreateVReg(*CI.getCalledValue());
729 Intrinsic::ID ID = F->getIntrinsicID();
730 if (TII && ID == Intrinsic::not_intrinsic)
731 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
733 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
735 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
738 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
739 MachineInstrBuilder MIB =
740 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
742 for (auto &Arg : CI.arg_operands()) {
743 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
744 MIB.addImm(CI->getSExtValue());
746 MIB.addUse(getOrCreateVReg(*Arg));
751 bool IRTranslator::translateInvoke(const User &U,
752 MachineIRBuilder &MIRBuilder) {
753 const InvokeInst &I = cast<InvokeInst>(U);
754 MCContext &Context = MF->getContext();
756 const BasicBlock *ReturnBB = I.getSuccessor(0);
757 const BasicBlock *EHPadBB = I.getSuccessor(1);
759 const Value *Callee(I.getCalledValue());
760 const Function *Fn = dyn_cast<Function>(Callee);
761 if (isa<InlineAsm>(Callee))
764 // FIXME: support invoking patchpoint and statepoint intrinsics.
765 if (Fn && Fn->isIntrinsic())
768 // FIXME: support whatever these are.
769 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
772 // FIXME: support Windows exception handling.
773 if (!isa<LandingPadInst>(EHPadBB->front()))
777 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
778 // the region covered by the try.
779 MCSymbol *BeginSymbol = Context.createTempSymbol();
780 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
782 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
783 SmallVector<unsigned, 8> Args;
784 for (auto &Arg: I.arg_operands())
785 Args.push_back(getOrCreateVReg(*Arg));
787 CLI->lowerCall(MIRBuilder, I, Res, Args,
788 [&]() { return getOrCreateVReg(*I.getCalledValue()); });
790 MCSymbol *EndSymbol = Context.createTempSymbol();
791 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
793 // FIXME: track probabilities.
794 MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
795 &ReturnMBB = getOrCreateBB(*ReturnBB);
796 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
797 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
798 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
799 MIRBuilder.buildBr(ReturnMBB);
804 bool IRTranslator::translateLandingPad(const User &U,
805 MachineIRBuilder &MIRBuilder) {
806 const LandingPadInst &LP = cast<LandingPadInst>(U);
808 MachineBasicBlock &MBB = MIRBuilder.getMBB();
809 addLandingPadInfo(LP, MBB);
813 // If there aren't registers to copy the values into (e.g., during SjLj
814 // exceptions), then don't bother.
815 auto &TLI = *MF->getSubtarget().getTargetLowering();
816 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
817 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
818 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
821 // If landingpad's return type is token type, we don't create DAG nodes
822 // for its exception pointer and selector value. The extraction of exception
823 // pointer or selector value from token type landingpads is not currently
825 if (LP.getType()->isTokenTy())
828 // Add a label to mark the beginning of the landing pad. Deletion of the
829 // landing pad can thus be detected via the MachineModuleInfo.
830 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
831 .addSym(MF->addLandingPad(&MBB));
833 SmallVector<LLT, 2> Tys;
834 for (Type *Ty : cast<StructType>(LP.getType())->elements())
835 Tys.push_back(LLT{*Ty, *DL});
836 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
838 // Mark exception register as live in.
839 SmallVector<unsigned, 2> Regs;
840 SmallVector<uint64_t, 2> Offsets;
841 if (unsigned Reg = TLI.getExceptionPointerRegister(PersonalityFn)) {
843 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]);
844 MIRBuilder.buildCopy(VReg, Reg);
845 Regs.push_back(VReg);
846 Offsets.push_back(0);
849 if (unsigned Reg = TLI.getExceptionSelectorRegister(PersonalityFn)) {
852 // N.b. the exception selector register always has pointer type and may not
853 // match the actual IR-level type in the landingpad so an extra cast is
855 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
856 MIRBuilder.buildCopy(PtrVReg, Reg);
858 unsigned VReg = MRI->createGenericVirtualRegister(Tys[1]);
859 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT)
862 Regs.push_back(VReg);
863 Offsets.push_back(Tys[0].getSizeInBits());
866 MIRBuilder.buildSequence(getOrCreateVReg(LP), Regs, Offsets);
870 bool IRTranslator::translateAlloca(const User &U,
871 MachineIRBuilder &MIRBuilder) {
872 auto &AI = cast<AllocaInst>(U);
874 if (AI.isStaticAlloca()) {
875 unsigned Res = getOrCreateVReg(AI);
876 int FI = getOrCreateFrameIndex(AI);
877 MIRBuilder.buildFrameIndex(Res, FI);
881 // Now we're in the harder dynamic case.
882 Type *Ty = AI.getAllocatedType();
884 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
886 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
888 LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
889 if (MRI->getType(NumElts) != IntPtrTy) {
890 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
891 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
895 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
896 unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
897 MIRBuilder.buildConstant(TySize, -DL->getTypeAllocSize(Ty));
898 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
900 LLT PtrTy = LLT{*AI.getType(), *DL};
901 auto &TLI = *MF->getSubtarget().getTargetLowering();
902 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
904 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
905 MIRBuilder.buildCopy(SPTmp, SPReg);
907 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
908 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
910 // Handle alignment. We have to realign if the allocation granule was smaller
911 // than stack alignment, or the specific alloca requires more than stack
913 unsigned StackAlign =
914 MF->getSubtarget().getFrameLowering()->getStackAlignment();
915 Align = std::max(Align, StackAlign);
916 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
917 // Round the size of the allocation up to the stack alignment size
918 // by add SA-1 to the size. This doesn't overflow because we're computing
919 // an address inside an alloca.
920 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
921 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
922 AllocTmp = AlignedAlloc;
925 MIRBuilder.buildCopy(SPReg, AllocTmp);
926 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
928 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
929 assert(MF->getFrameInfo().hasVarSizedObjects());
933 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
934 // FIXME: We may need more info about the type. Because of how LLT works,
935 // we're completely discarding the i64/double distinction here (amongst
936 // others). Fortunately the ABIs I know of where that matters don't use va_arg
937 // anyway but that's not guaranteed.
938 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
939 .addDef(getOrCreateVReg(U))
940 .addUse(getOrCreateVReg(*U.getOperand(0)))
941 .addImm(DL->getABITypeAlignment(U.getType()));
945 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
946 const PHINode &PI = cast<PHINode>(U);
947 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
948 MIB.addDef(getOrCreateVReg(PI));
950 PendingPHIs.emplace_back(&PI, MIB.getInstr());
954 void IRTranslator::finishPendingPhis() {
955 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
956 const PHINode *PI = Phi.first;
957 MachineInstrBuilder MIB(*MF, Phi.second);
959 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
960 // won't create extra control flow here, otherwise we need to find the
961 // dominating predecessor here (or perhaps force the weirder IRTranslators
962 // to provide a simple boundary).
963 SmallSet<const BasicBlock *, 4> HandledPreds;
965 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
966 auto IRPred = PI->getIncomingBlock(i);
967 if (HandledPreds.count(IRPred))
970 HandledPreds.insert(IRPred);
971 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
972 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
973 assert(Pred->isSuccessor(MIB->getParent()) &&
974 "incorrect CFG at MachineBasicBlock level");
982 bool IRTranslator::translate(const Instruction &Inst) {
983 CurBuilder.setDebugLoc(Inst.getDebugLoc());
984 switch(Inst.getOpcode()) {
985 #define HANDLE_INST(NUM, OPCODE, CLASS) \
986 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
987 #include "llvm/IR/Instruction.def"
989 if (!TPC->isGlobalISelAbortEnabled())
991 llvm_unreachable("unknown opcode");
995 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
996 if (auto CI = dyn_cast<ConstantInt>(&C))
997 EntryBuilder.buildConstant(Reg, *CI);
998 else if (auto CF = dyn_cast<ConstantFP>(&C))
999 EntryBuilder.buildFConstant(Reg, *CF);
1000 else if (isa<UndefValue>(C))
1001 EntryBuilder.buildUndef(Reg);
1002 else if (isa<ConstantPointerNull>(C))
1003 EntryBuilder.buildConstant(Reg, 0);
1004 else if (auto GV = dyn_cast<GlobalValue>(&C))
1005 EntryBuilder.buildGlobalValue(Reg, GV);
1006 else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1007 switch(CE->getOpcode()) {
1008 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1009 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
1010 #include "llvm/IR/Instruction.def"
1012 if (!TPC->isGlobalISelAbortEnabled())
1014 llvm_unreachable("unknown opcode");
1016 } else if (!TPC->isGlobalISelAbortEnabled())
1019 llvm_unreachable("unhandled constant kind");
1024 void IRTranslator::finalizeFunction() {
1025 // Release the memory used by the different maps we
1026 // needed during the translation.
1027 PendingPHIs.clear();
1029 FrameIndices.clear();
1031 MachinePreds.clear();
1034 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1036 const Function &F = *MF->getFunction();
1039 CLI = MF->getSubtarget().getCallLowering();
1040 CurBuilder.setMF(*MF);
1041 EntryBuilder.setMF(*MF);
1042 MRI = &MF->getRegInfo();
1043 DL = &F.getParent()->getDataLayout();
1044 TPC = &getAnalysis<TargetPassConfig>();
1045 ORE = make_unique<OptimizationRemarkEmitter>(&F);
1047 assert(PendingPHIs.empty() && "stale PHIs");
1049 // Release the per-function state when we return, whether we succeeded or not.
1050 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1052 // Setup a separate basic-block for the arguments and constants, falling
1053 // through to the IR-level Function's entry block.
1054 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1055 MF->push_back(EntryBB);
1056 EntryBB->addSuccessor(&getOrCreateBB(F.front()));
1057 EntryBuilder.setMBB(*EntryBB);
1059 // Lower the actual args into this basic block.
1060 SmallVector<unsigned, 8> VRegArgs;
1061 for (const Argument &Arg: F.args())
1062 VRegArgs.push_back(getOrCreateVReg(Arg));
1063 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
1064 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1065 MF->getFunction()->getSubprogram(),
1066 &MF->getFunction()->getEntryBlock());
1067 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1068 reportTranslationError(*MF, *TPC, *ORE, R);
1072 // And translate the function!
1073 for (const BasicBlock &BB: F) {
1074 MachineBasicBlock &MBB = getOrCreateBB(BB);
1075 // Set the insertion point of all the following translations to
1076 // the end of this basic block.
1077 CurBuilder.setMBB(MBB);
1079 for (const Instruction &Inst: BB) {
1080 if (translate(Inst))
1083 std::string InstStrStorage;
1084 raw_string_ostream InstStr(InstStrStorage);
1087 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1088 Inst.getDebugLoc(), &BB);
1089 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1090 << ": '" << InstStr.str() << "'";
1091 reportTranslationError(*MF, *TPC, *ORE, R);
1096 finishPendingPhis();
1098 // Now that the MachineFrameInfo has been configured, no further changes to
1099 // the reserved registers are possible.
1100 MRI->freezeReservedRegs(*MF);
1102 // Merge the argument lowering and constants block with its single
1103 // successor, the LLVM-IR entry block. We want the basic block to
1105 assert(EntryBB->succ_size() == 1 &&
1106 "Custom BB used for lowering should have only one successor");
1107 // Get the successor of the current entry block.
1108 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1109 assert(NewEntryBB.pred_size() == 1 &&
1110 "LLVM-IR entry block has a predecessor!?");
1111 // Move all the instruction from the current entry block to the
1113 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1116 // Update the live-in information for the new entry block.
1117 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1118 NewEntryBB.addLiveIn(LiveIn);
1119 NewEntryBB.sortUniqueLiveIns();
1121 // Get rid of the now empty basic block.
1122 EntryBB->removeSuccessor(&NewEntryBB);
1123 MF->remove(EntryBB);
1124 MF->DeleteMachineBasicBlock(EntryBB);
1126 assert(&MF->front() == &NewEntryBB &&
1127 "New entry wasn't next in the list of basic block!");