1 //===-- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator --*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements the IRTranslator class.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
14 
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Type.h"
24 #include "llvm/IR/Value.h"
25 #include "llvm/Target/TargetIntrinsicInfo.h"
26 #include "llvm/Target/TargetLowering.h"
27 
28 #define DEBUG_TYPE "irtranslator"
29 
30 using namespace llvm;
31 
32 char IRTranslator::ID = 0;
33 INITIALIZE_PASS(IRTranslator, "irtranslator", "IRTranslator LLVM IR -> MI",
34                 false, false)
35 
36 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
37   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
38 }
39 
40 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
41   unsigned &ValReg = ValToVReg[&Val];
42   // Check if this is the first time we see Val.
43   if (!ValReg) {
44     // Fill ValRegsSequence with the sequence of registers
45     // we need to concat together to produce the value.
46     assert(Val.getType()->isSized() &&
47            "Don't know how to create an empty vreg");
48     unsigned Size = DL->getTypeSizeInBits(Val.getType());
49     unsigned VReg = MRI->createGenericVirtualRegister(Size);
50     ValReg = VReg;
51 
52     if (auto CV = dyn_cast<Constant>(&Val)) {
53       bool Success = translate(*CV, VReg);
54       if (!Success)
55         report_fatal_error("unable to translate constant");
56     }
57   }
58   return ValReg;
59 }
60 
61 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
62   unsigned Alignment = 0;
63   Type *ValTy = nullptr;
64   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
65     Alignment = SI->getAlignment();
66     ValTy = SI->getValueOperand()->getType();
67   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
68     Alignment = LI->getAlignment();
69     ValTy = LI->getType();
70   } else
71     llvm_unreachable("unhandled memory instruction");
72 
73   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
74 }
75 
76 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
77   MachineBasicBlock *&MBB = BBToMBB[&BB];
78   if (!MBB) {
79     MachineFunction &MF = MIRBuilder.getMF();
80     MBB = MF.CreateMachineBasicBlock();
81     MF.push_back(MBB);
82   }
83   return *MBB;
84 }
85 
86 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U) {
87   // FIXME: handle signed/unsigned wrapping flags.
88 
89   // Get or create a virtual register for each value.
90   // Unless the value is a Constant => loadimm cst?
91   // or inline constant each time?
92   // Creation of a virtual register needs to have a size.
93   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
94   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
95   unsigned Res = getOrCreateVReg(U);
96   MIRBuilder.buildInstr(Opcode, LLT{*U.getType()})
97       .addDef(Res)
98       .addUse(Op0)
99       .addUse(Op1);
100   return true;
101 }
102 
103 bool IRTranslator::translateICmp(const User &U) {
104   const CmpInst &CI = cast<CmpInst>(U);
105   unsigned Op0 = getOrCreateVReg(*CI.getOperand(0));
106   unsigned Op1 = getOrCreateVReg(*CI.getOperand(1));
107   unsigned Res = getOrCreateVReg(CI);
108   CmpInst::Predicate Pred = CI.getPredicate();
109 
110   assert(isa<ICmpInst>(CI) && "only integer comparisons supported now");
111   assert(CmpInst::isIntPredicate(Pred) && "only int comparisons supported now");
112   MIRBuilder.buildICmp({LLT{*CI.getType()}, LLT{*CI.getOperand(0)->getType()}},
113                        Pred, Res, Op0, Op1);
114   return true;
115 }
116 
117 bool IRTranslator::translateRet(const User &U) {
118   const ReturnInst &RI = cast<ReturnInst>(U);
119   const Value *Ret = RI.getReturnValue();
120   // The target may mess up with the insertion point, but
121   // this is not important as a return is the last instruction
122   // of the block anyway.
123   return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
124 }
125 
126 bool IRTranslator::translateBr(const User &U) {
127   const BranchInst &BrInst = cast<BranchInst>(U);
128   unsigned Succ = 0;
129   if (!BrInst.isUnconditional()) {
130     // We want a G_BRCOND to the true BB followed by an unconditional branch.
131     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
132     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
133     MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
134     MIRBuilder.buildBrCond(LLT{*BrInst.getCondition()->getType()}, Tst, TrueBB);
135   }
136 
137   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
138   MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
139   MIRBuilder.buildBr(TgtBB);
140 
141   // Link successors.
142   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
143   for (const BasicBlock *Succ : BrInst.successors())
144     CurBB.addSuccessor(&getOrCreateBB(*Succ));
145   return true;
146 }
147 
148 bool IRTranslator::translateLoad(const User &U) {
149   const LoadInst &LI = cast<LoadInst>(U);
150   assert(LI.isSimple() && "only simple loads are supported at the moment");
151 
152   MachineFunction &MF = MIRBuilder.getMF();
153   unsigned Res = getOrCreateVReg(LI);
154   unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
155   LLT VTy{*LI.getType(), DL}, PTy{*LI.getPointerOperand()->getType()};
156 
157   MIRBuilder.buildLoad(
158       VTy, PTy, Res, Addr,
159       *MF.getMachineMemOperand(
160           MachinePointerInfo(LI.getPointerOperand()), MachineMemOperand::MOLoad,
161           DL->getTypeStoreSize(LI.getType()), getMemOpAlignment(LI)));
162   return true;
163 }
164 
165 bool IRTranslator::translateStore(const User &U) {
166   const StoreInst &SI = cast<StoreInst>(U);
167   assert(SI.isSimple() && "only simple loads are supported at the moment");
168 
169   MachineFunction &MF = MIRBuilder.getMF();
170   unsigned Val = getOrCreateVReg(*SI.getValueOperand());
171   unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
172   LLT VTy{*SI.getValueOperand()->getType(), DL},
173       PTy{*SI.getPointerOperand()->getType()};
174 
175   MIRBuilder.buildStore(
176       VTy, PTy, Val, Addr,
177       *MF.getMachineMemOperand(
178           MachinePointerInfo(SI.getPointerOperand()),
179           MachineMemOperand::MOStore,
180           DL->getTypeStoreSize(SI.getValueOperand()->getType()),
181           getMemOpAlignment(SI)));
182   return true;
183 }
184 
185 bool IRTranslator::translateBitCast(const User &U) {
186   if (LLT{*U.getOperand(0)->getType()} == LLT{*U.getType()}) {
187     unsigned &Reg = ValToVReg[&U];
188     if (Reg)
189       MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0)));
190     else
191       Reg = getOrCreateVReg(*U.getOperand(0));
192     return true;
193   }
194   return translateCast(TargetOpcode::G_BITCAST, U);
195 }
196 
197 bool IRTranslator::translateCast(unsigned Opcode, const User &U) {
198   unsigned Op = getOrCreateVReg(*U.getOperand(0));
199   unsigned Res = getOrCreateVReg(U);
200   MIRBuilder
201       .buildInstr(Opcode, {LLT{*U.getType()}, LLT{*U.getOperand(0)->getType()}})
202       .addDef(Res)
203       .addUse(Op);
204   return true;
205 }
206 
207 bool IRTranslator::translateCall(const User &U) {
208   const CallInst &CI = cast<CallInst>(U);
209   auto TII = MIRBuilder.getMF().getTarget().getIntrinsicInfo();
210   const Function *F = CI.getCalledFunction();
211 
212   if (!F || !F->isIntrinsic()) {
213     // FIXME: handle multiple return values.
214     unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
215     SmallVector<unsigned, 8> Args;
216     for (auto &Arg: CI.arg_operands())
217       Args.push_back(getOrCreateVReg(*Arg));
218 
219     return CLI->lowerCall(MIRBuilder, CI,
220                           F ? 0 : getOrCreateVReg(*CI.getCalledValue()), Res,
221                           Args);
222   }
223 
224   Intrinsic::ID ID = F->getIntrinsicID();
225   if (TII && ID == Intrinsic::not_intrinsic)
226     ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
227 
228   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
229 
230   // Need types (starting with return) & args.
231   SmallVector<LLT, 4> Tys;
232   Tys.emplace_back(*CI.getType());
233   for (auto &Arg : CI.arg_operands())
234     Tys.emplace_back(*Arg->getType());
235 
236   unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
237   MachineInstrBuilder MIB =
238       MIRBuilder.buildIntrinsic(Tys, ID, Res, !CI.doesNotAccessMemory());
239 
240   for (auto &Arg : CI.arg_operands()) {
241     if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
242       MIB.addImm(CI->getSExtValue());
243     else
244       MIB.addUse(getOrCreateVReg(*Arg));
245   }
246   return true;
247 }
248 
249 bool IRTranslator::translateStaticAlloca(const AllocaInst &AI) {
250   assert(AI.isStaticAlloca() && "only handle static allocas now");
251   MachineFunction &MF = MIRBuilder.getMF();
252   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
253   unsigned Size =
254       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
255 
256   // Always allocate at least one byte.
257   Size = std::max(Size, 1u);
258 
259   unsigned Alignment = AI.getAlignment();
260   if (!Alignment)
261     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
262 
263   unsigned Res = getOrCreateVReg(AI);
264   int FI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
265   MIRBuilder.buildFrameIndex(LLT::pointer(0), Res, FI);
266   return true;
267 }
268 
269 bool IRTranslator::translatePHI(const User &U) {
270   const PHINode &PI = cast<PHINode>(U);
271   MachineInstrBuilder MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
272   MIB.addDef(getOrCreateVReg(PI));
273 
274   PendingPHIs.emplace_back(&PI, MIB.getInstr());
275   return true;
276 }
277 
278 void IRTranslator::finishPendingPhis() {
279   for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
280     const PHINode *PI = Phi.first;
281     MachineInstrBuilder MIB(MIRBuilder.getMF(), Phi.second);
282 
283     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
284     // won't create extra control flow here, otherwise we need to find the
285     // dominating predecessor here (or perhaps force the weirder IRTranslators
286     // to provide a simple boundary).
287     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
288       assert(BBToMBB[PI->getIncomingBlock(i)]->isSuccessor(MIB->getParent()) &&
289              "I appear to have misunderstood Machine PHIs");
290       MIB.addUse(getOrCreateVReg(*PI->getIncomingValue(i)));
291       MIB.addMBB(BBToMBB[PI->getIncomingBlock(i)]);
292     }
293   }
294 
295   PendingPHIs.clear();
296 }
297 
298 bool IRTranslator::translate(const Instruction &Inst) {
299   MIRBuilder.setDebugLoc(Inst.getDebugLoc());
300   switch(Inst.getOpcode()) {
301 #define HANDLE_INST(NUM, OPCODE, CLASS) \
302     case Instruction::OPCODE: return translate##OPCODE(Inst);
303 #include "llvm/IR/Instruction.def"
304   default:
305     llvm_unreachable("unknown opcode");
306   }
307 }
308 
309 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
310   if (auto CI = dyn_cast<ConstantInt>(&C))
311     EntryBuilder.buildConstant(LLT{*CI->getType()}, Reg, CI->getZExtValue());
312   else if (isa<UndefValue>(C))
313     EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg);
314   else if (isa<ConstantPointerNull>(C))
315     EntryBuilder.buildInstr(TargetOpcode::G_CONSTANT, LLT{*C.getType()})
316         .addDef(Reg)
317         .addImm(0);
318   else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
319     switch(CE->getOpcode()) {
320 #define HANDLE_INST(NUM, OPCODE, CLASS)                         \
321       case Instruction::OPCODE: return translate##OPCODE(*CE);
322 #include "llvm/IR/Instruction.def"
323     default:
324       llvm_unreachable("unknown opcode");
325     }
326   } else
327     llvm_unreachable("unhandled constant kind");
328 
329   return true;
330 }
331 
332 
333 void IRTranslator::finalizeFunction() {
334   finishPendingPhis();
335 
336   // Release the memory used by the different maps we
337   // needed during the translation.
338   ValToVReg.clear();
339   Constants.clear();
340 }
341 
342 bool IRTranslator::runOnMachineFunction(MachineFunction &MF) {
343   const Function &F = *MF.getFunction();
344   if (F.empty())
345     return false;
346   CLI = MF.getSubtarget().getCallLowering();
347   MIRBuilder.setMF(MF);
348   EntryBuilder.setMF(MF);
349   MRI = &MF.getRegInfo();
350   DL = &F.getParent()->getDataLayout();
351 
352   assert(PendingPHIs.empty() && "stale PHIs");
353 
354   // Setup the arguments.
355   MachineBasicBlock &MBB = getOrCreateBB(F.front());
356   MIRBuilder.setMBB(MBB);
357   SmallVector<unsigned, 8> VRegArgs;
358   for (const Argument &Arg: F.args())
359     VRegArgs.push_back(getOrCreateVReg(Arg));
360   bool Succeeded =
361       CLI->lowerFormalArguments(MIRBuilder, F.getArgumentList(), VRegArgs);
362   if (!Succeeded)
363     report_fatal_error("Unable to lower arguments");
364 
365   // Now that we've got the ABI handling code, it's safe to set a location for
366   // any Constants we find in the IR.
367   if (MBB.empty())
368     EntryBuilder.setMBB(MBB);
369   else
370     EntryBuilder.setInstr(MBB.back(), /* Before */ false);
371 
372   for (const BasicBlock &BB: F) {
373     MachineBasicBlock &MBB = getOrCreateBB(BB);
374     // Set the insertion point of all the following translations to
375     // the end of this basic block.
376     MIRBuilder.setMBB(MBB);
377     for (const Instruction &Inst: BB) {
378       bool Succeeded = translate(Inst);
379       if (!Succeeded) {
380         DEBUG(dbgs() << "Cannot translate: " << Inst << '\n');
381         report_fatal_error("Unable to translate instruction");
382       }
383     }
384   }
385 
386   finalizeFunction();
387 
388   // Now that the MachineFrameInfo has been configured, no further changes to
389   // the reserved registers are possible.
390   MRI->freezeReservedRegs(MF);
391 
392   return false;
393 }
394