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/Type.h"
23 #include "llvm/IR/Value.h"
24 #include "llvm/Target/TargetLowering.h"
25 
26 #define DEBUG_TYPE "irtranslator"
27 
28 using namespace llvm;
29 
30 char IRTranslator::ID = 0;
31 INITIALIZE_PASS(IRTranslator, "irtranslator", "IRTranslator LLVM IR -> MI",
32                 false, false);
33 
34 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
35   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
36 }
37 
38 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
39   unsigned &ValReg = ValToVReg[&Val];
40   // Check if this is the first time we see Val.
41   if (!ValReg) {
42     // Fill ValRegsSequence with the sequence of registers
43     // we need to concat together to produce the value.
44     assert(Val.getType()->isSized() &&
45            "Don't know how to create an empty vreg");
46     assert(!Val.getType()->isAggregateType() && "Not yet implemented");
47     unsigned Size = DL->getTypeSizeInBits(Val.getType());
48     unsigned VReg = MRI->createGenericVirtualRegister(Size);
49     ValReg = VReg;
50     assert(!isa<Constant>(Val) && "Not yet implemented");
51   }
52   return ValReg;
53 }
54 
55 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
56   MachineBasicBlock *&MBB = BBToMBB[&BB];
57   if (!MBB) {
58     MachineFunction &MF = MIRBuilder.getMF();
59     MBB = MF.CreateMachineBasicBlock();
60     MF.push_back(MBB);
61   }
62   return *MBB;
63 }
64 
65 bool IRTranslator::translateBinaryOp(unsigned Opcode, const Instruction &Inst) {
66   // Get or create a virtual register for each value.
67   // Unless the value is a Constant => loadimm cst?
68   // or inline constant each time?
69   // Creation of a virtual register needs to have a size.
70   unsigned Op0 = getOrCreateVReg(*Inst.getOperand(0));
71   unsigned Op1 = getOrCreateVReg(*Inst.getOperand(1));
72   unsigned Res = getOrCreateVReg(Inst);
73   MIRBuilder.buildInstr(Opcode, LLT{*Inst.getType()}, Res, Op0, Op1);
74   return true;
75 }
76 
77 bool IRTranslator::translateReturn(const Instruction &Inst) {
78   assert(isa<ReturnInst>(Inst) && "Return expected");
79   const Value *Ret = cast<ReturnInst>(Inst).getReturnValue();
80   // The target may mess up with the insertion point, but
81   // this is not important as a return is the last instruction
82   // of the block anyway.
83   return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
84 }
85 
86 bool IRTranslator::translateBr(const Instruction &Inst) {
87   assert(isa<BranchInst>(Inst) && "Branch expected");
88   const BranchInst &BrInst = *cast<BranchInst>(&Inst);
89   if (BrInst.isUnconditional()) {
90     const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getOperand(0));
91     MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
92     MIRBuilder.buildInstr(TargetOpcode::G_BR, LLT{*BrTgt.getType()}, TgtBB);
93   } else {
94     assert(0 && "Not yet implemented");
95   }
96   // Link successors.
97   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
98   for (const BasicBlock *Succ : BrInst.successors())
99     CurBB.addSuccessor(&getOrCreateBB(*Succ));
100   return true;
101 }
102 
103 bool IRTranslator::translateStaticAlloca(const AllocaInst &AI) {
104   assert(AI.isStaticAlloca() && "only handle static allocas now");
105   MachineFunction &MF = MIRBuilder.getMF();
106   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
107   unsigned Size =
108       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
109 
110   unsigned Alignment = AI.getAlignment();
111   if (!Alignment)
112     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
113 
114   unsigned Res = getOrCreateVReg(AI);
115   int FI = MF.getFrameInfo()->CreateStackObject(Size, Alignment, false, &AI);
116   MIRBuilder.buildFrameIndex(LLT::pointer(0), Res, FI);
117   return true;
118 }
119 
120 bool IRTranslator::translate(const Instruction &Inst) {
121   MIRBuilder.setDebugLoc(Inst.getDebugLoc());
122   switch(Inst.getOpcode()) {
123   // Arithmetic operations.
124   case Instruction::Add:
125     return translateBinaryOp(TargetOpcode::G_ADD, Inst);
126   case Instruction::Sub:
127     return translateBinaryOp(TargetOpcode::G_SUB, Inst);
128 
129   // Bitwise operations.
130   case Instruction::And:
131     return translateBinaryOp(TargetOpcode::G_AND, Inst);
132   case Instruction::Or:
133     return translateBinaryOp(TargetOpcode::G_OR, Inst);
134 
135   // Branch operations.
136   case Instruction::Br:
137     return translateBr(Inst);
138   case Instruction::Ret:
139     return translateReturn(Inst);
140 
141   case Instruction::Alloca:
142     return translateStaticAlloca(cast<AllocaInst>(Inst));
143 
144   default:
145     llvm_unreachable("Opcode not supported");
146   }
147 }
148 
149 
150 void IRTranslator::finalize() {
151   // Release the memory used by the different maps we
152   // needed during the translation.
153   ValToVReg.clear();
154   Constants.clear();
155 }
156 
157 bool IRTranslator::runOnMachineFunction(MachineFunction &MF) {
158   const Function &F = *MF.getFunction();
159   if (F.empty())
160     return false;
161   CLI = MF.getSubtarget().getCallLowering();
162   MIRBuilder.setMF(MF);
163   MRI = &MF.getRegInfo();
164   DL = &F.getParent()->getDataLayout();
165 
166   // Setup the arguments.
167   MachineBasicBlock &MBB = getOrCreateBB(F.front());
168   MIRBuilder.setMBB(MBB);
169   SmallVector<unsigned, 8> VRegArgs;
170   for (const Argument &Arg: F.args())
171     VRegArgs.push_back(getOrCreateVReg(Arg));
172   bool Succeeded =
173       CLI->lowerFormalArguments(MIRBuilder, F.getArgumentList(), VRegArgs);
174   if (!Succeeded)
175     report_fatal_error("Unable to lower arguments");
176 
177   for (const BasicBlock &BB: F) {
178     MachineBasicBlock &MBB = getOrCreateBB(BB);
179     // Set the insertion point of all the following translations to
180     // the end of this basic block.
181     MIRBuilder.setMBB(MBB);
182     for (const Instruction &Inst: BB) {
183       bool Succeeded = translate(Inst);
184       if (!Succeeded) {
185         DEBUG(dbgs() << "Cannot translate: " << Inst << '\n');
186         report_fatal_error("Unable to translate instruction");
187       }
188     }
189   }
190 
191   // Now that the MachineFrameInfo has been configured, no further changes to
192   // the reserved registers are possible.
193   MRI->freezeReservedRegs(MF);
194 
195   return false;
196 }
197