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/CodeGen/TargetPassConfig.h"
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Type.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Target/TargetIntrinsicInfo.h"
27 #include "llvm/Target/TargetLowering.h"
28 
29 #define DEBUG_TYPE "irtranslator"
30 
31 using namespace llvm;
32 
33 char IRTranslator::ID = 0;
34 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
35                 false, false)
36 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
37 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
38                 false, false)
39 
40 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
41   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
42 }
43 
44 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
45   AU.addRequired<TargetPassConfig>();
46   MachineFunctionPass::getAnalysisUsage(AU);
47 }
48 
49 
50 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
51   unsigned &ValReg = ValToVReg[&Val];
52   // Check if this is the first time we see Val.
53   if (!ValReg) {
54     // Fill ValRegsSequence with the sequence of registers
55     // we need to concat together to produce the value.
56     assert(Val.getType()->isSized() &&
57            "Don't know how to create an empty vreg");
58     unsigned VReg = MRI->createGenericVirtualRegister(LLT{*Val.getType(), DL});
59     ValReg = VReg;
60 
61     if (auto CV = dyn_cast<Constant>(&Val)) {
62       bool Success = translate(*CV, VReg);
63       if (!Success) {
64         if (!TPC->isGlobalISelAbortEnabled()) {
65           MIRBuilder.getMF().getProperties().set(
66               MachineFunctionProperties::Property::FailedISel);
67           return 0;
68         }
69         report_fatal_error("unable to translate constant");
70       }
71     }
72   }
73   return ValReg;
74 }
75 
76 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
77   unsigned Alignment = 0;
78   Type *ValTy = nullptr;
79   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
80     Alignment = SI->getAlignment();
81     ValTy = SI->getValueOperand()->getType();
82   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
83     Alignment = LI->getAlignment();
84     ValTy = LI->getType();
85   } else if (!TPC->isGlobalISelAbortEnabled()) {
86     MIRBuilder.getMF().getProperties().set(
87         MachineFunctionProperties::Property::FailedISel);
88     return 1;
89   } else
90     llvm_unreachable("unhandled memory instruction");
91 
92   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
93 }
94 
95 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
96   MachineBasicBlock *&MBB = BBToMBB[&BB];
97   if (!MBB) {
98     MachineFunction &MF = MIRBuilder.getMF();
99     MBB = MF.CreateMachineBasicBlock();
100     MF.push_back(MBB);
101   }
102   return *MBB;
103 }
104 
105 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U) {
106   // FIXME: handle signed/unsigned wrapping flags.
107 
108   // Get or create a virtual register for each value.
109   // Unless the value is a Constant => loadimm cst?
110   // or inline constant each time?
111   // Creation of a virtual register needs to have a size.
112   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
113   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
114   unsigned Res = getOrCreateVReg(U);
115   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
116   return true;
117 }
118 
119 bool IRTranslator::translateCompare(const User &U) {
120   const CmpInst *CI = dyn_cast<CmpInst>(&U);
121   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
122   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
123   unsigned Res = getOrCreateVReg(U);
124   CmpInst::Predicate Pred =
125       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
126                                     cast<ConstantExpr>(U).getPredicate());
127 
128   if (CmpInst::isIntPredicate(Pred))
129     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
130   else
131     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
132 
133   return true;
134 }
135 
136 bool IRTranslator::translateRet(const User &U) {
137   const ReturnInst &RI = cast<ReturnInst>(U);
138   const Value *Ret = RI.getReturnValue();
139   // The target may mess up with the insertion point, but
140   // this is not important as a return is the last instruction
141   // of the block anyway.
142   return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
143 }
144 
145 bool IRTranslator::translateBr(const User &U) {
146   const BranchInst &BrInst = cast<BranchInst>(U);
147   unsigned Succ = 0;
148   if (!BrInst.isUnconditional()) {
149     // We want a G_BRCOND to the true BB followed by an unconditional branch.
150     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
151     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
152     MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
153     MIRBuilder.buildBrCond(Tst, TrueBB);
154   }
155 
156   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
157   MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
158   MIRBuilder.buildBr(TgtBB);
159 
160   // Link successors.
161   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
162   for (const BasicBlock *Succ : BrInst.successors())
163     CurBB.addSuccessor(&getOrCreateBB(*Succ));
164   return true;
165 }
166 
167 bool IRTranslator::translateLoad(const User &U) {
168   const LoadInst &LI = cast<LoadInst>(U);
169 
170   if (!TPC->isGlobalISelAbortEnabled() && !LI.isSimple())
171     return false;
172 
173   assert(LI.isSimple() && "only simple loads are supported at the moment");
174 
175   MachineFunction &MF = MIRBuilder.getMF();
176   unsigned Res = getOrCreateVReg(LI);
177   unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
178   LLT VTy{*LI.getType(), DL}, PTy{*LI.getPointerOperand()->getType()};
179 
180   MIRBuilder.buildLoad(
181       Res, Addr,
182       *MF.getMachineMemOperand(
183           MachinePointerInfo(LI.getPointerOperand()), MachineMemOperand::MOLoad,
184           DL->getTypeStoreSize(LI.getType()), getMemOpAlignment(LI)));
185   return true;
186 }
187 
188 bool IRTranslator::translateStore(const User &U) {
189   const StoreInst &SI = cast<StoreInst>(U);
190 
191   if (!TPC->isGlobalISelAbortEnabled() && !SI.isSimple())
192     return false;
193 
194   assert(SI.isSimple() && "only simple loads are supported at the moment");
195 
196   MachineFunction &MF = MIRBuilder.getMF();
197   unsigned Val = getOrCreateVReg(*SI.getValueOperand());
198   unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
199   LLT VTy{*SI.getValueOperand()->getType(), DL},
200       PTy{*SI.getPointerOperand()->getType()};
201 
202   MIRBuilder.buildStore(
203       Val, Addr,
204       *MF.getMachineMemOperand(
205           MachinePointerInfo(SI.getPointerOperand()),
206           MachineMemOperand::MOStore,
207           DL->getTypeStoreSize(SI.getValueOperand()->getType()),
208           getMemOpAlignment(SI)));
209   return true;
210 }
211 
212 bool IRTranslator::translateExtractValue(const User &U) {
213   const Value *Src = U.getOperand(0);
214   Type *Int32Ty = Type::getInt32Ty(U.getContext());
215   SmallVector<Value *, 1> Indices;
216 
217   // getIndexedOffsetInType is designed for GEPs, so the first index is the
218   // usual array element rather than looking into the actual aggregate.
219   Indices.push_back(ConstantInt::get(Int32Ty, 0));
220 
221   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
222     for (auto Idx : EVI->indices())
223       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
224   } else {
225     for (unsigned i = 1; i < U.getNumOperands(); ++i)
226       Indices.push_back(U.getOperand(i));
227   }
228 
229   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
230 
231   unsigned Res = getOrCreateVReg(U);
232   MIRBuilder.buildExtract(Res, Offset, getOrCreateVReg(*Src));
233 
234   return true;
235 }
236 
237 bool IRTranslator::translateInsertValue(const User &U) {
238   const Value *Src = U.getOperand(0);
239   Type *Int32Ty = Type::getInt32Ty(U.getContext());
240   SmallVector<Value *, 1> Indices;
241 
242   // getIndexedOffsetInType is designed for GEPs, so the first index is the
243   // usual array element rather than looking into the actual aggregate.
244   Indices.push_back(ConstantInt::get(Int32Ty, 0));
245 
246   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
247     for (auto Idx : IVI->indices())
248       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
249   } else {
250     for (unsigned i = 2; i < U.getNumOperands(); ++i)
251       Indices.push_back(U.getOperand(i));
252   }
253 
254   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
255 
256   unsigned Res = getOrCreateVReg(U);
257   const Value &Inserted = *U.getOperand(1);
258   MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
259                          Offset);
260 
261   return true;
262 }
263 
264 bool IRTranslator::translateSelect(const User &U) {
265   MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
266                          getOrCreateVReg(*U.getOperand(1)),
267                          getOrCreateVReg(*U.getOperand(2)));
268   return true;
269 }
270 
271 bool IRTranslator::translateBitCast(const User &U) {
272   if (LLT{*U.getOperand(0)->getType()} == LLT{*U.getType()}) {
273     unsigned &Reg = ValToVReg[&U];
274     if (Reg)
275       MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0)));
276     else
277       Reg = getOrCreateVReg(*U.getOperand(0));
278     return true;
279   }
280   return translateCast(TargetOpcode::G_BITCAST, U);
281 }
282 
283 bool IRTranslator::translateCast(unsigned Opcode, const User &U) {
284   unsigned Op = getOrCreateVReg(*U.getOperand(0));
285   unsigned Res = getOrCreateVReg(U);
286   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
287   return true;
288 }
289 
290 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI,
291                                            Intrinsic::ID ID) {
292   unsigned Op = 0;
293   switch (ID) {
294   default: return false;
295   case Intrinsic::uadd_with_overflow: Op = TargetOpcode::G_UADDE; break;
296   case Intrinsic::sadd_with_overflow: Op = TargetOpcode::G_SADDO; break;
297   case Intrinsic::usub_with_overflow: Op = TargetOpcode::G_USUBE; break;
298   case Intrinsic::ssub_with_overflow: Op = TargetOpcode::G_SSUBO; break;
299   case Intrinsic::umul_with_overflow: Op = TargetOpcode::G_UMULO; break;
300   case Intrinsic::smul_with_overflow: Op = TargetOpcode::G_SMULO; break;
301   }
302 
303   LLT Ty{*CI.getOperand(0)->getType()};
304   LLT s1 = LLT::scalar(1);
305   unsigned Width = Ty.getSizeInBits();
306   unsigned Res = MRI->createGenericVirtualRegister(Ty);
307   unsigned Overflow = MRI->createGenericVirtualRegister(s1);
308   auto MIB = MIRBuilder.buildInstr(Op)
309                  .addDef(Res)
310                  .addDef(Overflow)
311                  .addUse(getOrCreateVReg(*CI.getOperand(0)))
312                  .addUse(getOrCreateVReg(*CI.getOperand(1)));
313 
314   if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
315     unsigned Zero = MRI->createGenericVirtualRegister(s1);
316     EntryBuilder.buildConstant(Zero, 0);
317     MIB.addUse(Zero);
318   }
319 
320   MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
321   return true;
322 }
323 
324 bool IRTranslator::translateCall(const User &U) {
325   const CallInst &CI = cast<CallInst>(U);
326   auto TII = MIRBuilder.getMF().getTarget().getIntrinsicInfo();
327   const Function *F = CI.getCalledFunction();
328 
329   if (!F || !F->isIntrinsic()) {
330     // FIXME: handle multiple return values.
331     unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
332     SmallVector<unsigned, 8> Args;
333     for (auto &Arg: CI.arg_operands())
334       Args.push_back(getOrCreateVReg(*Arg));
335 
336     return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
337       return getOrCreateVReg(*CI.getCalledValue());
338     });
339   }
340 
341   Intrinsic::ID ID = F->getIntrinsicID();
342   if (TII && ID == Intrinsic::not_intrinsic)
343     ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
344 
345   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
346 
347   if (translateKnownIntrinsic(CI, ID))
348     return true;
349 
350   unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
351   MachineInstrBuilder MIB =
352       MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
353 
354   for (auto &Arg : CI.arg_operands()) {
355     if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
356       MIB.addImm(CI->getSExtValue());
357     else
358       MIB.addUse(getOrCreateVReg(*Arg));
359   }
360   return true;
361 }
362 
363 bool IRTranslator::translateStaticAlloca(const AllocaInst &AI) {
364   if (!TPC->isGlobalISelAbortEnabled() && !AI.isStaticAlloca())
365     return false;
366 
367   assert(AI.isStaticAlloca() && "only handle static allocas now");
368   MachineFunction &MF = MIRBuilder.getMF();
369   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
370   unsigned Size =
371       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
372 
373   // Always allocate at least one byte.
374   Size = std::max(Size, 1u);
375 
376   unsigned Alignment = AI.getAlignment();
377   if (!Alignment)
378     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
379 
380   unsigned Res = getOrCreateVReg(AI);
381   int FI = MF.getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
382   MIRBuilder.buildFrameIndex(Res, FI);
383   return true;
384 }
385 
386 bool IRTranslator::translatePHI(const User &U) {
387   const PHINode &PI = cast<PHINode>(U);
388   auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
389   MIB.addDef(getOrCreateVReg(PI));
390 
391   PendingPHIs.emplace_back(&PI, MIB.getInstr());
392   return true;
393 }
394 
395 void IRTranslator::finishPendingPhis() {
396   for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
397     const PHINode *PI = Phi.first;
398     MachineInstrBuilder MIB(MIRBuilder.getMF(), Phi.second);
399 
400     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
401     // won't create extra control flow here, otherwise we need to find the
402     // dominating predecessor here (or perhaps force the weirder IRTranslators
403     // to provide a simple boundary).
404     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
405       assert(BBToMBB[PI->getIncomingBlock(i)]->isSuccessor(MIB->getParent()) &&
406              "I appear to have misunderstood Machine PHIs");
407       MIB.addUse(getOrCreateVReg(*PI->getIncomingValue(i)));
408       MIB.addMBB(BBToMBB[PI->getIncomingBlock(i)]);
409     }
410   }
411 
412   PendingPHIs.clear();
413 }
414 
415 bool IRTranslator::translate(const Instruction &Inst) {
416   MIRBuilder.setDebugLoc(Inst.getDebugLoc());
417   switch(Inst.getOpcode()) {
418 #define HANDLE_INST(NUM, OPCODE, CLASS) \
419     case Instruction::OPCODE: return translate##OPCODE(Inst);
420 #include "llvm/IR/Instruction.def"
421   default:
422     if (!TPC->isGlobalISelAbortEnabled())
423       return false;
424     llvm_unreachable("unknown opcode");
425   }
426 }
427 
428 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
429   if (auto CI = dyn_cast<ConstantInt>(&C))
430     EntryBuilder.buildConstant(Reg, CI->getZExtValue());
431   else if (auto CF = dyn_cast<ConstantFP>(&C))
432     EntryBuilder.buildFConstant(Reg, *CF);
433   else if (isa<UndefValue>(C))
434     EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg);
435   else if (isa<ConstantPointerNull>(C))
436     EntryBuilder.buildInstr(TargetOpcode::G_CONSTANT)
437         .addDef(Reg)
438         .addImm(0);
439   else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
440     switch(CE->getOpcode()) {
441 #define HANDLE_INST(NUM, OPCODE, CLASS)                         \
442       case Instruction::OPCODE: return translate##OPCODE(*CE);
443 #include "llvm/IR/Instruction.def"
444     default:
445       if (!TPC->isGlobalISelAbortEnabled())
446         return false;
447       llvm_unreachable("unknown opcode");
448     }
449   } else if (!TPC->isGlobalISelAbortEnabled())
450     return false;
451   else
452     llvm_unreachable("unhandled constant kind");
453 
454   return true;
455 }
456 
457 
458 void IRTranslator::finalizeFunction() {
459   finishPendingPhis();
460 
461   // Release the memory used by the different maps we
462   // needed during the translation.
463   ValToVReg.clear();
464   Constants.clear();
465 }
466 
467 bool IRTranslator::runOnMachineFunction(MachineFunction &MF) {
468   const Function &F = *MF.getFunction();
469   if (F.empty())
470     return false;
471   CLI = MF.getSubtarget().getCallLowering();
472   MIRBuilder.setMF(MF);
473   EntryBuilder.setMF(MF);
474   MRI = &MF.getRegInfo();
475   DL = &F.getParent()->getDataLayout();
476   TPC = &getAnalysis<TargetPassConfig>();
477 
478   assert(PendingPHIs.empty() && "stale PHIs");
479 
480   // Setup the arguments.
481   MachineBasicBlock &MBB = getOrCreateBB(F.front());
482   MIRBuilder.setMBB(MBB);
483   SmallVector<unsigned, 8> VRegArgs;
484   for (const Argument &Arg: F.args())
485     VRegArgs.push_back(getOrCreateVReg(Arg));
486   bool Succeeded =
487       CLI->lowerFormalArguments(MIRBuilder, F.getArgumentList(), VRegArgs);
488   if (!Succeeded) {
489     if (!TPC->isGlobalISelAbortEnabled()) {
490       MIRBuilder.getMF().getProperties().set(
491           MachineFunctionProperties::Property::FailedISel);
492       return false;
493     }
494     report_fatal_error("Unable to lower arguments");
495   }
496 
497   // Now that we've got the ABI handling code, it's safe to set a location for
498   // any Constants we find in the IR.
499   if (MBB.empty())
500     EntryBuilder.setMBB(MBB);
501   else
502     EntryBuilder.setInstr(MBB.back(), /* Before */ false);
503 
504   for (const BasicBlock &BB: F) {
505     MachineBasicBlock &MBB = getOrCreateBB(BB);
506     // Set the insertion point of all the following translations to
507     // the end of this basic block.
508     MIRBuilder.setMBB(MBB);
509     for (const Instruction &Inst: BB) {
510       bool Succeeded = translate(Inst);
511       if (!Succeeded) {
512         DEBUG(dbgs() << "Cannot translate: " << Inst << '\n');
513         if (TPC->isGlobalISelAbortEnabled())
514           report_fatal_error("Unable to translate instruction");
515         MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
516         break;
517       }
518     }
519   }
520 
521   finalizeFunction();
522 
523   // Now that the MachineFrameInfo has been configured, no further changes to
524   // the reserved registers are possible.
525   MRI->freezeReservedRegs(MF);
526 
527   return false;
528 }
529