blob: bb9f9d5267a440d254849c0b4628a89b7b341222 [file] [log] [blame]
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001//===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
Quentin Colombet105cf2b2016-01-20 20:58:56 +00002//
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"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000014#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +000015#include "llvm/ADT/ScopeExit.h"
Tim Northoverb6636fd2017-01-17 22:13:50 +000016#include "llvm/ADT/SmallSet.h"
Quentin Colombetfd9d0a02016-02-11 19:59:41 +000017#include "llvm/ADT/SmallVector.h"
Adam Nemet0965da22017-10-09 23:19:02 +000018#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Tim Northovera9105be2016-11-09 22:39:54 +000019#include "llvm/CodeGen/Analysis.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000020#include "llvm/CodeGen/GlobalISel/CallLowering.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000021#include "llvm/CodeGen/LowLevelType.h"
22#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northoverbd505462016-07-22 16:59:52 +000023#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000025#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineMemOperand.h"
27#include "llvm/CodeGen/MachineOperand.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000029#include "llvm/CodeGen/TargetFrameLowering.h"
30#include "llvm/CodeGen/TargetLowering.h"
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000031#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000032#include "llvm/CodeGen/TargetRegisterInfo.h"
33#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000034#include "llvm/IR/BasicBlock.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000035#include "llvm/IR/Constant.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000036#include "llvm/IR/Constants.h"
37#include "llvm/IR/DataLayout.h"
Tim Northover09aac4a2017-01-26 23:39:14 +000038#include "llvm/IR/DebugInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000039#include "llvm/IR/DerivedTypes.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000040#include "llvm/IR/Function.h"
Tim Northovera7653b32016-09-12 11:20:22 +000041#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000042#include "llvm/IR/InlineAsm.h"
43#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instructions.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000045#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000046#include "llvm/IR/Intrinsics.h"
47#include "llvm/IR/LLVMContext.h"
48#include "llvm/IR/Metadata.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000049#include "llvm/IR/Type.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000050#include "llvm/IR/User.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000051#include "llvm/IR/Value.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000052#include "llvm/MC/MCContext.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/CodeGen.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/ErrorHandling.h"
58#include "llvm/Support/LowLevelTypeImpl.h"
59#include "llvm/Support/MathExtras.h"
60#include "llvm/Support/raw_ostream.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000061#include "llvm/Target/TargetIntrinsicInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000062#include "llvm/Target/TargetMachine.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000063#include <algorithm>
64#include <cassert>
65#include <cstdint>
66#include <iterator>
67#include <string>
68#include <utility>
69#include <vector>
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000070
71#define DEBUG_TYPE "irtranslator"
72
Quentin Colombet105cf2b2016-01-20 20:58:56 +000073using namespace llvm;
74
75char IRTranslator::ID = 0;
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000076
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000077INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
78 false, false)
79INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
80INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
Tim Northover884b47e2016-07-26 03:29:18 +000081 false, false)
Quentin Colombet105cf2b2016-01-20 20:58:56 +000082
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000083static void reportTranslationError(MachineFunction &MF,
84 const TargetPassConfig &TPC,
85 OptimizationRemarkEmitter &ORE,
86 OptimizationRemarkMissed &R) {
87 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
88
89 // Print the function name explicitly if we don't have a debug location (which
90 // makes the diagnostic less useful) or if we're going to emit a raw error.
91 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
92 R << (" (in function: " + MF.getName() + ")").str();
93
94 if (TPC.isGlobalISelAbortEnabled())
95 report_fatal_error(R.getMsg());
96 else
97 ORE.emit(R);
Tim Northover60f23492016-11-08 01:12:17 +000098}
99
Eugene Zelenko76bf48d2017-06-26 22:44:03 +0000100IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
Quentin Colombet39293d32016-03-08 01:38:55 +0000101 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
Quentin Colombeta7fae162016-02-11 17:53:23 +0000102}
103
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000104void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
105 AU.addRequired<TargetPassConfig>();
106 MachineFunctionPass::getAnalysisUsage(AU);
107}
108
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000109static void computeValueLLTs(const DataLayout &DL, Type &Ty,
110 SmallVectorImpl<LLT> &ValueTys,
111 SmallVectorImpl<uint64_t> *Offsets = nullptr,
112 uint64_t StartingOffset = 0) {
113 // Given a struct type, recursively traverse the elements.
114 if (StructType *STy = dyn_cast<StructType>(&Ty)) {
115 const StructLayout *SL = DL.getStructLayout(STy);
116 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
117 computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
118 StartingOffset + SL->getElementOffset(I));
119 return;
120 }
121 // Given an array type, recursively traverse the elements.
122 if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
123 Type *EltTy = ATy->getElementType();
124 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
125 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
126 computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
127 StartingOffset + i * EltSize);
128 return;
129 }
130 // Interpret void as zero return values.
131 if (Ty.isVoidTy())
132 return;
133 // Base case: we can get an LLT for this LLVM IR type.
134 ValueTys.push_back(getLLTForType(Ty, DL));
135 if (Offsets != nullptr)
136 Offsets->push_back(StartingOffset * 8);
137}
Tim Northover5ed648e2016-08-09 21:28:04 +0000138
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000139IRTranslator::ValueToVRegInfo::VRegListT &
140IRTranslator::allocateVRegs(const Value &Val) {
141 assert(!VMap.contains(Val) && "Value already allocated in VMap");
142 auto *Regs = VMap.getVRegs(Val);
143 auto *Offsets = VMap.getOffsets(Val);
144 SmallVector<LLT, 4> SplitTys;
145 computeValueLLTs(*DL, *Val.getType(), SplitTys,
146 Offsets->empty() ? Offsets : nullptr);
147 for (unsigned i = 0; i < SplitTys.size(); ++i)
148 Regs->push_back(0);
149 return *Regs;
150}
Tim Northover9e35f1e2017-01-25 20:58:22 +0000151
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000152ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
153 auto VRegsIt = VMap.findVRegs(Val);
154 if (VRegsIt != VMap.vregs_end())
155 return *VRegsIt->second;
156
157 if (Val.getType()->isVoidTy())
158 return *VMap.getVRegs(Val);
159
160 // Create entry for this type.
161 auto *VRegs = VMap.getVRegs(Val);
162 auto *Offsets = VMap.getOffsets(Val);
163
Tim Northover9e35f1e2017-01-25 20:58:22 +0000164 assert(Val.getType()->isSized() &&
165 "Don't know how to create an empty vreg");
Tim Northover9e35f1e2017-01-25 20:58:22 +0000166
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000167 SmallVector<LLT, 4> SplitTys;
168 computeValueLLTs(*DL, *Val.getType(), SplitTys,
169 Offsets->empty() ? Offsets : nullptr);
170
171 if (!isa<Constant>(Val)) {
172 for (auto Ty : SplitTys)
173 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
174 return *VRegs;
175 }
176
177 if (Val.getType()->isAggregateType()) {
178 // UndefValue, ConstantAggregateZero
179 auto &C = cast<Constant>(Val);
180 unsigned Idx = 0;
181 while (auto Elt = C.getAggregateElement(Idx++)) {
182 auto EltRegs = getOrCreateVRegs(*Elt);
183 std::copy(EltRegs.begin(), EltRegs.end(), std::back_inserter(*VRegs));
184 }
185 } else {
186 assert(SplitTys.size() == 1 && "unexpectedly split LLT");
187 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
188 bool Success = translate(cast<Constant>(Val), VRegs->front());
Tim Northover9e35f1e2017-01-25 20:58:22 +0000189 if (!Success) {
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000190 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +0000191 MF->getFunction().getSubprogram(),
192 &MF->getFunction().getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000193 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
194 reportTranslationError(*MF, *TPC, *ORE, R);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000195 return *VRegs;
Tim Northover5ed648e2016-08-09 21:28:04 +0000196 }
Quentin Colombet17c494b2016-02-11 17:51:31 +0000197 }
Tim Northover7f3ad2e2017-01-20 23:25:17 +0000198
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000199 return *VRegs;
Quentin Colombet17c494b2016-02-11 17:51:31 +0000200}
201
Tim Northovercdf23f12016-10-31 18:30:59 +0000202int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
203 if (FrameIndices.find(&AI) != FrameIndices.end())
204 return FrameIndices[&AI];
205
Tim Northovercdf23f12016-10-31 18:30:59 +0000206 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
207 unsigned Size =
208 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
209
210 // Always allocate at least one byte.
211 Size = std::max(Size, 1u);
212
213 unsigned Alignment = AI.getAlignment();
214 if (!Alignment)
215 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
216
217 int &FI = FrameIndices[&AI];
Tim Northover50db7f412016-12-07 21:17:47 +0000218 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
Tim Northovercdf23f12016-10-31 18:30:59 +0000219 return FI;
220}
221
Tim Northoverad2b7172016-07-26 20:23:26 +0000222unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
223 unsigned Alignment = 0;
224 Type *ValTy = nullptr;
225 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
226 Alignment = SI->getAlignment();
227 ValTy = SI->getValueOperand()->getType();
228 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
229 Alignment = LI->getAlignment();
230 ValTy = LI->getType();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000231 } else {
232 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
233 R << "unable to translate memop: " << ore::NV("Opcode", &I);
234 reportTranslationError(*MF, *TPC, *ORE, R);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000235 return 1;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000236 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000237
238 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
239}
240
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000241MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
Quentin Colombet53237a92016-03-11 17:27:43 +0000242 MachineBasicBlock *&MBB = BBToMBB[&BB];
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000243 assert(MBB && "BasicBlock was not encountered before");
Quentin Colombet17c494b2016-02-11 17:51:31 +0000244 return *MBB;
245}
246
Tim Northoverb6636fd2017-01-17 22:13:50 +0000247void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
248 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
249 MachinePreds[Edge].push_back(NewPred);
250}
251
Tim Northoverc53606e2016-12-07 21:29:15 +0000252bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
253 MachineIRBuilder &MIRBuilder) {
Tim Northover0d56e052016-07-29 18:11:21 +0000254 // FIXME: handle signed/unsigned wrapping flags.
255
Quentin Colombet2ecff3b2016-02-10 22:59:27 +0000256 // Get or create a virtual register for each value.
257 // Unless the value is a Constant => loadimm cst?
258 // or inline constant each time?
259 // Creation of a virtual register needs to have a size.
Tim Northover357f1be2016-08-10 23:02:41 +0000260 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
261 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
262 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000263 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
Quentin Colombet17c494b2016-02-11 17:51:31 +0000264 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000265}
266
Volkan Keles20d3c422017-03-07 18:03:28 +0000267bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
268 // -0.0 - X --> G_FNEG
269 if (isa<Constant>(U.getOperand(0)) &&
270 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
271 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
272 .addDef(getOrCreateVReg(U))
273 .addUse(getOrCreateVReg(*U.getOperand(1)));
274 return true;
275 }
276 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
277}
278
Tim Northoverc53606e2016-12-07 21:29:15 +0000279bool IRTranslator::translateCompare(const User &U,
280 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000281 const CmpInst *CI = dyn_cast<CmpInst>(&U);
282 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
283 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
284 unsigned Res = getOrCreateVReg(U);
285 CmpInst::Predicate Pred =
286 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
287 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000288 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000289 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000290 else if (Pred == CmpInst::FCMP_FALSE)
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000291 MIRBuilder.buildCopy(
292 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
293 else if (Pred == CmpInst::FCMP_TRUE)
294 MIRBuilder.buildCopy(
295 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000296 else
Tim Northover0f140c72016-09-09 11:46:34 +0000297 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000298
Tim Northoverde3aea0412016-08-17 20:25:25 +0000299 return true;
300}
301
Tim Northoverc53606e2016-12-07 21:29:15 +0000302bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000303 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000304 const Value *Ret = RI.getReturnValue();
Amara Emersond78d65c2017-11-30 20:06:02 +0000305 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
306 Ret = nullptr;
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000307 // The target may mess up with the insertion point, but
308 // this is not important as a return is the last instruction
309 // of the block anyway.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000310
311 // FIXME: this interface should simplify when CallLowering gets adapted to
312 // multiple VRegs per Value.
313 unsigned VReg = Ret ? packRegs(*Ret, MIRBuilder) : 0;
314 return CLI->lowerReturn(MIRBuilder, Ret, VReg);
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000315}
316
Tim Northoverc53606e2016-12-07 21:29:15 +0000317bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000318 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000319 unsigned Succ = 0;
320 if (!BrInst.isUnconditional()) {
321 // We want a G_BRCOND to the true BB followed by an unconditional branch.
322 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
323 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000324 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000325 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000326 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000327
328 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000329 MachineBasicBlock &TgtBB = getMBB(BrTgt);
Ahmed Bougachae8e1fa32017-03-21 23:42:50 +0000330 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
331
332 // If the unconditional target is the layout successor, fallthrough.
333 if (!CurBB.isLayoutSuccessor(&TgtBB))
334 MIRBuilder.buildBr(TgtBB);
Tim Northover69c2ba52016-07-29 17:58:00 +0000335
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000336 // Link successors.
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000337 for (const BasicBlock *Succ : BrInst.successors())
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000338 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000339 return true;
340}
341
Kristof Beylseced0712017-01-05 11:28:51 +0000342bool IRTranslator::translateSwitch(const User &U,
343 MachineIRBuilder &MIRBuilder) {
344 // For now, just translate as a chain of conditional branches.
345 // FIXME: could we share most of the logic/code in
346 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
347 // At first sight, it seems most of the logic in there is independent of
348 // SelectionDAG-specifics and a lot of work went in to optimize switch
349 // lowering in there.
350
351 const SwitchInst &SwInst = cast<SwitchInst>(U);
352 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000353 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000354
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000355 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000356 for (auto &CaseIt : SwInst.cases()) {
357 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
358 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
359 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000360 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
361 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000362 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000363
Tim Northoverb6636fd2017-01-17 22:13:50 +0000364 MIRBuilder.buildBrCond(Tst, TrueMBB);
365 CurMBB.addSuccessor(&TrueMBB);
366 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000367
Tim Northoverb6636fd2017-01-17 22:13:50 +0000368 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000369 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000370 // Insert the comparison blocks one after the other.
371 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000372 MIRBuilder.buildBr(*FalseMBB);
373 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000374
Tim Northoverb6636fd2017-01-17 22:13:50 +0000375 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000376 }
377 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000378 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000379 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000380 MIRBuilder.buildBr(DefaultMBB);
381 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
382 CurMBB.addSuccessor(&DefaultMBB);
383 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000384
385 return true;
386}
387
Kristof Beyls65a12c02017-01-30 09:13:18 +0000388bool IRTranslator::translateIndirectBr(const User &U,
389 MachineIRBuilder &MIRBuilder) {
390 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
391
392 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
393 MIRBuilder.buildBrIndirect(Tgt);
394
395 // Link successors.
396 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
397 for (const BasicBlock *Succ : BrInst.successors())
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000398 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000399
400 return true;
401}
402
Tim Northoverc53606e2016-12-07 21:29:15 +0000403bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000404 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000405
Tim Northover7152dca2016-10-19 15:55:06 +0000406 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
407 : MachineMemOperand::MONone;
408 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000409
Amara Emersond78d65c2017-11-30 20:06:02 +0000410 if (DL->getTypeStoreSize(LI.getType()) == 0)
411 return true;
412
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000413 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
414 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
415 unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000416
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000417 for (unsigned i = 0; i < Regs.size(); ++i) {
418 unsigned Addr = 0;
419 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
420
421 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
422 unsigned BaseAlign = getMemOpAlignment(LI);
423 auto MMO = MF->getMachineMemOperand(
424 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
425 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
426 LI.getSyncScopeID(), LI.getOrdering());
427 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
428 }
429
Tim Northoverad2b7172016-07-26 20:23:26 +0000430 return true;
431}
432
Tim Northoverc53606e2016-12-07 21:29:15 +0000433bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000434 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000435 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
436 : MachineMemOperand::MONone;
437 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000438
Amara Emersond78d65c2017-11-30 20:06:02 +0000439 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
440 return true;
441
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000442 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
443 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
444 unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000445
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000446 for (unsigned i = 0; i < Vals.size(); ++i) {
447 unsigned Addr = 0;
448 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
449
450 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
451 unsigned BaseAlign = getMemOpAlignment(SI);
452 auto MMO = MF->getMachineMemOperand(
453 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
454 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
455 SI.getSyncScopeID(), SI.getOrdering());
456 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
457 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000458 return true;
459}
460
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000461static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
Tim Northoverb6046222016-08-19 20:09:03 +0000462 const Value *Src = U.getOperand(0);
463 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Volkan Keles6a36c642017-05-19 09:47:02 +0000464
Tim Northover6f80b082016-08-19 17:47:05 +0000465 // getIndexedOffsetInType is designed for GEPs, so the first index is the
466 // usual array element rather than looking into the actual aggregate.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000467 SmallVector<Value *, 1> Indices;
Tim Northover6f80b082016-08-19 17:47:05 +0000468 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000469
470 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
471 for (auto Idx : EVI->indices())
472 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000473 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
474 for (auto Idx : IVI->indices())
475 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Tim Northoverb6046222016-08-19 20:09:03 +0000476 } else {
477 for (unsigned i = 1; i < U.getNumOperands(); ++i)
478 Indices.push_back(U.getOperand(i));
479 }
Tim Northover6f80b082016-08-19 17:47:05 +0000480
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000481 return 8 * static_cast<uint64_t>(
482 DL.getIndexedOffsetInType(Src->getType(), Indices));
483}
Tim Northover6f80b082016-08-19 17:47:05 +0000484
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000485bool IRTranslator::translateExtractValue(const User &U,
486 MachineIRBuilder &MIRBuilder) {
487 const Value *Src = U.getOperand(0);
488 uint64_t Offset = getOffsetFromIndices(U, *DL);
489 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
490 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
491 unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
492 Offsets.begin();
493 auto &DstRegs = allocateVRegs(U);
494
495 for (unsigned i = 0; i < DstRegs.size(); ++i)
496 DstRegs[i] = SrcRegs[Idx++];
Tim Northover6f80b082016-08-19 17:47:05 +0000497
498 return true;
499}
500
Tim Northoverc53606e2016-12-07 21:29:15 +0000501bool IRTranslator::translateInsertValue(const User &U,
502 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000503 const Value *Src = U.getOperand(0);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000504 uint64_t Offset = getOffsetFromIndices(U, *DL);
505 auto &DstRegs = allocateVRegs(U);
506 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
507 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
508 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
509 auto InsertedIt = InsertedRegs.begin();
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000510
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000511 for (unsigned i = 0; i < DstRegs.size(); ++i) {
512 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
513 DstRegs[i] = *InsertedIt++;
514 else
515 DstRegs[i] = SrcRegs[i];
Tim Northoverb6046222016-08-19 20:09:03 +0000516 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000517
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000518 return true;
519}
520
Tim Northoverc53606e2016-12-07 21:29:15 +0000521bool IRTranslator::translateSelect(const User &U,
522 MachineIRBuilder &MIRBuilder) {
Kristof Beyls7a713502017-04-19 06:38:37 +0000523 unsigned Tst = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000524 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
525 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
526 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
527
528 for (unsigned i = 0; i < ResRegs.size(); ++i)
529 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i]);
530
Tim Northover5a28c362016-08-19 20:09:07 +0000531 return true;
532}
533
Tim Northoverc53606e2016-12-07 21:29:15 +0000534bool IRTranslator::translateBitCast(const User &U,
535 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000536 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000537 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
538 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000539 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000540 auto &Regs = *VMap.getVRegs(U);
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000541 // If we already assigned a vreg for this bitcast, we can't change that.
542 // Emit a copy to satisfy the users we already emitted.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000543 if (!Regs.empty())
544 MIRBuilder.buildCopy(Regs[0], SrcReg);
545 else {
546 Regs.push_back(SrcReg);
547 VMap.getOffsets(U)->push_back(0);
548 }
Tim Northover7c9eba92016-07-25 21:01:29 +0000549 return true;
550 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000551 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000552}
553
Tim Northoverc53606e2016-12-07 21:29:15 +0000554bool IRTranslator::translateCast(unsigned Opcode, const User &U,
555 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000556 unsigned Op = getOrCreateVReg(*U.getOperand(0));
557 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000558 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
Tim Northover7c9eba92016-07-25 21:01:29 +0000559 return true;
560}
561
Tim Northoverc53606e2016-12-07 21:29:15 +0000562bool IRTranslator::translateGetElementPtr(const User &U,
563 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000564 // FIXME: support vector GEPs.
565 if (U.getType()->isVectorTy())
566 return false;
567
568 Value &Op0 = *U.getOperand(0);
569 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000570 Type *PtrIRTy = Op0.getType();
571 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
572 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
573 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000574
575 int64_t Offset = 0;
576 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
577 GTI != E; ++GTI) {
578 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000579 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000580 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
581 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
582 continue;
583 } else {
584 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
585
586 // If this is a scalar constant or a splat vector of constants,
587 // handle it quickly.
588 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
589 Offset += ElementSize * CI->getSExtValue();
590 continue;
591 }
592
593 if (Offset != 0) {
594 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000595 unsigned OffsetReg =
596 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000597 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
598
599 BaseReg = NewBaseReg;
600 Offset = 0;
601 }
602
Tim Northovera7653b32016-09-12 11:20:22 +0000603 unsigned IdxReg = getOrCreateVReg(*Idx);
604 if (MRI->getType(IdxReg) != OffsetTy) {
605 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
606 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
607 IdxReg = NewIdxReg;
608 }
609
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000610 // N = N + Idx * ElementSize;
611 // Avoid doing it for ElementSize of 1.
612 unsigned GepOffsetReg;
613 if (ElementSize != 1) {
614 unsigned ElementSizeReg =
615 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
616
617 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
618 MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
619 } else
620 GepOffsetReg = IdxReg;
Tim Northovera7653b32016-09-12 11:20:22 +0000621
622 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000623 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
Tim Northovera7653b32016-09-12 11:20:22 +0000624 BaseReg = NewBaseReg;
625 }
626 }
627
628 if (Offset != 0) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000629 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000630 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
631 return true;
632 }
633
634 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
635 return true;
636}
637
Tim Northover79f43f12017-01-30 19:33:07 +0000638bool IRTranslator::translateMemfunc(const CallInst &CI,
639 MachineIRBuilder &MIRBuilder,
640 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000641 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000642 Type *DstTy = CI.getArgOperand(0)->getType();
643 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000644 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
645 return false;
646
647 SmallVector<CallLowering::ArgInfo, 8> Args;
648 for (int i = 0; i < 3; ++i) {
649 const auto &Arg = CI.getArgOperand(i);
650 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
651 }
652
Tim Northover79f43f12017-01-30 19:33:07 +0000653 const char *Callee;
654 switch (ID) {
655 case Intrinsic::memmove:
656 case Intrinsic::memcpy: {
657 Type *SrcTy = CI.getArgOperand(1)->getType();
658 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
659 return false;
660 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
661 break;
662 }
663 case Intrinsic::memset:
664 Callee = "memset";
665 break;
666 default:
667 return false;
668 }
Tim Northover3f186032016-10-18 20:03:45 +0000669
Diana Picusd79253a2017-03-20 14:40:18 +0000670 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
671 MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000672 CallLowering::ArgInfo(0, CI.getType()), Args);
673}
Tim Northovera7653b32016-09-12 11:20:22 +0000674
Tim Northoverc53606e2016-12-07 21:29:15 +0000675void IRTranslator::getStackGuard(unsigned DstReg,
676 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000677 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
678 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000679 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
680 MIB.addDef(DstReg);
681
Tim Northover50db7f412016-12-07 21:17:47 +0000682 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +0000683 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000684 if (!Global)
685 return;
686
687 MachinePointerInfo MPInfo(Global);
Tim Northover50db7f412016-12-07 21:17:47 +0000688 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
Tim Northovercdf23f12016-10-31 18:30:59 +0000689 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
690 MachineMemOperand::MODereferenceable;
691 *MemRefs =
Tim Northover50db7f412016-12-07 21:17:47 +0000692 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
Fangrui Songe73534462017-11-15 06:17:32 +0000693 DL->getPointerABIAlignment(0));
Tim Northovercdf23f12016-10-31 18:30:59 +0000694 MIB.setMemRefs(MemRefs, MemRefs + 1);
695}
696
Tim Northover1e656ec2016-12-08 22:44:00 +0000697bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
698 MachineIRBuilder &MIRBuilder) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000699 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
Tim Northover1e656ec2016-12-08 22:44:00 +0000700 auto MIB = MIRBuilder.buildInstr(Op)
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000701 .addDef(ResRegs[0])
702 .addDef(ResRegs[1])
Tim Northover1e656ec2016-12-08 22:44:00 +0000703 .addUse(getOrCreateVReg(*CI.getOperand(0)))
704 .addUse(getOrCreateVReg(*CI.getOperand(1)));
705
706 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000707 unsigned Zero = getOrCreateVReg(
708 *Constant::getNullValue(Type::getInt1Ty(CI.getContext())));
Tim Northover1e656ec2016-12-08 22:44:00 +0000709 MIB.addUse(Zero);
710 }
711
Tim Northover1e656ec2016-12-08 22:44:00 +0000712 return true;
713}
714
Tim Northoverc53606e2016-12-07 21:29:15 +0000715bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
716 MachineIRBuilder &MIRBuilder) {
Tim Northover91c81732016-08-19 17:17:06 +0000717 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000718 default:
719 break;
Tim Northover0e011702017-02-10 19:10:38 +0000720 case Intrinsic::lifetime_start:
721 case Intrinsic::lifetime_end:
722 // Stack coloring is not enabled in O0 (which we care about now) so we can
723 // drop these. Make sure someone notices when we start compiling at higher
724 // opts though.
725 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
726 return false;
727 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000728 case Intrinsic::dbg_declare: {
729 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
730 assert(DI.getVariable() && "Missing variable");
731
732 const Value *Address = DI.getAddress();
733 if (!Address || isa<UndefValue>(Address)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000734 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Tim Northover09aac4a2017-01-26 23:39:14 +0000735 return true;
736 }
737
Tim Northover09aac4a2017-01-26 23:39:14 +0000738 assert(DI.getVariable()->isValidLocationForIntrinsic(
739 MIRBuilder.getDebugLoc()) &&
740 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000741 auto AI = dyn_cast<AllocaInst>(Address);
742 if (AI && AI->isStaticAlloca()) {
743 // Static allocas are tracked at the MF level, no need for DBG_VALUE
744 // instructions (in fact, they get ignored if they *do* exist).
745 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
746 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Tim Northover09aac4a2017-01-26 23:39:14 +0000747 } else
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000748 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
749 DI.getVariable(), DI.getExpression());
Tim Northoverb58346f2016-12-08 22:44:13 +0000750 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000751 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000752 case Intrinsic::vaend:
753 // No target I know of cares about va_end. Certainly no in-tree target
754 // does. Simplest intrinsic ever!
755 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000756 case Intrinsic::vastart: {
757 auto &TLI = *MF->getSubtarget().getTargetLowering();
758 Value *Ptr = CI.getArgOperand(0);
759 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
760
761 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
762 .addUse(getOrCreateVReg(*Ptr))
763 .addMemOperand(MF->getMachineMemOperand(
764 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
765 return true;
766 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000767 case Intrinsic::dbg_value: {
768 // This form of DBG_VALUE is target-independent.
769 const DbgValueInst &DI = cast<DbgValueInst>(CI);
770 const Value *V = DI.getValue();
771 assert(DI.getVariable()->isValidLocationForIntrinsic(
772 MIRBuilder.getDebugLoc()) &&
773 "Expected inlined-at fields to agree");
774 if (!V) {
775 // Currently the optimizer can produce this; insert an undef to
776 // help debugging. Probably the optimizer should not do this.
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000777 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000778 } else if (const auto *CI = dyn_cast<Constant>(V)) {
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000779 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000780 } else {
781 unsigned Reg = getOrCreateVReg(*V);
782 // FIXME: This does not handle register-indirect values at offset 0. The
783 // direct/indirect thing shouldn't really be handled by something as
784 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
785 // pretty baked in right now.
Adrian Prantlabe04752017-07-28 20:21:02 +0000786 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000787 }
788 return true;
789 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000790 case Intrinsic::uadd_with_overflow:
791 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
792 case Intrinsic::sadd_with_overflow:
793 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
794 case Intrinsic::usub_with_overflow:
795 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
796 case Intrinsic::ssub_with_overflow:
797 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
798 case Intrinsic::umul_with_overflow:
799 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
800 case Intrinsic::smul_with_overflow:
801 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Tim Northoverb38b4e22017-02-08 23:23:32 +0000802 case Intrinsic::pow:
803 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
804 .addDef(getOrCreateVReg(CI))
805 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
806 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
807 return true;
Aditya Nandakumarcca75d22017-06-27 22:19:32 +0000808 case Intrinsic::exp:
809 MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
810 .addDef(getOrCreateVReg(CI))
811 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
812 return true;
813 case Intrinsic::exp2:
814 MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
815 .addDef(getOrCreateVReg(CI))
816 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
817 return true;
Aditya Nandakumar20f62072017-06-29 23:43:44 +0000818 case Intrinsic::log:
819 MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
820 .addDef(getOrCreateVReg(CI))
821 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
822 return true;
823 case Intrinsic::log2:
824 MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
825 .addDef(getOrCreateVReg(CI))
826 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
827 return true;
Volkan Keles2bc42e92018-03-05 22:31:55 +0000828 case Intrinsic::fabs:
829 MIRBuilder.buildInstr(TargetOpcode::G_FABS)
830 .addDef(getOrCreateVReg(CI))
831 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
832 return true;
Aditya Nandakumarc6a41912017-06-20 19:25:23 +0000833 case Intrinsic::fma:
834 MIRBuilder.buildInstr(TargetOpcode::G_FMA)
835 .addDef(getOrCreateVReg(CI))
836 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
837 .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
838 .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
839 return true;
Volkan Keles92837632018-02-13 00:47:46 +0000840 case Intrinsic::fmuladd: {
841 const TargetMachine &TM = MF->getTarget();
842 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
843 unsigned Dst = getOrCreateVReg(CI);
844 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
845 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
846 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
847 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
848 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
849 // TODO: Revisit this to see if we should move this part of the
850 // lowering to the combiner.
851 MIRBuilder.buildInstr(TargetOpcode::G_FMA, Dst, Op0, Op1, Op2);
852 } else {
853 LLT Ty = getLLTForType(*CI.getType(), *DL);
854 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, Ty, Op0, Op1);
855 MIRBuilder.buildInstr(TargetOpcode::G_FADD, Dst, FMul, Op2);
856 }
857 return true;
858 }
Tim Northover3f186032016-10-18 20:03:45 +0000859 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +0000860 case Intrinsic::memmove:
861 case Intrinsic::memset:
862 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +0000863 case Intrinsic::eh_typeid_for: {
864 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
865 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +0000866 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +0000867 MIRBuilder.buildConstant(Reg, TypeID);
868 return true;
869 }
Tim Northover6e904302016-10-18 20:03:51 +0000870 case Intrinsic::objectsize: {
871 // If we don't know by now, we're never going to know.
872 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
873
874 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
875 return true;
876 }
Tim Northovercdf23f12016-10-31 18:30:59 +0000877 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +0000878 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000879 return true;
880 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000881 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +0000882 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +0000883 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000884
885 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
886 MIRBuilder.buildStore(
887 GuardVal, getOrCreateVReg(*Slot),
Tim Northover50db7f412016-12-07 21:17:47 +0000888 *MF->getMachineMemOperand(
889 MachinePointerInfo::getFixedStack(*MF,
890 getOrCreateFrameIndex(*Slot)),
Tim Northovercdf23f12016-10-31 18:30:59 +0000891 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
892 PtrTy.getSizeInBits() / 8, 8));
893 return true;
894 }
Tim Northover91c81732016-08-19 17:17:06 +0000895 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000896 return false;
Tim Northover91c81732016-08-19 17:17:06 +0000897}
898
Tim Northoveraa995c92017-03-09 23:36:26 +0000899bool IRTranslator::translateInlineAsm(const CallInst &CI,
900 MachineIRBuilder &MIRBuilder) {
901 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
902 if (!IA.getConstraintString().empty())
903 return false;
904
905 unsigned ExtraInfo = 0;
906 if (IA.hasSideEffects())
907 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
908 if (IA.getDialect() == InlineAsm::AD_Intel)
909 ExtraInfo |= InlineAsm::Extra_AsmDialect;
910
911 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
912 .addExternalSymbol(IA.getAsmString().c_str())
913 .addImm(ExtraInfo);
914
915 return true;
916}
917
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000918unsigned IRTranslator::packRegs(const Value &V,
919 MachineIRBuilder &MIRBuilder) {
920 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
921 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
922 LLT BigTy = getLLTForType(*V.getType(), *DL);
923
924 if (Regs.size() == 1)
925 return Regs[0];
926
927 unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
928 MIRBuilder.buildUndef(Dst);
929 for (unsigned i = 0; i < Regs.size(); ++i) {
930 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
931 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
932 Dst = NewDst;
933 }
934 return Dst;
935}
936
937void IRTranslator::unpackRegs(const Value &V, unsigned Src,
938 MachineIRBuilder &MIRBuilder) {
939 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
940 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
941
942 for (unsigned i = 0; i < Regs.size(); ++i)
943 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
944}
945
Tim Northoverc53606e2016-12-07 21:29:15 +0000946bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000947 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +0000948 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +0000949 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +0000950
Martin Storsjocc981d22018-01-30 19:50:58 +0000951 // FIXME: support Windows dllimport function calls.
952 if (F && F->hasDLLImportStorageClass())
953 return false;
954
Tim Northover3babfef2017-01-19 23:59:35 +0000955 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +0000956 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +0000957
Amara Emerson913918c2018-01-02 18:56:39 +0000958 Intrinsic::ID ID = Intrinsic::not_intrinsic;
959 if (F && F->isIntrinsic()) {
960 ID = F->getIntrinsicID();
961 if (TII && ID == Intrinsic::not_intrinsic)
962 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
963 }
964
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000965 bool IsSplitType = valueIsSplit(CI);
Amara Emerson913918c2018-01-02 18:56:39 +0000966 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000967 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
968 getLLTForType(*CI.getType(), *DL))
969 : getOrCreateVReg(CI);
970
Tim Northover406024a2016-08-10 21:44:01 +0000971 SmallVector<unsigned, 8> Args;
972 for (auto &Arg: CI.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000973 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northover406024a2016-08-10 21:44:01 +0000974
Tim Northoverd1e951e2017-03-09 22:00:39 +0000975 MF->getFrameInfo().setHasCalls(true);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000976 bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
Tim Northoverfe5f89b2016-08-29 19:07:08 +0000977 return getOrCreateVReg(*CI.getCalledValue());
978 });
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000979
980 if (IsSplitType)
981 unpackRegs(CI, Res, MIRBuilder);
982 return Success;
Tim Northover406024a2016-08-10 21:44:01 +0000983 }
984
Tim Northover406024a2016-08-10 21:44:01 +0000985 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +0000986
Tim Northoverc53606e2016-12-07 21:29:15 +0000987 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +0000988 return true;
989
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000990 unsigned Res = 0;
991 if (!CI.getType()->isVoidTy()) {
992 if (IsSplitType)
993 Res =
994 MRI->createGenericVirtualRegister(getLLTForType(*CI.getType(), *DL));
995 else
996 Res = getOrCreateVReg(CI);
997 }
Tim Northover5fb414d2016-07-29 22:32:36 +0000998 MachineInstrBuilder MIB =
Tim Northover0f140c72016-09-09 11:46:34 +0000999 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
Tim Northover5fb414d2016-07-29 22:32:36 +00001000
1001 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +00001002 // Some intrinsics take metadata parameters. Reject them.
1003 if (isa<MetadataAsValue>(Arg))
1004 return false;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001005 MIB.addUse(packRegs(*Arg, MIRBuilder));
Tim Northover5fb414d2016-07-29 22:32:36 +00001006 }
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001007
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001008 if (IsSplitType)
1009 unpackRegs(CI, Res, MIRBuilder);
1010
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001011 // Add a MachineMemOperand if it is a target mem intrinsic.
1012 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1013 TargetLowering::IntrinsicInfo Info;
1014 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
Matt Arsenault7d7adf42017-12-14 22:34:10 +00001015 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +00001016 uint64_t Size = Info.memVT.getStoreSize();
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001017 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
Matt Arsenault11171332017-12-14 21:39:51 +00001018 Info.flags, Size, Info.align));
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001019 }
1020
Tim Northover5fb414d2016-07-29 22:32:36 +00001021 return true;
1022}
1023
Tim Northoverc53606e2016-12-07 21:29:15 +00001024bool IRTranslator::translateInvoke(const User &U,
1025 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001026 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001027 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +00001028
1029 const BasicBlock *ReturnBB = I.getSuccessor(0);
1030 const BasicBlock *EHPadBB = I.getSuccessor(1);
1031
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001032 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +00001033 const Function *Fn = dyn_cast<Function>(Callee);
1034 if (isa<InlineAsm>(Callee))
1035 return false;
1036
1037 // FIXME: support invoking patchpoint and statepoint intrinsics.
1038 if (Fn && Fn->isIntrinsic())
1039 return false;
1040
1041 // FIXME: support whatever these are.
1042 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1043 return false;
1044
1045 // FIXME: support Windows exception handling.
1046 if (!isa<LandingPadInst>(EHPadBB->front()))
1047 return false;
1048
Matthias Braund0ee66c2016-12-01 19:32:15 +00001049 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +00001050 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +00001051 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001052 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1053
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001054 unsigned Res =
1055 MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
Tim Northover293f7432017-01-31 18:36:11 +00001056 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +00001057 for (auto &Arg: I.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001058 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northovera9105be2016-11-09 22:39:54 +00001059
Ahmed Bougachad22b84b2017-03-10 00:25:44 +00001060 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001061 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1062 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001063
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001064 unpackRegs(I, Res, MIRBuilder);
1065
Matthias Braund0ee66c2016-12-01 19:32:15 +00001066 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001067 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1068
1069 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001070 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1071 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +00001072 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +00001073 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1074 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +00001075 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001076
1077 return true;
1078}
1079
Tim Northoverc53606e2016-12-07 21:29:15 +00001080bool IRTranslator::translateLandingPad(const User &U,
1081 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001082 const LandingPadInst &LP = cast<LandingPadInst>(U);
1083
1084 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Matthias Braund0ee66c2016-12-01 19:32:15 +00001085 addLandingPadInfo(LP, MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001086
1087 MBB.setIsEHPad();
1088
1089 // If there aren't registers to copy the values into (e.g., during SjLj
1090 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +00001091 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +00001092 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +00001093 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1094 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1095 return true;
1096
1097 // If landingpad's return type is token type, we don't create DAG nodes
1098 // for its exception pointer and selector value. The extraction of exception
1099 // pointer or selector value from token type landingpads is not currently
1100 // supported.
1101 if (LP.getType()->isTokenTy())
1102 return true;
1103
1104 // Add a label to mark the beginning of the landing pad. Deletion of the
1105 // landing pad can thus be detected via the MachineModuleInfo.
1106 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +00001107 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +00001108
Daniel Sanders1351db42017-03-07 23:32:10 +00001109 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +00001110 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1111 MIRBuilder.buildUndef(Undef);
1112
Justin Bognera0295312017-01-25 00:16:53 +00001113 SmallVector<LLT, 2> Tys;
1114 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001115 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +00001116 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1117
Tim Northovera9105be2016-11-09 22:39:54 +00001118 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +00001119 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1120 if (!ExceptionReg)
1121 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001122
Tim Northover542d1c12017-03-07 23:04:06 +00001123 MBB.addLiveIn(ExceptionReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001124 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1125 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
Tim Northoverc9449702017-01-30 20:52:42 +00001126
Tim Northover542d1c12017-03-07 23:04:06 +00001127 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1128 if (!SelectorReg)
1129 return false;
Tim Northoverc9449702017-01-30 20:52:42 +00001130
Tim Northover542d1c12017-03-07 23:04:06 +00001131 MBB.addLiveIn(SelectorReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001132 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1133 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001134 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001135
Tim Northovera9105be2016-11-09 22:39:54 +00001136 return true;
1137}
1138
Tim Northoverc3e3f592017-02-03 18:22:45 +00001139bool IRTranslator::translateAlloca(const User &U,
1140 MachineIRBuilder &MIRBuilder) {
1141 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001142
Tim Northoverc3e3f592017-02-03 18:22:45 +00001143 if (AI.isStaticAlloca()) {
1144 unsigned Res = getOrCreateVReg(AI);
1145 int FI = getOrCreateFrameIndex(AI);
1146 MIRBuilder.buildFrameIndex(Res, FI);
1147 return true;
1148 }
1149
Martin Storsjoa63a5b92018-02-17 14:26:32 +00001150 // FIXME: support stack probing for Windows.
1151 if (MF->getTarget().getTargetTriple().isOSWindows())
1152 return false;
1153
Tim Northoverc3e3f592017-02-03 18:22:45 +00001154 // Now we're in the harder dynamic case.
1155 Type *Ty = AI.getAllocatedType();
1156 unsigned Align =
1157 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1158
1159 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1160
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001161 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1162 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001163 if (MRI->getType(NumElts) != IntPtrTy) {
1164 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1165 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1166 NumElts = ExtElts;
1167 }
1168
1169 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001170 unsigned TySize =
1171 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +00001172 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1173
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001174 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001175 auto &TLI = *MF->getSubtarget().getTargetLowering();
1176 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1177
1178 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1179 MIRBuilder.buildCopy(SPTmp, SPReg);
1180
Tim Northoverc2f89562017-02-14 20:56:18 +00001181 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1182 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001183
1184 // Handle alignment. We have to realign if the allocation granule was smaller
1185 // than stack alignment, or the specific alloca requires more than stack
1186 // alignment.
1187 unsigned StackAlign =
1188 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1189 Align = std::max(Align, StackAlign);
1190 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1191 // Round the size of the allocation up to the stack alignment size
1192 // by add SA-1 to the size. This doesn't overflow because we're computing
1193 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +00001194 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1195 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1196 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +00001197 }
1198
Tim Northoverc2f89562017-02-14 20:56:18 +00001199 MIRBuilder.buildCopy(SPReg, AllocTmp);
1200 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001201
1202 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1203 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +00001204 return true;
1205}
1206
Tim Northover4a652222017-02-15 23:22:33 +00001207bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1208 // FIXME: We may need more info about the type. Because of how LLT works,
1209 // we're completely discarding the i64/double distinction here (amongst
1210 // others). Fortunately the ABIs I know of where that matters don't use va_arg
1211 // anyway but that's not guaranteed.
1212 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1213 .addDef(getOrCreateVReg(U))
1214 .addUse(getOrCreateVReg(*U.getOperand(0)))
1215 .addImm(DL->getABITypeAlignment(U.getType()));
1216 return true;
1217}
1218
Volkan Keles04cb08c2017-03-10 19:08:28 +00001219bool IRTranslator::translateInsertElement(const User &U,
1220 MachineIRBuilder &MIRBuilder) {
1221 // If it is a <1 x Ty> vector, use the scalar as it is
1222 // not a legal vector type in LLT.
1223 if (U.getType()->getVectorNumElements() == 1) {
1224 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001225 auto &Regs = *VMap.getVRegs(U);
1226 if (Regs.empty()) {
1227 Regs.push_back(Elt);
1228 VMap.getOffsets(U)->push_back(0);
1229 } else {
1230 MIRBuilder.buildCopy(Regs[0], Elt);
1231 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001232 return true;
1233 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001234
Kristof Beyls7a713502017-04-19 06:38:37 +00001235 unsigned Res = getOrCreateVReg(U);
1236 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1237 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1238 unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1239 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001240 return true;
1241}
1242
1243bool IRTranslator::translateExtractElement(const User &U,
1244 MachineIRBuilder &MIRBuilder) {
1245 // If it is a <1 x Ty> vector, use the scalar as it is
1246 // not a legal vector type in LLT.
1247 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1248 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001249 auto &Regs = *VMap.getVRegs(U);
1250 if (Regs.empty()) {
1251 Regs.push_back(Elt);
1252 VMap.getOffsets(U)->push_back(0);
1253 } else {
1254 MIRBuilder.buildCopy(Regs[0], Elt);
1255 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001256 return true;
1257 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001258 unsigned Res = getOrCreateVReg(U);
1259 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1260 unsigned Idx = getOrCreateVReg(*U.getOperand(1));
1261 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001262 return true;
1263}
1264
Volkan Keles75bdc762017-03-21 08:44:13 +00001265bool IRTranslator::translateShuffleVector(const User &U,
1266 MachineIRBuilder &MIRBuilder) {
1267 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1268 .addDef(getOrCreateVReg(U))
1269 .addUse(getOrCreateVReg(*U.getOperand(0)))
1270 .addUse(getOrCreateVReg(*U.getOperand(1)))
1271 .addUse(getOrCreateVReg(*U.getOperand(2)));
1272 return true;
1273}
1274
Tim Northoverc53606e2016-12-07 21:29:15 +00001275bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001276 const PHINode &PI = cast<PHINode>(U);
Tim Northover97d0cb32016-08-05 17:16:40 +00001277
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001278 SmallVector<MachineInstr *, 4> Insts;
1279 for (auto Reg : getOrCreateVRegs(PI)) {
1280 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, Reg);
1281 Insts.push_back(MIB.getInstr());
1282 }
1283
1284 PendingPHIs.emplace_back(&PI, std::move(Insts));
Tim Northover97d0cb32016-08-05 17:16:40 +00001285 return true;
1286}
1287
1288void IRTranslator::finishPendingPhis() {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001289 for (auto &Phi : PendingPHIs) {
Tim Northover97d0cb32016-08-05 17:16:40 +00001290 const PHINode *PI = Phi.first;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001291 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
Tim Northover97d0cb32016-08-05 17:16:40 +00001292
1293 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1294 // won't create extra control flow here, otherwise we need to find the
1295 // dominating predecessor here (or perhaps force the weirder IRTranslators
1296 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001297 SmallSet<const BasicBlock *, 4> HandledPreds;
1298
Tim Northover97d0cb32016-08-05 17:16:40 +00001299 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001300 auto IRPred = PI->getIncomingBlock(i);
1301 if (HandledPreds.count(IRPred))
1302 continue;
1303
1304 HandledPreds.insert(IRPred);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001305 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
Tim Northoverb6636fd2017-01-17 22:13:50 +00001306 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001307 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
Tim Northoverb6636fd2017-01-17 22:13:50 +00001308 "incorrect CFG at MachineBasicBlock level");
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001309 for (unsigned j = 0; j < ValRegs.size(); ++j) {
1310 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1311 MIB.addUse(ValRegs[j]);
1312 MIB.addMBB(Pred);
1313 }
Tim Northoverb6636fd2017-01-17 22:13:50 +00001314 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001315 }
1316 }
1317}
1318
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001319bool IRTranslator::valueIsSplit(const Value &V,
1320 SmallVectorImpl<uint64_t> *Offsets) {
1321 SmallVector<LLT, 4> SplitTys;
1322 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1323 return SplitTys.size() > 1;
1324}
1325
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001326bool IRTranslator::translate(const Instruction &Inst) {
Tim Northoverc53606e2016-12-07 21:29:15 +00001327 CurBuilder.setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001328 switch(Inst.getOpcode()) {
Tim Northover357f1be2016-08-10 23:02:41 +00001329#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001330 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001331#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001332 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001333 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001334 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001335}
1336
Tim Northover5ed648e2016-08-09 21:28:04 +00001337bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001338 if (auto CI = dyn_cast<ConstantInt>(&C))
Tim Northovercc35f902016-12-05 21:54:17 +00001339 EntryBuilder.buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001340 else if (auto CF = dyn_cast<ConstantFP>(&C))
Tim Northover0f140c72016-09-09 11:46:34 +00001341 EntryBuilder.buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001342 else if (isa<UndefValue>(C))
Tim Northover81dafc12017-03-06 18:36:40 +00001343 EntryBuilder.buildUndef(Reg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001344 else if (isa<ConstantPointerNull>(C)) {
1345 // As we are trying to build a constant val of 0 into a pointer,
1346 // insert a cast to make them correct with respect to types.
1347 unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1348 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1349 auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1350 unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1351 EntryBuilder.buildCast(Reg, ZeroReg);
1352 } else if (auto GV = dyn_cast<GlobalValue>(&C))
Tim Northover032548f2016-09-12 12:10:41 +00001353 EntryBuilder.buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001354 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1355 if (!CAZ->getType()->isVectorTy())
1356 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001357 // Return the scalar if it is a <1 x Ty> vector.
1358 if (CAZ->getNumElements() == 1)
1359 return translate(*CAZ->getElementValue(0u), Reg);
Volkan Keles970fee42017-03-10 21:23:13 +00001360 std::vector<unsigned> Ops;
1361 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1362 Constant &Elt = *CAZ->getElementValue(i);
1363 Ops.push_back(getOrCreateVReg(Elt));
1364 }
1365 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001366 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001367 // Return the scalar if it is a <1 x Ty> vector.
1368 if (CV->getNumElements() == 1)
1369 return translate(*CV->getElementAsConstant(0), Reg);
Volkan Keles38a91a02017-03-13 21:36:19 +00001370 std::vector<unsigned> Ops;
1371 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1372 Constant &Elt = *CV->getElementAsConstant(i);
1373 Ops.push_back(getOrCreateVReg(Elt));
1374 }
1375 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001376 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001377 switch(CE->getOpcode()) {
1378#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001379 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001380#include "llvm/IR/Instruction.def"
1381 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001382 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001383 }
Aditya Nandakumar117b6672017-05-04 21:43:12 +00001384 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1385 if (CV->getNumOperands() == 1)
1386 return translate(*CV->getOperand(0), Reg);
1387 SmallVector<unsigned, 4> Ops;
1388 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1389 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1390 }
1391 EntryBuilder.buildMerge(Reg, Ops);
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001392 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001393 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001394
Tim Northoverd403a3d2016-08-09 23:01:30 +00001395 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001396}
1397
Tim Northover0d510442016-08-11 16:21:29 +00001398void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001399 // Release the memory used by the different maps we
1400 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001401 PendingPHIs.clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001402 VMap.reset();
Tim Northovercdf23f12016-10-31 18:30:59 +00001403 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001404 MachinePreds.clear();
Aditya Nandakumarbe929932017-05-17 17:41:55 +00001405 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1406 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1407 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1408 EntryBuilder = MachineIRBuilder();
1409 CurBuilder = MachineIRBuilder();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001410}
1411
Tim Northover50db7f412016-12-07 21:17:47 +00001412bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1413 MF = &CurMF;
Matthias Braunf1caa282017-12-15 22:22:58 +00001414 const Function &F = MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001415 if (F.empty())
1416 return false;
Tim Northover50db7f412016-12-07 21:17:47 +00001417 CLI = MF->getSubtarget().getCallLowering();
Tim Northoverc53606e2016-12-07 21:29:15 +00001418 CurBuilder.setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001419 EntryBuilder.setMF(*MF);
1420 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001421 DL = &F.getParent()->getDataLayout();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001422 TPC = &getAnalysis<TargetPassConfig>();
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001423 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001424
Tim Northover14e7f732016-08-05 17:50:36 +00001425 assert(PendingPHIs.empty() && "stale PHIs");
1426
Amara Emersondf9b5292017-12-11 16:58:29 +00001427 if (!DL->isLittleEndian()) {
1428 // Currently we don't properly handle big endian code.
1429 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001430 F.getSubprogram(), &F.getEntryBlock());
Amara Emersondf9b5292017-12-11 16:58:29 +00001431 R << "unable to translate in big endian mode";
1432 reportTranslationError(*MF, *TPC, *ORE, R);
1433 }
1434
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001435 // Release the per-function state when we return, whether we succeeded or not.
1436 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1437
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001438 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001439 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1440 MF->push_back(EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001441 EntryBuilder.setMBB(*EntryBB);
1442
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001443 // Create all blocks, in IR order, to preserve the layout.
1444 for (const BasicBlock &BB: F) {
1445 auto *&MBB = BBToMBB[&BB];
1446
1447 MBB = MF->CreateMachineBasicBlock(&BB);
1448 MF->push_back(MBB);
1449
1450 if (BB.hasAddressTaken())
1451 MBB->setHasAddressTaken();
1452 }
1453
1454 // Make our arguments/constants entry block fallthrough to the IR entry block.
1455 EntryBB->addSuccessor(&getMBB(F.front()));
1456
Tim Northover05cc4852016-12-07 21:05:38 +00001457 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001458 SmallVector<unsigned, 8> VRegArgs;
Amara Emersond78d65c2017-11-30 20:06:02 +00001459 for (const Argument &Arg: F.args()) {
1460 if (DL->getTypeStoreSize(Arg.getType()) == 0)
1461 continue; // Don't handle zero sized types.
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001462 VRegArgs.push_back(
1463 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
Amara Emersond78d65c2017-11-30 20:06:02 +00001464 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001465
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001466 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001467 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001468 F.getSubprogram(), &F.getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001469 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1470 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001471 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001472 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001473
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001474 auto ArgIt = F.arg_begin();
1475 for (auto &VArg : VRegArgs) {
1476 // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1477 // creating redundant copies.
1478 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1479 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1480 assert(VRegs.empty() && "VRegs already populated?");
1481 VRegs.push_back(VArg);
1482 } else {
1483 unpackRegs(*ArgIt, VArg, EntryBuilder);
1484 }
1485 ArgIt++;
1486 }
1487
Tim Northover05cc4852016-12-07 21:05:38 +00001488 // And translate the function!
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001489 for (const BasicBlock &BB : F) {
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001490 MachineBasicBlock &MBB = getMBB(BB);
Quentin Colombet91ebd712016-03-11 17:27:47 +00001491 // Set the insertion point of all the following translations to
1492 // the end of this basic block.
Tim Northoverc53606e2016-12-07 21:29:15 +00001493 CurBuilder.setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001494
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001495 for (const Instruction &Inst : BB) {
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001496 if (translate(Inst))
1497 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001498
Ahmed Bougacha7daaf882017-02-24 00:34:47 +00001499 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1500 Inst.getDebugLoc(), &BB);
Ahmed Bougachad630a922017-09-18 18:50:09 +00001501 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1502
1503 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1504 std::string InstStrStorage;
1505 raw_string_ostream InstStr(InstStrStorage);
1506 InstStr << Inst;
1507
1508 R << ": '" << InstStr.str() << "'";
1509 }
1510
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001511 reportTranslationError(*MF, *TPC, *ORE, R);
1512 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001513 }
1514 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001515
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001516 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001517
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001518 // Merge the argument lowering and constants block with its single
1519 // successor, the LLVM-IR entry block. We want the basic block to
1520 // be maximal.
1521 assert(EntryBB->succ_size() == 1 &&
1522 "Custom BB used for lowering should have only one successor");
1523 // Get the successor of the current entry block.
1524 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1525 assert(NewEntryBB.pred_size() == 1 &&
1526 "LLVM-IR entry block has a predecessor!?");
1527 // Move all the instruction from the current entry block to the
1528 // new entry block.
1529 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1530 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001531
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001532 // Update the live-in information for the new entry block.
1533 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1534 NewEntryBB.addLiveIn(LiveIn);
1535 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001536
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001537 // Get rid of the now empty basic block.
1538 EntryBB->removeSuccessor(&NewEntryBB);
1539 MF->remove(EntryBB);
1540 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001541
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001542 assert(&MF->front() == &NewEntryBB &&
1543 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001544
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001545 return false;
1546}