blob: 7b09fd815ab9eb7cdf0236ad07a9da9bfddbacfa [file] [log] [blame]
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001//===-- 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
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"
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000018#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Quentin Colombetba2a0162016-02-16 19:26:02 +000019#include "llvm/CodeGen/GlobalISel/CallLowering.h"
Tim Northovera9105be2016-11-09 22:39:54 +000020#include "llvm/CodeGen/Analysis.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000021#include "llvm/CodeGen/MachineFunction.h"
Tim Northoverbd505462016-07-22 16:59:52 +000022#include "llvm/CodeGen/MachineFrameInfo.h"
Tim Northovera9105be2016-11-09 22:39:54 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000025#include "llvm/CodeGen/TargetPassConfig.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000026#include "llvm/IR/Constant.h"
Tim Northover09aac4a2017-01-26 23:39:14 +000027#include "llvm/IR/DebugInfo.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000028#include "llvm/IR/Function.h"
Tim Northovera7653b32016-09-12 11:20:22 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000030#include "llvm/IR/IntrinsicInst.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000031#include "llvm/IR/Type.h"
32#include "llvm/IR/Value.h"
Tim Northoverc3e3f592017-02-03 18:22:45 +000033#include "llvm/Target/TargetFrameLowering.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000034#include "llvm/Target/TargetIntrinsicInfo.h"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +000035#include "llvm/Target/TargetLowering.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000036
37#define DEBUG_TYPE "irtranslator"
38
Quentin Colombet105cf2b2016-01-20 20:58:56 +000039using namespace llvm;
40
41char IRTranslator::ID = 0;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000042INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
43 false, false)
44INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
45INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
Tim Northover884b47e2016-07-26 03:29:18 +000046 false, false)
Quentin Colombet105cf2b2016-01-20 20:58:56 +000047
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000048static void reportTranslationError(MachineFunction &MF,
49 const TargetPassConfig &TPC,
50 OptimizationRemarkEmitter &ORE,
51 OptimizationRemarkMissed &R) {
52 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
53
54 // Print the function name explicitly if we don't have a debug location (which
55 // makes the diagnostic less useful) or if we're going to emit a raw error.
56 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
57 R << (" (in function: " + MF.getName() + ")").str();
58
59 if (TPC.isGlobalISelAbortEnabled())
60 report_fatal_error(R.getMsg());
61 else
62 ORE.emit(R);
Tim Northover60f23492016-11-08 01:12:17 +000063}
64
Quentin Colombeta7fae162016-02-11 17:53:23 +000065IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
Quentin Colombet39293d32016-03-08 01:38:55 +000066 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
Quentin Colombeta7fae162016-02-11 17:53:23 +000067}
68
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000069void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<TargetPassConfig>();
71 MachineFunctionPass::getAnalysisUsage(AU);
72}
73
74
Quentin Colombete225e252016-03-11 17:27:54 +000075unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
76 unsigned &ValReg = ValToVReg[&Val];
Tim Northover5ed648e2016-08-09 21:28:04 +000077
Tim Northover9e35f1e2017-01-25 20:58:22 +000078 if (ValReg)
79 return ValReg;
80
81 // Fill ValRegsSequence with the sequence of registers
82 // we need to concat together to produce the value.
83 assert(Val.getType()->isSized() &&
84 "Don't know how to create an empty vreg");
Daniel Sanders52b4ce72017-03-07 23:20:35 +000085 unsigned VReg =
86 MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL));
Tim Northover9e35f1e2017-01-25 20:58:22 +000087 ValReg = VReg;
88
89 if (auto CV = dyn_cast<Constant>(&Val)) {
90 bool Success = translate(*CV, VReg);
91 if (!Success) {
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000092 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +000093 MF->getFunction()->getSubprogram(),
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000094 &MF->getFunction()->getEntryBlock());
95 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
96 reportTranslationError(*MF, *TPC, *ORE, R);
97 return VReg;
Tim Northover5ed648e2016-08-09 21:28:04 +000098 }
Quentin Colombet17c494b2016-02-11 17:51:31 +000099 }
Tim Northover7f3ad2e2017-01-20 23:25:17 +0000100
Tim Northover9e35f1e2017-01-25 20:58:22 +0000101 return VReg;
Quentin Colombet17c494b2016-02-11 17:51:31 +0000102}
103
Tim Northovercdf23f12016-10-31 18:30:59 +0000104int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
105 if (FrameIndices.find(&AI) != FrameIndices.end())
106 return FrameIndices[&AI];
107
Tim Northovercdf23f12016-10-31 18:30:59 +0000108 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
109 unsigned Size =
110 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
111
112 // Always allocate at least one byte.
113 Size = std::max(Size, 1u);
114
115 unsigned Alignment = AI.getAlignment();
116 if (!Alignment)
117 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
118
119 int &FI = FrameIndices[&AI];
Tim Northover50db7f412016-12-07 21:17:47 +0000120 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
Tim Northovercdf23f12016-10-31 18:30:59 +0000121 return FI;
122}
123
Tim Northoverad2b7172016-07-26 20:23:26 +0000124unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
125 unsigned Alignment = 0;
126 Type *ValTy = nullptr;
127 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
128 Alignment = SI->getAlignment();
129 ValTy = SI->getValueOperand()->getType();
130 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
131 Alignment = LI->getAlignment();
132 ValTy = LI->getType();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000133 } else {
134 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
135 R << "unable to translate memop: " << ore::NV("Opcode", &I);
136 reportTranslationError(*MF, *TPC, *ORE, R);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000137 return 1;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000138 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000139
140 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
141}
142
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000143MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
Quentin Colombet53237a92016-03-11 17:27:43 +0000144 MachineBasicBlock *&MBB = BBToMBB[&BB];
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000145 assert(MBB && "BasicBlock was not encountered before");
Quentin Colombet17c494b2016-02-11 17:51:31 +0000146 return *MBB;
147}
148
Tim Northoverb6636fd2017-01-17 22:13:50 +0000149void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
150 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
151 MachinePreds[Edge].push_back(NewPred);
152}
153
Tim Northoverc53606e2016-12-07 21:29:15 +0000154bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
155 MachineIRBuilder &MIRBuilder) {
Tim Northover0d56e052016-07-29 18:11:21 +0000156 // FIXME: handle signed/unsigned wrapping flags.
157
Quentin Colombet2ecff3b2016-02-10 22:59:27 +0000158 // Get or create a virtual register for each value.
159 // Unless the value is a Constant => loadimm cst?
160 // or inline constant each time?
161 // Creation of a virtual register needs to have a size.
Tim Northover357f1be2016-08-10 23:02:41 +0000162 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
163 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
164 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000165 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
Quentin Colombet17c494b2016-02-11 17:51:31 +0000166 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000167}
168
Volkan Keles20d3c422017-03-07 18:03:28 +0000169bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
170 // -0.0 - X --> G_FNEG
171 if (isa<Constant>(U.getOperand(0)) &&
172 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
173 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
174 .addDef(getOrCreateVReg(U))
175 .addUse(getOrCreateVReg(*U.getOperand(1)));
176 return true;
177 }
178 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
179}
180
Tim Northoverc53606e2016-12-07 21:29:15 +0000181bool IRTranslator::translateCompare(const User &U,
182 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000183 const CmpInst *CI = dyn_cast<CmpInst>(&U);
184 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
185 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
186 unsigned Res = getOrCreateVReg(U);
187 CmpInst::Predicate Pred =
188 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
189 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000190 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000191 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000192 else if (Pred == CmpInst::FCMP_FALSE)
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000193 MIRBuilder.buildCopy(
194 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
195 else if (Pred == CmpInst::FCMP_TRUE)
196 MIRBuilder.buildCopy(
197 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000198 else
Tim Northover0f140c72016-09-09 11:46:34 +0000199 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000200
Tim Northoverde3aea0412016-08-17 20:25:25 +0000201 return true;
202}
203
Tim Northoverc53606e2016-12-07 21:29:15 +0000204bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000205 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000206 const Value *Ret = RI.getReturnValue();
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000207 // The target may mess up with the insertion point, but
208 // this is not important as a return is the last instruction
209 // of the block anyway.
Tom Stellardb72a65f2016-04-14 17:23:33 +0000210 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000211}
212
Tim Northoverc53606e2016-12-07 21:29:15 +0000213bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000214 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000215 unsigned Succ = 0;
216 if (!BrInst.isUnconditional()) {
217 // We want a G_BRCOND to the true BB followed by an unconditional branch.
218 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
219 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000220 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000221 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000222 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000223
224 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000225 MachineBasicBlock &TgtBB = getMBB(BrTgt);
Tim Northover69c2ba52016-07-29 17:58:00 +0000226 MIRBuilder.buildBr(TgtBB);
227
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000228 // Link successors.
229 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
230 for (const BasicBlock *Succ : BrInst.successors())
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000231 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000232 return true;
233}
234
Kristof Beylseced0712017-01-05 11:28:51 +0000235bool IRTranslator::translateSwitch(const User &U,
236 MachineIRBuilder &MIRBuilder) {
237 // For now, just translate as a chain of conditional branches.
238 // FIXME: could we share most of the logic/code in
239 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
240 // At first sight, it seems most of the logic in there is independent of
241 // SelectionDAG-specifics and a lot of work went in to optimize switch
242 // lowering in there.
243
244 const SwitchInst &SwInst = cast<SwitchInst>(U);
245 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000246 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000247
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000248 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000249 for (auto &CaseIt : SwInst.cases()) {
250 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
251 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
252 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000253 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
254 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000255 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000256
Tim Northoverb6636fd2017-01-17 22:13:50 +0000257 MIRBuilder.buildBrCond(Tst, TrueMBB);
258 CurMBB.addSuccessor(&TrueMBB);
259 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000260
Tim Northoverb6636fd2017-01-17 22:13:50 +0000261 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000262 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000263 // Insert the comparison blocks one after the other.
264 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000265 MIRBuilder.buildBr(*FalseMBB);
266 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000267
Tim Northoverb6636fd2017-01-17 22:13:50 +0000268 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000269 }
270 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000271 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000272 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000273 MIRBuilder.buildBr(DefaultMBB);
274 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
275 CurMBB.addSuccessor(&DefaultMBB);
276 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000277
278 return true;
279}
280
Kristof Beyls65a12c02017-01-30 09:13:18 +0000281bool IRTranslator::translateIndirectBr(const User &U,
282 MachineIRBuilder &MIRBuilder) {
283 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
284
285 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
286 MIRBuilder.buildBrIndirect(Tgt);
287
288 // Link successors.
289 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
290 for (const BasicBlock *Succ : BrInst.successors())
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000291 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000292
293 return true;
294}
295
Tim Northoverc53606e2016-12-07 21:29:15 +0000296bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000297 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000298
Tim Northover7152dca2016-10-19 15:55:06 +0000299 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
300 : MachineMemOperand::MONone;
301 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000302
Tim Northoverad2b7172016-07-26 20:23:26 +0000303 unsigned Res = getOrCreateVReg(LI);
304 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000305
Tim Northoverad2b7172016-07-26 20:23:26 +0000306 MIRBuilder.buildLoad(
Tim Northover0f140c72016-09-09 11:46:34 +0000307 Res, Addr,
Tim Northover50db7f412016-12-07 21:17:47 +0000308 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
309 Flags, DL->getTypeStoreSize(LI.getType()),
Tim Northover48dfa1a2017-02-13 22:14:16 +0000310 getMemOpAlignment(LI), AAMDNodes(), nullptr,
311 LI.getSynchScope(), LI.getOrdering()));
Tim Northoverad2b7172016-07-26 20:23:26 +0000312 return true;
313}
314
Tim Northoverc53606e2016-12-07 21:29:15 +0000315bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000316 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000317 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
318 : MachineMemOperand::MONone;
319 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000320
Tim Northoverad2b7172016-07-26 20:23:26 +0000321 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
322 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000323
324 MIRBuilder.buildStore(
Tim Northover50db7f412016-12-07 21:17:47 +0000325 Val, Addr,
326 *MF->getMachineMemOperand(
327 MachinePointerInfo(SI.getPointerOperand()), Flags,
328 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
Tim Northover48dfa1a2017-02-13 22:14:16 +0000329 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
330 SI.getOrdering()));
Tim Northoverad2b7172016-07-26 20:23:26 +0000331 return true;
332}
333
Tim Northoverc53606e2016-12-07 21:29:15 +0000334bool IRTranslator::translateExtractValue(const User &U,
335 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000336 const Value *Src = U.getOperand(0);
337 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Tim Northover6f80b082016-08-19 17:47:05 +0000338 SmallVector<Value *, 1> Indices;
339
340 // getIndexedOffsetInType is designed for GEPs, so the first index is the
341 // usual array element rather than looking into the actual aggregate.
342 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000343
344 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
345 for (auto Idx : EVI->indices())
346 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
347 } else {
348 for (unsigned i = 1; i < U.getNumOperands(); ++i)
349 Indices.push_back(U.getOperand(i));
350 }
Tim Northover6f80b082016-08-19 17:47:05 +0000351
352 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
353
Tim Northoverb6046222016-08-19 20:09:03 +0000354 unsigned Res = getOrCreateVReg(U);
Tim Northoverc2c545b2017-03-06 23:50:28 +0000355 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
Tim Northover6f80b082016-08-19 17:47:05 +0000356
357 return true;
358}
359
Tim Northoverc53606e2016-12-07 21:29:15 +0000360bool IRTranslator::translateInsertValue(const User &U,
361 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000362 const Value *Src = U.getOperand(0);
363 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000364 SmallVector<Value *, 1> Indices;
365
366 // getIndexedOffsetInType is designed for GEPs, so the first index is the
367 // usual array element rather than looking into the actual aggregate.
368 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000369
370 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
371 for (auto Idx : IVI->indices())
372 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
373 } else {
374 for (unsigned i = 2; i < U.getNumOperands(); ++i)
375 Indices.push_back(U.getOperand(i));
376 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000377
378 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
379
Tim Northoverb6046222016-08-19 20:09:03 +0000380 unsigned Res = getOrCreateVReg(U);
381 const Value &Inserted = *U.getOperand(1);
Tim Northover0f140c72016-09-09 11:46:34 +0000382 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
383 Offset);
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000384
385 return true;
386}
387
Tim Northoverc53606e2016-12-07 21:29:15 +0000388bool IRTranslator::translateSelect(const User &U,
389 MachineIRBuilder &MIRBuilder) {
Tim Northover0f140c72016-09-09 11:46:34 +0000390 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
391 getOrCreateVReg(*U.getOperand(1)),
392 getOrCreateVReg(*U.getOperand(2)));
Tim Northover5a28c362016-08-19 20:09:07 +0000393 return true;
394}
395
Tim Northoverc53606e2016-12-07 21:29:15 +0000396bool IRTranslator::translateBitCast(const User &U,
397 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000398 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000399 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
400 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000401 // Get the source vreg now, to avoid invalidating ValToVReg.
402 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Tim Northover357f1be2016-08-10 23:02:41 +0000403 unsigned &Reg = ValToVReg[&U];
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000404 // If we already assigned a vreg for this bitcast, we can't change that.
405 // Emit a copy to satisfy the users we already emitted.
Tim Northover7552ef52016-08-10 16:51:14 +0000406 if (Reg)
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000407 MIRBuilder.buildCopy(Reg, SrcReg);
Tim Northover7552ef52016-08-10 16:51:14 +0000408 else
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000409 Reg = SrcReg;
Tim Northover7c9eba92016-07-25 21:01:29 +0000410 return true;
411 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000412 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000413}
414
Tim Northoverc53606e2016-12-07 21:29:15 +0000415bool IRTranslator::translateCast(unsigned Opcode, const User &U,
416 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000417 unsigned Op = getOrCreateVReg(*U.getOperand(0));
418 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000419 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
Tim Northover7c9eba92016-07-25 21:01:29 +0000420 return true;
421}
422
Tim Northoverc53606e2016-12-07 21:29:15 +0000423bool IRTranslator::translateGetElementPtr(const User &U,
424 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000425 // FIXME: support vector GEPs.
426 if (U.getType()->isVectorTy())
427 return false;
428
429 Value &Op0 = *U.getOperand(0);
430 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000431 Type *PtrIRTy = Op0.getType();
432 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
433 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
434 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000435
436 int64_t Offset = 0;
437 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
438 GTI != E; ++GTI) {
439 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000440 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000441 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
442 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
443 continue;
444 } else {
445 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
446
447 // If this is a scalar constant or a splat vector of constants,
448 // handle it quickly.
449 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
450 Offset += ElementSize * CI->getSExtValue();
451 continue;
452 }
453
454 if (Offset != 0) {
455 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000456 unsigned OffsetReg =
457 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000458 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
459
460 BaseReg = NewBaseReg;
461 Offset = 0;
462 }
463
464 // N = N + Idx * ElementSize;
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000465 unsigned ElementSizeReg =
466 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
Tim Northovera7653b32016-09-12 11:20:22 +0000467
468 unsigned IdxReg = getOrCreateVReg(*Idx);
469 if (MRI->getType(IdxReg) != OffsetTy) {
470 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
471 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
472 IdxReg = NewIdxReg;
473 }
474
475 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
476 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
477
478 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
479 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
480 BaseReg = NewBaseReg;
481 }
482 }
483
484 if (Offset != 0) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000485 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000486 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
487 return true;
488 }
489
490 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
491 return true;
492}
493
Tim Northover79f43f12017-01-30 19:33:07 +0000494bool IRTranslator::translateMemfunc(const CallInst &CI,
495 MachineIRBuilder &MIRBuilder,
496 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000497 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000498 Type *DstTy = CI.getArgOperand(0)->getType();
499 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000500 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
501 return false;
502
503 SmallVector<CallLowering::ArgInfo, 8> Args;
504 for (int i = 0; i < 3; ++i) {
505 const auto &Arg = CI.getArgOperand(i);
506 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
507 }
508
Tim Northover79f43f12017-01-30 19:33:07 +0000509 const char *Callee;
510 switch (ID) {
511 case Intrinsic::memmove:
512 case Intrinsic::memcpy: {
513 Type *SrcTy = CI.getArgOperand(1)->getType();
514 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
515 return false;
516 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
517 break;
518 }
519 case Intrinsic::memset:
520 Callee = "memset";
521 break;
522 default:
523 return false;
524 }
Tim Northover3f186032016-10-18 20:03:45 +0000525
Tim Northover79f43f12017-01-30 19:33:07 +0000526 return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000527 CallLowering::ArgInfo(0, CI.getType()), Args);
528}
Tim Northovera7653b32016-09-12 11:20:22 +0000529
Tim Northoverc53606e2016-12-07 21:29:15 +0000530void IRTranslator::getStackGuard(unsigned DstReg,
531 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000532 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
533 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000534 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
535 MIB.addDef(DstReg);
536
Tim Northover50db7f412016-12-07 21:17:47 +0000537 auto &TLI = *MF->getSubtarget().getTargetLowering();
538 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000539 if (!Global)
540 return;
541
542 MachinePointerInfo MPInfo(Global);
Tim Northover50db7f412016-12-07 21:17:47 +0000543 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
Tim Northovercdf23f12016-10-31 18:30:59 +0000544 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
545 MachineMemOperand::MODereferenceable;
546 *MemRefs =
Tim Northover50db7f412016-12-07 21:17:47 +0000547 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
548 DL->getPointerABIAlignment());
Tim Northovercdf23f12016-10-31 18:30:59 +0000549 MIB.setMemRefs(MemRefs, MemRefs + 1);
550}
551
Tim Northover1e656ec2016-12-08 22:44:00 +0000552bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
553 MachineIRBuilder &MIRBuilder) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000554 LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL);
Tim Northover1e656ec2016-12-08 22:44:00 +0000555 LLT s1 = LLT::scalar(1);
556 unsigned Width = Ty.getSizeInBits();
557 unsigned Res = MRI->createGenericVirtualRegister(Ty);
558 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
559 auto MIB = MIRBuilder.buildInstr(Op)
560 .addDef(Res)
561 .addDef(Overflow)
562 .addUse(getOrCreateVReg(*CI.getOperand(0)))
563 .addUse(getOrCreateVReg(*CI.getOperand(1)));
564
565 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000566 unsigned Zero = getOrCreateVReg(
567 *Constant::getNullValue(Type::getInt1Ty(CI.getContext())));
Tim Northover1e656ec2016-12-08 22:44:00 +0000568 MIB.addUse(Zero);
569 }
570
571 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
572 return true;
573}
574
Tim Northoverc53606e2016-12-07 21:29:15 +0000575bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
576 MachineIRBuilder &MIRBuilder) {
Tim Northover91c81732016-08-19 17:17:06 +0000577 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000578 default:
579 break;
Tim Northover0e011702017-02-10 19:10:38 +0000580 case Intrinsic::lifetime_start:
581 case Intrinsic::lifetime_end:
582 // Stack coloring is not enabled in O0 (which we care about now) so we can
583 // drop these. Make sure someone notices when we start compiling at higher
584 // opts though.
585 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
586 return false;
587 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000588 case Intrinsic::dbg_declare: {
589 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
590 assert(DI.getVariable() && "Missing variable");
591
592 const Value *Address = DI.getAddress();
593 if (!Address || isa<UndefValue>(Address)) {
594 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
595 return true;
596 }
597
Tim Northover09aac4a2017-01-26 23:39:14 +0000598 assert(DI.getVariable()->isValidLocationForIntrinsic(
599 MIRBuilder.getDebugLoc()) &&
600 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000601 auto AI = dyn_cast<AllocaInst>(Address);
602 if (AI && AI->isStaticAlloca()) {
603 // Static allocas are tracked at the MF level, no need for DBG_VALUE
604 // instructions (in fact, they get ignored if they *do* exist).
605 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
606 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Tim Northover09aac4a2017-01-26 23:39:14 +0000607 } else
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000608 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
609 DI.getVariable(), DI.getExpression());
Tim Northoverb58346f2016-12-08 22:44:13 +0000610 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000611 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000612 case Intrinsic::vaend:
613 // No target I know of cares about va_end. Certainly no in-tree target
614 // does. Simplest intrinsic ever!
615 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000616 case Intrinsic::vastart: {
617 auto &TLI = *MF->getSubtarget().getTargetLowering();
618 Value *Ptr = CI.getArgOperand(0);
619 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
620
621 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
622 .addUse(getOrCreateVReg(*Ptr))
623 .addMemOperand(MF->getMachineMemOperand(
624 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
625 return true;
626 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000627 case Intrinsic::dbg_value: {
628 // This form of DBG_VALUE is target-independent.
629 const DbgValueInst &DI = cast<DbgValueInst>(CI);
630 const Value *V = DI.getValue();
631 assert(DI.getVariable()->isValidLocationForIntrinsic(
632 MIRBuilder.getDebugLoc()) &&
633 "Expected inlined-at fields to agree");
634 if (!V) {
635 // Currently the optimizer can produce this; insert an undef to
636 // help debugging. Probably the optimizer should not do this.
637 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
638 DI.getExpression());
639 } else if (const auto *CI = dyn_cast<Constant>(V)) {
640 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
641 DI.getExpression());
642 } else {
643 unsigned Reg = getOrCreateVReg(*V);
644 // FIXME: This does not handle register-indirect values at offset 0. The
645 // direct/indirect thing shouldn't really be handled by something as
646 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
647 // pretty baked in right now.
648 if (DI.getOffset() != 0)
649 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
650 DI.getExpression());
651 else
652 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
653 DI.getExpression());
654 }
655 return true;
656 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000657 case Intrinsic::uadd_with_overflow:
658 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
659 case Intrinsic::sadd_with_overflow:
660 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
661 case Intrinsic::usub_with_overflow:
662 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
663 case Intrinsic::ssub_with_overflow:
664 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
665 case Intrinsic::umul_with_overflow:
666 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
667 case Intrinsic::smul_with_overflow:
668 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Tim Northoverb38b4e22017-02-08 23:23:32 +0000669 case Intrinsic::pow:
670 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
671 .addDef(getOrCreateVReg(CI))
672 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
673 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
674 return true;
Tim Northover3f186032016-10-18 20:03:45 +0000675 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +0000676 case Intrinsic::memmove:
677 case Intrinsic::memset:
678 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +0000679 case Intrinsic::eh_typeid_for: {
680 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
681 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +0000682 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +0000683 MIRBuilder.buildConstant(Reg, TypeID);
684 return true;
685 }
Tim Northover6e904302016-10-18 20:03:51 +0000686 case Intrinsic::objectsize: {
687 // If we don't know by now, we're never going to know.
688 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
689
690 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
691 return true;
692 }
Tim Northovercdf23f12016-10-31 18:30:59 +0000693 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +0000694 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000695 return true;
696 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000697 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +0000698 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +0000699 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000700
701 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
702 MIRBuilder.buildStore(
703 GuardVal, getOrCreateVReg(*Slot),
Tim Northover50db7f412016-12-07 21:17:47 +0000704 *MF->getMachineMemOperand(
705 MachinePointerInfo::getFixedStack(*MF,
706 getOrCreateFrameIndex(*Slot)),
Tim Northovercdf23f12016-10-31 18:30:59 +0000707 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
708 PtrTy.getSizeInBits() / 8, 8));
709 return true;
710 }
Tim Northover91c81732016-08-19 17:17:06 +0000711 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000712 return false;
Tim Northover91c81732016-08-19 17:17:06 +0000713}
714
Tim Northoveraa995c92017-03-09 23:36:26 +0000715bool IRTranslator::translateInlineAsm(const CallInst &CI,
716 MachineIRBuilder &MIRBuilder) {
717 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
718 if (!IA.getConstraintString().empty())
719 return false;
720
721 unsigned ExtraInfo = 0;
722 if (IA.hasSideEffects())
723 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
724 if (IA.getDialect() == InlineAsm::AD_Intel)
725 ExtraInfo |= InlineAsm::Extra_AsmDialect;
726
727 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
728 .addExternalSymbol(IA.getAsmString().c_str())
729 .addImm(ExtraInfo);
730
731 return true;
732}
733
Tim Northoverc53606e2016-12-07 21:29:15 +0000734bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000735 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +0000736 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +0000737 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +0000738
Tim Northover3babfef2017-01-19 23:59:35 +0000739 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +0000740 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +0000741
Tim Northover406024a2016-08-10 21:44:01 +0000742 if (!F || !F->isIntrinsic()) {
Tim Northover406024a2016-08-10 21:44:01 +0000743 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
744 SmallVector<unsigned, 8> Args;
745 for (auto &Arg: CI.arg_operands())
746 Args.push_back(getOrCreateVReg(*Arg));
747
Tim Northoverd1e951e2017-03-09 22:00:39 +0000748 MF->getFrameInfo().setHasCalls(true);
Ahmed Bougachad22b84b2017-03-10 00:25:44 +0000749 return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
Tim Northoverfe5f89b2016-08-29 19:07:08 +0000750 return getOrCreateVReg(*CI.getCalledValue());
751 });
Tim Northover406024a2016-08-10 21:44:01 +0000752 }
753
754 Intrinsic::ID ID = F->getIntrinsicID();
755 if (TII && ID == Intrinsic::not_intrinsic)
756 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
757
758 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +0000759
Tim Northoverc53606e2016-12-07 21:29:15 +0000760 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +0000761 return true;
762
Tim Northover5fb414d2016-07-29 22:32:36 +0000763 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
764 MachineInstrBuilder MIB =
Tim Northover0f140c72016-09-09 11:46:34 +0000765 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
Tim Northover5fb414d2016-07-29 22:32:36 +0000766
767 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +0000768 // Some intrinsics take metadata parameters. Reject them.
769 if (isa<MetadataAsValue>(Arg))
770 return false;
Tim Northover5fb414d2016-07-29 22:32:36 +0000771 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
772 MIB.addImm(CI->getSExtValue());
773 else
774 MIB.addUse(getOrCreateVReg(*Arg));
775 }
776 return true;
777}
778
Tim Northoverc53606e2016-12-07 21:29:15 +0000779bool IRTranslator::translateInvoke(const User &U,
780 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +0000781 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +0000782 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +0000783
784 const BasicBlock *ReturnBB = I.getSuccessor(0);
785 const BasicBlock *EHPadBB = I.getSuccessor(1);
786
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +0000787 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +0000788 const Function *Fn = dyn_cast<Function>(Callee);
789 if (isa<InlineAsm>(Callee))
790 return false;
791
792 // FIXME: support invoking patchpoint and statepoint intrinsics.
793 if (Fn && Fn->isIntrinsic())
794 return false;
795
796 // FIXME: support whatever these are.
797 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
798 return false;
799
800 // FIXME: support Windows exception handling.
801 if (!isa<LandingPadInst>(EHPadBB->front()))
802 return false;
803
804
Matthias Braund0ee66c2016-12-01 19:32:15 +0000805 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +0000806 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000807 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +0000808 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
809
810 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
Tim Northover293f7432017-01-31 18:36:11 +0000811 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +0000812 for (auto &Arg: I.arg_operands())
Tim Northover293f7432017-01-31 18:36:11 +0000813 Args.push_back(getOrCreateVReg(*Arg));
Tim Northovera9105be2016-11-09 22:39:54 +0000814
Ahmed Bougachad22b84b2017-03-10 00:25:44 +0000815 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +0000816 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
817 return false;
Tim Northovera9105be2016-11-09 22:39:54 +0000818
Matthias Braund0ee66c2016-12-01 19:32:15 +0000819 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +0000820 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
821
822 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000823 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
824 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +0000825 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +0000826 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
827 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +0000828 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +0000829
830 return true;
831}
832
Tim Northoverc53606e2016-12-07 21:29:15 +0000833bool IRTranslator::translateLandingPad(const User &U,
834 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +0000835 const LandingPadInst &LP = cast<LandingPadInst>(U);
836
837 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Matthias Braund0ee66c2016-12-01 19:32:15 +0000838 addLandingPadInfo(LP, MBB);
Tim Northovera9105be2016-11-09 22:39:54 +0000839
840 MBB.setIsEHPad();
841
842 // If there aren't registers to copy the values into (e.g., during SjLj
843 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +0000844 auto &TLI = *MF->getSubtarget().getTargetLowering();
845 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +0000846 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
847 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
848 return true;
849
850 // If landingpad's return type is token type, we don't create DAG nodes
851 // for its exception pointer and selector value. The extraction of exception
852 // pointer or selector value from token type landingpads is not currently
853 // supported.
854 if (LP.getType()->isTokenTy())
855 return true;
856
857 // Add a label to mark the beginning of the landing pad. Deletion of the
858 // landing pad can thus be detected via the MachineModuleInfo.
859 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +0000860 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +0000861
Daniel Sanders1351db42017-03-07 23:32:10 +0000862 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +0000863 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
864 MIRBuilder.buildUndef(Undef);
865
Justin Bognera0295312017-01-25 00:16:53 +0000866 SmallVector<LLT, 2> Tys;
867 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000868 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +0000869 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
870
Tim Northovera9105be2016-11-09 22:39:54 +0000871 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +0000872 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
873 if (!ExceptionReg)
874 return false;
Tim Northovera9105be2016-11-09 22:39:54 +0000875
Tim Northover542d1c12017-03-07 23:04:06 +0000876 MBB.addLiveIn(ExceptionReg);
877 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]),
878 Tmp = MRI->createGenericVirtualRegister(Ty);
879 MIRBuilder.buildCopy(VReg, ExceptionReg);
880 MIRBuilder.buildInsert(Tmp, Undef, VReg, 0);
Tim Northoverc9449702017-01-30 20:52:42 +0000881
Tim Northover542d1c12017-03-07 23:04:06 +0000882 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
883 if (!SelectorReg)
884 return false;
Tim Northoverc9449702017-01-30 20:52:42 +0000885
Tim Northover542d1c12017-03-07 23:04:06 +0000886 MBB.addLiveIn(SelectorReg);
Tim Northovera9105be2016-11-09 22:39:54 +0000887
Tim Northover542d1c12017-03-07 23:04:06 +0000888 // N.b. the exception selector register always has pointer type and may not
889 // match the actual IR-level type in the landingpad so an extra cast is
890 // needed.
891 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
892 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
893
894 VReg = MRI->createGenericVirtualRegister(Tys[1]);
895 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg);
896 MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg,
897 Tys[0].getSizeInBits());
Tim Northovera9105be2016-11-09 22:39:54 +0000898 return true;
899}
900
Tim Northoverc3e3f592017-02-03 18:22:45 +0000901bool IRTranslator::translateAlloca(const User &U,
902 MachineIRBuilder &MIRBuilder) {
903 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000904
Tim Northoverc3e3f592017-02-03 18:22:45 +0000905 if (AI.isStaticAlloca()) {
906 unsigned Res = getOrCreateVReg(AI);
907 int FI = getOrCreateFrameIndex(AI);
908 MIRBuilder.buildFrameIndex(Res, FI);
909 return true;
910 }
911
912 // Now we're in the harder dynamic case.
913 Type *Ty = AI.getAllocatedType();
914 unsigned Align =
915 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
916
917 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
918
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000919 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
920 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000921 if (MRI->getType(NumElts) != IntPtrTy) {
922 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
923 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
924 NumElts = ExtElts;
925 }
926
927 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000928 unsigned TySize =
929 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +0000930 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
931
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000932 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000933 auto &TLI = *MF->getSubtarget().getTargetLowering();
934 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
935
936 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
937 MIRBuilder.buildCopy(SPTmp, SPReg);
938
Tim Northoverc2f89562017-02-14 20:56:18 +0000939 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
940 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000941
942 // Handle alignment. We have to realign if the allocation granule was smaller
943 // than stack alignment, or the specific alloca requires more than stack
944 // alignment.
945 unsigned StackAlign =
946 MF->getSubtarget().getFrameLowering()->getStackAlignment();
947 Align = std::max(Align, StackAlign);
948 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
949 // Round the size of the allocation up to the stack alignment size
950 // by add SA-1 to the size. This doesn't overflow because we're computing
951 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +0000952 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
953 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
954 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +0000955 }
956
Tim Northoverc2f89562017-02-14 20:56:18 +0000957 MIRBuilder.buildCopy(SPReg, AllocTmp);
958 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000959
960 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
961 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +0000962 return true;
963}
964
Tim Northover4a652222017-02-15 23:22:33 +0000965bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
966 // FIXME: We may need more info about the type. Because of how LLT works,
967 // we're completely discarding the i64/double distinction here (amongst
968 // others). Fortunately the ABIs I know of where that matters don't use va_arg
969 // anyway but that's not guaranteed.
970 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
971 .addDef(getOrCreateVReg(U))
972 .addUse(getOrCreateVReg(*U.getOperand(0)))
973 .addImm(DL->getABITypeAlignment(U.getType()));
974 return true;
975}
976
Volkan Keles04cb08c2017-03-10 19:08:28 +0000977bool IRTranslator::translateInsertElement(const User &U,
978 MachineIRBuilder &MIRBuilder) {
979 // If it is a <1 x Ty> vector, use the scalar as it is
980 // not a legal vector type in LLT.
981 if (U.getType()->getVectorNumElements() == 1) {
982 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
983 ValToVReg[&U] = Elt;
984 return true;
985 }
986 MIRBuilder.buildInsertVectorElement(
987 getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
988 getOrCreateVReg(*U.getOperand(1)), getOrCreateVReg(*U.getOperand(2)));
989 return true;
990}
991
992bool IRTranslator::translateExtractElement(const User &U,
993 MachineIRBuilder &MIRBuilder) {
994 // If it is a <1 x Ty> vector, use the scalar as it is
995 // not a legal vector type in LLT.
996 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
997 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
998 ValToVReg[&U] = Elt;
999 return true;
1000 }
1001 MIRBuilder.buildExtractVectorElement(getOrCreateVReg(U),
1002 getOrCreateVReg(*U.getOperand(0)),
1003 getOrCreateVReg(*U.getOperand(1)));
1004 return true;
1005}
1006
Tim Northoverc53606e2016-12-07 21:29:15 +00001007bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001008 const PHINode &PI = cast<PHINode>(U);
Tim Northover25d12862016-09-09 11:47:31 +00001009 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
Tim Northover97d0cb32016-08-05 17:16:40 +00001010 MIB.addDef(getOrCreateVReg(PI));
1011
1012 PendingPHIs.emplace_back(&PI, MIB.getInstr());
1013 return true;
1014}
1015
1016void IRTranslator::finishPendingPhis() {
1017 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
1018 const PHINode *PI = Phi.first;
Tim Northoverc53606e2016-12-07 21:29:15 +00001019 MachineInstrBuilder MIB(*MF, Phi.second);
Tim Northover97d0cb32016-08-05 17:16:40 +00001020
1021 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1022 // won't create extra control flow here, otherwise we need to find the
1023 // dominating predecessor here (or perhaps force the weirder IRTranslators
1024 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001025 SmallSet<const BasicBlock *, 4> HandledPreds;
1026
Tim Northover97d0cb32016-08-05 17:16:40 +00001027 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001028 auto IRPred = PI->getIncomingBlock(i);
1029 if (HandledPreds.count(IRPred))
1030 continue;
1031
1032 HandledPreds.insert(IRPred);
1033 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
1034 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1035 assert(Pred->isSuccessor(MIB->getParent()) &&
1036 "incorrect CFG at MachineBasicBlock level");
1037 MIB.addUse(ValReg);
1038 MIB.addMBB(Pred);
1039 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001040 }
1041 }
1042}
1043
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001044bool IRTranslator::translate(const Instruction &Inst) {
Tim Northoverc53606e2016-12-07 21:29:15 +00001045 CurBuilder.setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001046 switch(Inst.getOpcode()) {
Tim Northover357f1be2016-08-10 23:02:41 +00001047#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001048 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001049#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001050 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001051 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001052 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001053}
1054
Tim Northover5ed648e2016-08-09 21:28:04 +00001055bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001056 if (auto CI = dyn_cast<ConstantInt>(&C))
Tim Northovercc35f902016-12-05 21:54:17 +00001057 EntryBuilder.buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001058 else if (auto CF = dyn_cast<ConstantFP>(&C))
Tim Northover0f140c72016-09-09 11:46:34 +00001059 EntryBuilder.buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001060 else if (isa<UndefValue>(C))
Tim Northover81dafc12017-03-06 18:36:40 +00001061 EntryBuilder.buildUndef(Reg);
Tim Northover8e0c53a2016-08-11 21:40:55 +00001062 else if (isa<ConstantPointerNull>(C))
Tim Northover9267ac52016-12-05 21:47:07 +00001063 EntryBuilder.buildConstant(Reg, 0);
Tim Northover032548f2016-09-12 12:10:41 +00001064 else if (auto GV = dyn_cast<GlobalValue>(&C))
1065 EntryBuilder.buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001066 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1067 if (!CAZ->getType()->isVectorTy())
1068 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001069 // Return the scalar if it is a <1 x Ty> vector.
1070 if (CAZ->getNumElements() == 1)
1071 return translate(*CAZ->getElementValue(0u), Reg);
Volkan Keles970fee42017-03-10 21:23:13 +00001072 std::vector<unsigned> Ops;
1073 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1074 Constant &Elt = *CAZ->getElementValue(i);
1075 Ops.push_back(getOrCreateVReg(Elt));
1076 }
1077 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001078 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001079 // Return the scalar if it is a <1 x Ty> vector.
1080 if (CV->getNumElements() == 1)
1081 return translate(*CV->getElementAsConstant(0), Reg);
Volkan Keles38a91a02017-03-13 21:36:19 +00001082 std::vector<unsigned> Ops;
1083 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1084 Constant &Elt = *CV->getElementAsConstant(i);
1085 Ops.push_back(getOrCreateVReg(Elt));
1086 }
1087 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001088 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001089 switch(CE->getOpcode()) {
1090#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001091 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001092#include "llvm/IR/Instruction.def"
1093 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001094 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001095 }
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001096 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001097 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001098
Tim Northoverd403a3d2016-08-09 23:01:30 +00001099 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001100}
1101
Tim Northover0d510442016-08-11 16:21:29 +00001102void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001103 // Release the memory used by the different maps we
1104 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001105 PendingPHIs.clear();
Quentin Colombetccd77252016-02-11 21:48:32 +00001106 ValToVReg.clear();
Tim Northovercdf23f12016-10-31 18:30:59 +00001107 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001108 MachinePreds.clear();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001109}
1110
Tim Northover50db7f412016-12-07 21:17:47 +00001111bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1112 MF = &CurMF;
1113 const Function &F = *MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001114 if (F.empty())
1115 return false;
Tim Northover50db7f412016-12-07 21:17:47 +00001116 CLI = MF->getSubtarget().getCallLowering();
Tim Northoverc53606e2016-12-07 21:29:15 +00001117 CurBuilder.setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001118 EntryBuilder.setMF(*MF);
1119 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001120 DL = &F.getParent()->getDataLayout();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001121 TPC = &getAnalysis<TargetPassConfig>();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001122 ORE = make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001123
Tim Northover14e7f732016-08-05 17:50:36 +00001124 assert(PendingPHIs.empty() && "stale PHIs");
1125
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001126 // Release the per-function state when we return, whether we succeeded or not.
1127 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1128
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001129 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001130 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1131 MF->push_back(EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001132 EntryBuilder.setMBB(*EntryBB);
1133
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001134 // Create all blocks, in IR order, to preserve the layout.
1135 for (const BasicBlock &BB: F) {
1136 auto *&MBB = BBToMBB[&BB];
1137
1138 MBB = MF->CreateMachineBasicBlock(&BB);
1139 MF->push_back(MBB);
1140
1141 if (BB.hasAddressTaken())
1142 MBB->setHasAddressTaken();
1143 }
1144
1145 // Make our arguments/constants entry block fallthrough to the IR entry block.
1146 EntryBB->addSuccessor(&getMBB(F.front()));
1147
Tim Northover05cc4852016-12-07 21:05:38 +00001148 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001149 SmallVector<unsigned, 8> VRegArgs;
1150 for (const Argument &Arg: F.args())
Quentin Colombete225e252016-03-11 17:27:54 +00001151 VRegArgs.push_back(getOrCreateVReg(Arg));
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001152 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001153 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1154 MF->getFunction()->getSubprogram(),
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001155 &MF->getFunction()->getEntryBlock());
1156 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1157 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001158 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001159 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001160
Tim Northover05cc4852016-12-07 21:05:38 +00001161 // And translate the function!
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001162 for (const BasicBlock &BB: F) {
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001163 MachineBasicBlock &MBB = getMBB(BB);
Quentin Colombet91ebd712016-03-11 17:27:47 +00001164 // Set the insertion point of all the following translations to
1165 // the end of this basic block.
Tim Northoverc53606e2016-12-07 21:29:15 +00001166 CurBuilder.setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001167
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001168 for (const Instruction &Inst: BB) {
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001169 if (translate(Inst))
1170 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001171
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001172 std::string InstStrStorage;
1173 raw_string_ostream InstStr(InstStrStorage);
1174 InstStr << Inst;
1175
Ahmed Bougacha7daaf882017-02-24 00:34:47 +00001176 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1177 Inst.getDebugLoc(), &BB);
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001178 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1179 << ": '" << InstStr.str() << "'";
1180 reportTranslationError(*MF, *TPC, *ORE, R);
1181 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001182 }
1183 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001184
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001185 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001186
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001187 // Now that the MachineFrameInfo has been configured, no further changes to
1188 // the reserved registers are possible.
1189 MRI->freezeReservedRegs(*MF);
Quentin Colombet327f9422016-12-15 23:32:25 +00001190
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001191 // Merge the argument lowering and constants block with its single
1192 // successor, the LLVM-IR entry block. We want the basic block to
1193 // be maximal.
1194 assert(EntryBB->succ_size() == 1 &&
1195 "Custom BB used for lowering should have only one successor");
1196 // Get the successor of the current entry block.
1197 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1198 assert(NewEntryBB.pred_size() == 1 &&
1199 "LLVM-IR entry block has a predecessor!?");
1200 // Move all the instruction from the current entry block to the
1201 // new entry block.
1202 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1203 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001204
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001205 // Update the live-in information for the new entry block.
1206 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1207 NewEntryBB.addLiveIn(LiveIn);
1208 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001209
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001210 // Get rid of the now empty basic block.
1211 EntryBB->removeSuccessor(&NewEntryBB);
1212 MF->remove(EntryBB);
1213 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001214
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001215 assert(&MF->front() == &NewEntryBB &&
1216 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001217
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001218 return false;
1219}