blob: 766187378446903fa26e2c3d58885b51d2fa4003 [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);
Ahmed Bougachae8e1fa32017-03-21 23:42:50 +0000226 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
227
228 // If the unconditional target is the layout successor, fallthrough.
229 if (!CurBB.isLayoutSuccessor(&TgtBB))
230 MIRBuilder.buildBr(TgtBB);
Tim Northover69c2ba52016-07-29 17:58:00 +0000231
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000232 // Link successors.
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000233 for (const BasicBlock *Succ : BrInst.successors())
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000234 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000235 return true;
236}
237
Kristof Beylseced0712017-01-05 11:28:51 +0000238bool IRTranslator::translateSwitch(const User &U,
239 MachineIRBuilder &MIRBuilder) {
240 // For now, just translate as a chain of conditional branches.
241 // FIXME: could we share most of the logic/code in
242 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
243 // At first sight, it seems most of the logic in there is independent of
244 // SelectionDAG-specifics and a lot of work went in to optimize switch
245 // lowering in there.
246
247 const SwitchInst &SwInst = cast<SwitchInst>(U);
248 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000249 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000250
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000251 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000252 for (auto &CaseIt : SwInst.cases()) {
253 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
254 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
255 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000256 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
257 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000258 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000259
Tim Northoverb6636fd2017-01-17 22:13:50 +0000260 MIRBuilder.buildBrCond(Tst, TrueMBB);
261 CurMBB.addSuccessor(&TrueMBB);
262 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000263
Tim Northoverb6636fd2017-01-17 22:13:50 +0000264 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000265 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000266 // Insert the comparison blocks one after the other.
267 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000268 MIRBuilder.buildBr(*FalseMBB);
269 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000270
Tim Northoverb6636fd2017-01-17 22:13:50 +0000271 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000272 }
273 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000274 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000275 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000276 MIRBuilder.buildBr(DefaultMBB);
277 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
278 CurMBB.addSuccessor(&DefaultMBB);
279 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000280
281 return true;
282}
283
Kristof Beyls65a12c02017-01-30 09:13:18 +0000284bool IRTranslator::translateIndirectBr(const User &U,
285 MachineIRBuilder &MIRBuilder) {
286 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
287
288 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
289 MIRBuilder.buildBrIndirect(Tgt);
290
291 // Link successors.
292 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
293 for (const BasicBlock *Succ : BrInst.successors())
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000294 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000295
296 return true;
297}
298
Tim Northoverc53606e2016-12-07 21:29:15 +0000299bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000300 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000301
Tim Northover7152dca2016-10-19 15:55:06 +0000302 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
303 : MachineMemOperand::MONone;
304 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000305
Tim Northoverad2b7172016-07-26 20:23:26 +0000306 unsigned Res = getOrCreateVReg(LI);
307 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000308
Tim Northoverad2b7172016-07-26 20:23:26 +0000309 MIRBuilder.buildLoad(
Tim Northover0f140c72016-09-09 11:46:34 +0000310 Res, Addr,
Tim Northover50db7f412016-12-07 21:17:47 +0000311 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
312 Flags, DL->getTypeStoreSize(LI.getType()),
Tim Northover48dfa1a2017-02-13 22:14:16 +0000313 getMemOpAlignment(LI), AAMDNodes(), nullptr,
314 LI.getSynchScope(), LI.getOrdering()));
Tim Northoverad2b7172016-07-26 20:23:26 +0000315 return true;
316}
317
Tim Northoverc53606e2016-12-07 21:29:15 +0000318bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000319 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000320 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
321 : MachineMemOperand::MONone;
322 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000323
Tim Northoverad2b7172016-07-26 20:23:26 +0000324 unsigned Val = getOrCreateVReg(*SI.getValueOperand());
325 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000326
327 MIRBuilder.buildStore(
Tim Northover50db7f412016-12-07 21:17:47 +0000328 Val, Addr,
329 *MF->getMachineMemOperand(
330 MachinePointerInfo(SI.getPointerOperand()), Flags,
331 DL->getTypeStoreSize(SI.getValueOperand()->getType()),
Tim Northover48dfa1a2017-02-13 22:14:16 +0000332 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
333 SI.getOrdering()));
Tim Northoverad2b7172016-07-26 20:23:26 +0000334 return true;
335}
336
Tim Northoverc53606e2016-12-07 21:29:15 +0000337bool IRTranslator::translateExtractValue(const User &U,
338 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000339 const Value *Src = U.getOperand(0);
340 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Tim Northover6f80b082016-08-19 17:47:05 +0000341 SmallVector<Value *, 1> Indices;
342
343 // getIndexedOffsetInType is designed for GEPs, so the first index is the
344 // usual array element rather than looking into the actual aggregate.
345 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000346
347 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
348 for (auto Idx : EVI->indices())
349 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
350 } else {
351 for (unsigned i = 1; i < U.getNumOperands(); ++i)
352 Indices.push_back(U.getOperand(i));
353 }
Tim Northover6f80b082016-08-19 17:47:05 +0000354
355 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
356
Tim Northoverb6046222016-08-19 20:09:03 +0000357 unsigned Res = getOrCreateVReg(U);
Tim Northoverc2c545b2017-03-06 23:50:28 +0000358 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset);
Tim Northover6f80b082016-08-19 17:47:05 +0000359
360 return true;
361}
362
Tim Northoverc53606e2016-12-07 21:29:15 +0000363bool IRTranslator::translateInsertValue(const User &U,
364 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000365 const Value *Src = U.getOperand(0);
366 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000367 SmallVector<Value *, 1> Indices;
368
369 // getIndexedOffsetInType is designed for GEPs, so the first index is the
370 // usual array element rather than looking into the actual aggregate.
371 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000372
373 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
374 for (auto Idx : IVI->indices())
375 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
376 } else {
377 for (unsigned i = 2; i < U.getNumOperands(); ++i)
378 Indices.push_back(U.getOperand(i));
379 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000380
381 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
382
Tim Northoverb6046222016-08-19 20:09:03 +0000383 unsigned Res = getOrCreateVReg(U);
384 const Value &Inserted = *U.getOperand(1);
Tim Northover0f140c72016-09-09 11:46:34 +0000385 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
386 Offset);
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000387
388 return true;
389}
390
Tim Northoverc53606e2016-12-07 21:29:15 +0000391bool IRTranslator::translateSelect(const User &U,
392 MachineIRBuilder &MIRBuilder) {
Tim Northover0f140c72016-09-09 11:46:34 +0000393 MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
394 getOrCreateVReg(*U.getOperand(1)),
395 getOrCreateVReg(*U.getOperand(2)));
Tim Northover5a28c362016-08-19 20:09:07 +0000396 return true;
397}
398
Tim Northoverc53606e2016-12-07 21:29:15 +0000399bool IRTranslator::translateBitCast(const User &U,
400 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000401 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000402 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
403 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000404 // Get the source vreg now, to avoid invalidating ValToVReg.
405 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Tim Northover357f1be2016-08-10 23:02:41 +0000406 unsigned &Reg = ValToVReg[&U];
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000407 // If we already assigned a vreg for this bitcast, we can't change that.
408 // Emit a copy to satisfy the users we already emitted.
Tim Northover7552ef52016-08-10 16:51:14 +0000409 if (Reg)
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000410 MIRBuilder.buildCopy(Reg, SrcReg);
Tim Northover7552ef52016-08-10 16:51:14 +0000411 else
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000412 Reg = SrcReg;
Tim Northover7c9eba92016-07-25 21:01:29 +0000413 return true;
414 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000415 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000416}
417
Tim Northoverc53606e2016-12-07 21:29:15 +0000418bool IRTranslator::translateCast(unsigned Opcode, const User &U,
419 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000420 unsigned Op = getOrCreateVReg(*U.getOperand(0));
421 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000422 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
Tim Northover7c9eba92016-07-25 21:01:29 +0000423 return true;
424}
425
Tim Northoverc53606e2016-12-07 21:29:15 +0000426bool IRTranslator::translateGetElementPtr(const User &U,
427 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000428 // FIXME: support vector GEPs.
429 if (U.getType()->isVectorTy())
430 return false;
431
432 Value &Op0 = *U.getOperand(0);
433 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000434 Type *PtrIRTy = Op0.getType();
435 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
436 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
437 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000438
439 int64_t Offset = 0;
440 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
441 GTI != E; ++GTI) {
442 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000443 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000444 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
445 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
446 continue;
447 } else {
448 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
449
450 // If this is a scalar constant or a splat vector of constants,
451 // handle it quickly.
452 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
453 Offset += ElementSize * CI->getSExtValue();
454 continue;
455 }
456
457 if (Offset != 0) {
458 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000459 unsigned OffsetReg =
460 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000461 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
462
463 BaseReg = NewBaseReg;
464 Offset = 0;
465 }
466
467 // N = N + Idx * ElementSize;
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000468 unsigned ElementSizeReg =
469 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
Tim Northovera7653b32016-09-12 11:20:22 +0000470
471 unsigned IdxReg = getOrCreateVReg(*Idx);
472 if (MRI->getType(IdxReg) != OffsetTy) {
473 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
474 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
475 IdxReg = NewIdxReg;
476 }
477
478 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
479 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
480
481 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
482 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
483 BaseReg = NewBaseReg;
484 }
485 }
486
487 if (Offset != 0) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000488 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000489 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
490 return true;
491 }
492
493 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
494 return true;
495}
496
Tim Northover79f43f12017-01-30 19:33:07 +0000497bool IRTranslator::translateMemfunc(const CallInst &CI,
498 MachineIRBuilder &MIRBuilder,
499 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000500 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000501 Type *DstTy = CI.getArgOperand(0)->getType();
502 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000503 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
504 return false;
505
506 SmallVector<CallLowering::ArgInfo, 8> Args;
507 for (int i = 0; i < 3; ++i) {
508 const auto &Arg = CI.getArgOperand(i);
509 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
510 }
511
Tim Northover79f43f12017-01-30 19:33:07 +0000512 const char *Callee;
513 switch (ID) {
514 case Intrinsic::memmove:
515 case Intrinsic::memcpy: {
516 Type *SrcTy = CI.getArgOperand(1)->getType();
517 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
518 return false;
519 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
520 break;
521 }
522 case Intrinsic::memset:
523 Callee = "memset";
524 break;
525 default:
526 return false;
527 }
Tim Northover3f186032016-10-18 20:03:45 +0000528
Diana Picusd79253a2017-03-20 14:40:18 +0000529 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
530 MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000531 CallLowering::ArgInfo(0, CI.getType()), Args);
532}
Tim Northovera7653b32016-09-12 11:20:22 +0000533
Tim Northoverc53606e2016-12-07 21:29:15 +0000534void IRTranslator::getStackGuard(unsigned DstReg,
535 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000536 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
537 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000538 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
539 MIB.addDef(DstReg);
540
Tim Northover50db7f412016-12-07 21:17:47 +0000541 auto &TLI = *MF->getSubtarget().getTargetLowering();
542 Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000543 if (!Global)
544 return;
545
546 MachinePointerInfo MPInfo(Global);
Tim Northover50db7f412016-12-07 21:17:47 +0000547 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
Tim Northovercdf23f12016-10-31 18:30:59 +0000548 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
549 MachineMemOperand::MODereferenceable;
550 *MemRefs =
Tim Northover50db7f412016-12-07 21:17:47 +0000551 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
552 DL->getPointerABIAlignment());
Tim Northovercdf23f12016-10-31 18:30:59 +0000553 MIB.setMemRefs(MemRefs, MemRefs + 1);
554}
555
Tim Northover1e656ec2016-12-08 22:44:00 +0000556bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
557 MachineIRBuilder &MIRBuilder) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000558 LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL);
Tim Northover1e656ec2016-12-08 22:44:00 +0000559 LLT s1 = LLT::scalar(1);
560 unsigned Width = Ty.getSizeInBits();
561 unsigned Res = MRI->createGenericVirtualRegister(Ty);
562 unsigned Overflow = MRI->createGenericVirtualRegister(s1);
563 auto MIB = MIRBuilder.buildInstr(Op)
564 .addDef(Res)
565 .addDef(Overflow)
566 .addUse(getOrCreateVReg(*CI.getOperand(0)))
567 .addUse(getOrCreateVReg(*CI.getOperand(1)));
568
569 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000570 unsigned Zero = getOrCreateVReg(
571 *Constant::getNullValue(Type::getInt1Ty(CI.getContext())));
Tim Northover1e656ec2016-12-08 22:44:00 +0000572 MIB.addUse(Zero);
573 }
574
575 MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
576 return true;
577}
578
Tim Northoverc53606e2016-12-07 21:29:15 +0000579bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
580 MachineIRBuilder &MIRBuilder) {
Tim Northover91c81732016-08-19 17:17:06 +0000581 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000582 default:
583 break;
Tim Northover0e011702017-02-10 19:10:38 +0000584 case Intrinsic::lifetime_start:
585 case Intrinsic::lifetime_end:
586 // Stack coloring is not enabled in O0 (which we care about now) so we can
587 // drop these. Make sure someone notices when we start compiling at higher
588 // opts though.
589 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
590 return false;
591 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000592 case Intrinsic::dbg_declare: {
593 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
594 assert(DI.getVariable() && "Missing variable");
595
596 const Value *Address = DI.getAddress();
597 if (!Address || isa<UndefValue>(Address)) {
598 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
599 return true;
600 }
601
Tim Northover09aac4a2017-01-26 23:39:14 +0000602 assert(DI.getVariable()->isValidLocationForIntrinsic(
603 MIRBuilder.getDebugLoc()) &&
604 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000605 auto AI = dyn_cast<AllocaInst>(Address);
606 if (AI && AI->isStaticAlloca()) {
607 // Static allocas are tracked at the MF level, no need for DBG_VALUE
608 // instructions (in fact, they get ignored if they *do* exist).
609 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
610 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Tim Northover09aac4a2017-01-26 23:39:14 +0000611 } else
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000612 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
613 DI.getVariable(), DI.getExpression());
Tim Northoverb58346f2016-12-08 22:44:13 +0000614 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000615 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000616 case Intrinsic::vaend:
617 // No target I know of cares about va_end. Certainly no in-tree target
618 // does. Simplest intrinsic ever!
619 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000620 case Intrinsic::vastart: {
621 auto &TLI = *MF->getSubtarget().getTargetLowering();
622 Value *Ptr = CI.getArgOperand(0);
623 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
624
625 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
626 .addUse(getOrCreateVReg(*Ptr))
627 .addMemOperand(MF->getMachineMemOperand(
628 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
629 return true;
630 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000631 case Intrinsic::dbg_value: {
632 // This form of DBG_VALUE is target-independent.
633 const DbgValueInst &DI = cast<DbgValueInst>(CI);
634 const Value *V = DI.getValue();
635 assert(DI.getVariable()->isValidLocationForIntrinsic(
636 MIRBuilder.getDebugLoc()) &&
637 "Expected inlined-at fields to agree");
638 if (!V) {
639 // Currently the optimizer can produce this; insert an undef to
640 // help debugging. Probably the optimizer should not do this.
641 MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
642 DI.getExpression());
643 } else if (const auto *CI = dyn_cast<Constant>(V)) {
644 MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
645 DI.getExpression());
646 } else {
647 unsigned Reg = getOrCreateVReg(*V);
648 // FIXME: This does not handle register-indirect values at offset 0. The
649 // direct/indirect thing shouldn't really be handled by something as
650 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
651 // pretty baked in right now.
652 if (DI.getOffset() != 0)
653 MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
654 DI.getExpression());
655 else
656 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
657 DI.getExpression());
658 }
659 return true;
660 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000661 case Intrinsic::uadd_with_overflow:
662 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
663 case Intrinsic::sadd_with_overflow:
664 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
665 case Intrinsic::usub_with_overflow:
666 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
667 case Intrinsic::ssub_with_overflow:
668 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
669 case Intrinsic::umul_with_overflow:
670 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
671 case Intrinsic::smul_with_overflow:
672 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Tim Northoverb38b4e22017-02-08 23:23:32 +0000673 case Intrinsic::pow:
674 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
675 .addDef(getOrCreateVReg(CI))
676 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
677 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
678 return true;
Tim Northover3f186032016-10-18 20:03:45 +0000679 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +0000680 case Intrinsic::memmove:
681 case Intrinsic::memset:
682 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +0000683 case Intrinsic::eh_typeid_for: {
684 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
685 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +0000686 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +0000687 MIRBuilder.buildConstant(Reg, TypeID);
688 return true;
689 }
Tim Northover6e904302016-10-18 20:03:51 +0000690 case Intrinsic::objectsize: {
691 // If we don't know by now, we're never going to know.
692 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
693
694 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
695 return true;
696 }
Tim Northovercdf23f12016-10-31 18:30:59 +0000697 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +0000698 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000699 return true;
700 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000701 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +0000702 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +0000703 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000704
705 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
706 MIRBuilder.buildStore(
707 GuardVal, getOrCreateVReg(*Slot),
Tim Northover50db7f412016-12-07 21:17:47 +0000708 *MF->getMachineMemOperand(
709 MachinePointerInfo::getFixedStack(*MF,
710 getOrCreateFrameIndex(*Slot)),
Tim Northovercdf23f12016-10-31 18:30:59 +0000711 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
712 PtrTy.getSizeInBits() / 8, 8));
713 return true;
714 }
Tim Northover91c81732016-08-19 17:17:06 +0000715 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000716 return false;
Tim Northover91c81732016-08-19 17:17:06 +0000717}
718
Tim Northoveraa995c92017-03-09 23:36:26 +0000719bool IRTranslator::translateInlineAsm(const CallInst &CI,
720 MachineIRBuilder &MIRBuilder) {
721 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
722 if (!IA.getConstraintString().empty())
723 return false;
724
725 unsigned ExtraInfo = 0;
726 if (IA.hasSideEffects())
727 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
728 if (IA.getDialect() == InlineAsm::AD_Intel)
729 ExtraInfo |= InlineAsm::Extra_AsmDialect;
730
731 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
732 .addExternalSymbol(IA.getAsmString().c_str())
733 .addImm(ExtraInfo);
734
735 return true;
736}
737
Tim Northoverc53606e2016-12-07 21:29:15 +0000738bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000739 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +0000740 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +0000741 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +0000742
Tim Northover3babfef2017-01-19 23:59:35 +0000743 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +0000744 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +0000745
Tim Northover406024a2016-08-10 21:44:01 +0000746 if (!F || !F->isIntrinsic()) {
Tim Northover406024a2016-08-10 21:44:01 +0000747 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
748 SmallVector<unsigned, 8> Args;
749 for (auto &Arg: CI.arg_operands())
750 Args.push_back(getOrCreateVReg(*Arg));
751
Tim Northoverd1e951e2017-03-09 22:00:39 +0000752 MF->getFrameInfo().setHasCalls(true);
Ahmed Bougachad22b84b2017-03-10 00:25:44 +0000753 return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
Tim Northoverfe5f89b2016-08-29 19:07:08 +0000754 return getOrCreateVReg(*CI.getCalledValue());
755 });
Tim Northover406024a2016-08-10 21:44:01 +0000756 }
757
758 Intrinsic::ID ID = F->getIntrinsicID();
759 if (TII && ID == Intrinsic::not_intrinsic)
760 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
761
762 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +0000763
Tim Northoverc53606e2016-12-07 21:29:15 +0000764 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +0000765 return true;
766
Tim Northover5fb414d2016-07-29 22:32:36 +0000767 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
768 MachineInstrBuilder MIB =
Tim Northover0f140c72016-09-09 11:46:34 +0000769 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
Tim Northover5fb414d2016-07-29 22:32:36 +0000770
771 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +0000772 // Some intrinsics take metadata parameters. Reject them.
773 if (isa<MetadataAsValue>(Arg))
774 return false;
Aditya Nandakumarbc389ba2017-03-22 01:16:39 +0000775 MIB.addUse(getOrCreateVReg(*Arg));
Tim Northover5fb414d2016-07-29 22:32:36 +0000776 }
777 return true;
778}
779
Tim Northoverc53606e2016-12-07 21:29:15 +0000780bool IRTranslator::translateInvoke(const User &U,
781 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +0000782 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +0000783 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +0000784
785 const BasicBlock *ReturnBB = I.getSuccessor(0);
786 const BasicBlock *EHPadBB = I.getSuccessor(1);
787
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +0000788 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +0000789 const Function *Fn = dyn_cast<Function>(Callee);
790 if (isa<InlineAsm>(Callee))
791 return false;
792
793 // FIXME: support invoking patchpoint and statepoint intrinsics.
794 if (Fn && Fn->isIntrinsic())
795 return false;
796
797 // FIXME: support whatever these are.
798 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
799 return false;
800
801 // FIXME: support Windows exception handling.
802 if (!isa<LandingPadInst>(EHPadBB->front()))
803 return false;
804
805
Matthias Braund0ee66c2016-12-01 19:32:15 +0000806 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +0000807 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +0000808 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +0000809 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
810
811 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
Tim Northover293f7432017-01-31 18:36:11 +0000812 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +0000813 for (auto &Arg: I.arg_operands())
Tim Northover293f7432017-01-31 18:36:11 +0000814 Args.push_back(getOrCreateVReg(*Arg));
Tim Northovera9105be2016-11-09 22:39:54 +0000815
Ahmed Bougachad22b84b2017-03-10 00:25:44 +0000816 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +0000817 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
818 return false;
Tim Northovera9105be2016-11-09 22:39:54 +0000819
Matthias Braund0ee66c2016-12-01 19:32:15 +0000820 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +0000821 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
822
823 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000824 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
825 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +0000826 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +0000827 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
828 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +0000829 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +0000830
831 return true;
832}
833
Tim Northoverc53606e2016-12-07 21:29:15 +0000834bool IRTranslator::translateLandingPad(const User &U,
835 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +0000836 const LandingPadInst &LP = cast<LandingPadInst>(U);
837
838 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Matthias Braund0ee66c2016-12-01 19:32:15 +0000839 addLandingPadInfo(LP, MBB);
Tim Northovera9105be2016-11-09 22:39:54 +0000840
841 MBB.setIsEHPad();
842
843 // If there aren't registers to copy the values into (e.g., during SjLj
844 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +0000845 auto &TLI = *MF->getSubtarget().getTargetLowering();
846 const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +0000847 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
848 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
849 return true;
850
851 // If landingpad's return type is token type, we don't create DAG nodes
852 // for its exception pointer and selector value. The extraction of exception
853 // pointer or selector value from token type landingpads is not currently
854 // supported.
855 if (LP.getType()->isTokenTy())
856 return true;
857
858 // Add a label to mark the beginning of the landing pad. Deletion of the
859 // landing pad can thus be detected via the MachineModuleInfo.
860 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +0000861 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +0000862
Daniel Sanders1351db42017-03-07 23:32:10 +0000863 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +0000864 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
865 MIRBuilder.buildUndef(Undef);
866
Justin Bognera0295312017-01-25 00:16:53 +0000867 SmallVector<LLT, 2> Tys;
868 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000869 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +0000870 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
871
Tim Northovera9105be2016-11-09 22:39:54 +0000872 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +0000873 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
874 if (!ExceptionReg)
875 return false;
Tim Northovera9105be2016-11-09 22:39:54 +0000876
Tim Northover542d1c12017-03-07 23:04:06 +0000877 MBB.addLiveIn(ExceptionReg);
878 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]),
879 Tmp = MRI->createGenericVirtualRegister(Ty);
880 MIRBuilder.buildCopy(VReg, ExceptionReg);
881 MIRBuilder.buildInsert(Tmp, Undef, VReg, 0);
Tim Northoverc9449702017-01-30 20:52:42 +0000882
Tim Northover542d1c12017-03-07 23:04:06 +0000883 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
884 if (!SelectorReg)
885 return false;
Tim Northoverc9449702017-01-30 20:52:42 +0000886
Tim Northover542d1c12017-03-07 23:04:06 +0000887 MBB.addLiveIn(SelectorReg);
Tim Northovera9105be2016-11-09 22:39:54 +0000888
Tim Northover542d1c12017-03-07 23:04:06 +0000889 // N.b. the exception selector register always has pointer type and may not
890 // match the actual IR-level type in the landingpad so an extra cast is
891 // needed.
892 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
893 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
894
895 VReg = MRI->createGenericVirtualRegister(Tys[1]);
896 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg);
897 MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg,
898 Tys[0].getSizeInBits());
Tim Northovera9105be2016-11-09 22:39:54 +0000899 return true;
900}
901
Tim Northoverc3e3f592017-02-03 18:22:45 +0000902bool IRTranslator::translateAlloca(const User &U,
903 MachineIRBuilder &MIRBuilder) {
904 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000905
Tim Northoverc3e3f592017-02-03 18:22:45 +0000906 if (AI.isStaticAlloca()) {
907 unsigned Res = getOrCreateVReg(AI);
908 int FI = getOrCreateFrameIndex(AI);
909 MIRBuilder.buildFrameIndex(Res, FI);
910 return true;
911 }
912
913 // Now we're in the harder dynamic case.
914 Type *Ty = AI.getAllocatedType();
915 unsigned Align =
916 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
917
918 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
919
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000920 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
921 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000922 if (MRI->getType(NumElts) != IntPtrTy) {
923 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
924 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
925 NumElts = ExtElts;
926 }
927
928 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000929 unsigned TySize =
930 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +0000931 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
932
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000933 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000934 auto &TLI = *MF->getSubtarget().getTargetLowering();
935 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
936
937 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
938 MIRBuilder.buildCopy(SPTmp, SPReg);
939
Tim Northoverc2f89562017-02-14 20:56:18 +0000940 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
941 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000942
943 // Handle alignment. We have to realign if the allocation granule was smaller
944 // than stack alignment, or the specific alloca requires more than stack
945 // alignment.
946 unsigned StackAlign =
947 MF->getSubtarget().getFrameLowering()->getStackAlignment();
948 Align = std::max(Align, StackAlign);
949 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
950 // Round the size of the allocation up to the stack alignment size
951 // by add SA-1 to the size. This doesn't overflow because we're computing
952 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +0000953 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
954 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
955 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +0000956 }
957
Tim Northoverc2f89562017-02-14 20:56:18 +0000958 MIRBuilder.buildCopy(SPReg, AllocTmp);
959 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +0000960
961 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
962 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +0000963 return true;
964}
965
Tim Northover4a652222017-02-15 23:22:33 +0000966bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
967 // FIXME: We may need more info about the type. Because of how LLT works,
968 // we're completely discarding the i64/double distinction here (amongst
969 // others). Fortunately the ABIs I know of where that matters don't use va_arg
970 // anyway but that's not guaranteed.
971 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
972 .addDef(getOrCreateVReg(U))
973 .addUse(getOrCreateVReg(*U.getOperand(0)))
974 .addImm(DL->getABITypeAlignment(U.getType()));
975 return true;
976}
977
Volkan Keles04cb08c2017-03-10 19:08:28 +0000978bool IRTranslator::translateInsertElement(const User &U,
979 MachineIRBuilder &MIRBuilder) {
980 // If it is a <1 x Ty> vector, use the scalar as it is
981 // not a legal vector type in LLT.
982 if (U.getType()->getVectorNumElements() == 1) {
983 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
984 ValToVReg[&U] = Elt;
985 return true;
986 }
987 MIRBuilder.buildInsertVectorElement(
988 getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
989 getOrCreateVReg(*U.getOperand(1)), getOrCreateVReg(*U.getOperand(2)));
990 return true;
991}
992
993bool IRTranslator::translateExtractElement(const User &U,
994 MachineIRBuilder &MIRBuilder) {
995 // If it is a <1 x Ty> vector, use the scalar as it is
996 // not a legal vector type in LLT.
997 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
998 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
999 ValToVReg[&U] = Elt;
1000 return true;
1001 }
1002 MIRBuilder.buildExtractVectorElement(getOrCreateVReg(U),
1003 getOrCreateVReg(*U.getOperand(0)),
1004 getOrCreateVReg(*U.getOperand(1)));
1005 return true;
1006}
1007
Volkan Keles75bdc762017-03-21 08:44:13 +00001008bool IRTranslator::translateShuffleVector(const User &U,
1009 MachineIRBuilder &MIRBuilder) {
1010 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1011 .addDef(getOrCreateVReg(U))
1012 .addUse(getOrCreateVReg(*U.getOperand(0)))
1013 .addUse(getOrCreateVReg(*U.getOperand(1)))
1014 .addUse(getOrCreateVReg(*U.getOperand(2)));
1015 return true;
1016}
1017
Tim Northoverc53606e2016-12-07 21:29:15 +00001018bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001019 const PHINode &PI = cast<PHINode>(U);
Tim Northover25d12862016-09-09 11:47:31 +00001020 auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
Tim Northover97d0cb32016-08-05 17:16:40 +00001021 MIB.addDef(getOrCreateVReg(PI));
1022
1023 PendingPHIs.emplace_back(&PI, MIB.getInstr());
1024 return true;
1025}
1026
1027void IRTranslator::finishPendingPhis() {
1028 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
1029 const PHINode *PI = Phi.first;
Tim Northoverc53606e2016-12-07 21:29:15 +00001030 MachineInstrBuilder MIB(*MF, Phi.second);
Tim Northover97d0cb32016-08-05 17:16:40 +00001031
1032 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1033 // won't create extra control flow here, otherwise we need to find the
1034 // dominating predecessor here (or perhaps force the weirder IRTranslators
1035 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001036 SmallSet<const BasicBlock *, 4> HandledPreds;
1037
Tim Northover97d0cb32016-08-05 17:16:40 +00001038 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001039 auto IRPred = PI->getIncomingBlock(i);
1040 if (HandledPreds.count(IRPred))
1041 continue;
1042
1043 HandledPreds.insert(IRPred);
1044 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
1045 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1046 assert(Pred->isSuccessor(MIB->getParent()) &&
1047 "incorrect CFG at MachineBasicBlock level");
1048 MIB.addUse(ValReg);
1049 MIB.addMBB(Pred);
1050 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001051 }
1052 }
1053}
1054
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001055bool IRTranslator::translate(const Instruction &Inst) {
Tim Northoverc53606e2016-12-07 21:29:15 +00001056 CurBuilder.setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001057 switch(Inst.getOpcode()) {
Tim Northover357f1be2016-08-10 23:02:41 +00001058#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001059 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001060#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001061 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001062 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001063 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001064}
1065
Tim Northover5ed648e2016-08-09 21:28:04 +00001066bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001067 if (auto CI = dyn_cast<ConstantInt>(&C))
Tim Northovercc35f902016-12-05 21:54:17 +00001068 EntryBuilder.buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001069 else if (auto CF = dyn_cast<ConstantFP>(&C))
Tim Northover0f140c72016-09-09 11:46:34 +00001070 EntryBuilder.buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001071 else if (isa<UndefValue>(C))
Tim Northover81dafc12017-03-06 18:36:40 +00001072 EntryBuilder.buildUndef(Reg);
Tim Northover8e0c53a2016-08-11 21:40:55 +00001073 else if (isa<ConstantPointerNull>(C))
Tim Northover9267ac52016-12-05 21:47:07 +00001074 EntryBuilder.buildConstant(Reg, 0);
Tim Northover032548f2016-09-12 12:10:41 +00001075 else if (auto GV = dyn_cast<GlobalValue>(&C))
1076 EntryBuilder.buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001077 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1078 if (!CAZ->getType()->isVectorTy())
1079 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001080 // Return the scalar if it is a <1 x Ty> vector.
1081 if (CAZ->getNumElements() == 1)
1082 return translate(*CAZ->getElementValue(0u), Reg);
Volkan Keles970fee42017-03-10 21:23:13 +00001083 std::vector<unsigned> Ops;
1084 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1085 Constant &Elt = *CAZ->getElementValue(i);
1086 Ops.push_back(getOrCreateVReg(Elt));
1087 }
1088 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001089 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001090 // Return the scalar if it is a <1 x Ty> vector.
1091 if (CV->getNumElements() == 1)
1092 return translate(*CV->getElementAsConstant(0), Reg);
Volkan Keles38a91a02017-03-13 21:36:19 +00001093 std::vector<unsigned> Ops;
1094 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1095 Constant &Elt = *CV->getElementAsConstant(i);
1096 Ops.push_back(getOrCreateVReg(Elt));
1097 }
1098 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001099 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001100 switch(CE->getOpcode()) {
1101#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001102 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001103#include "llvm/IR/Instruction.def"
1104 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001105 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001106 }
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001107 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001108 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001109
Tim Northoverd403a3d2016-08-09 23:01:30 +00001110 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001111}
1112
Tim Northover0d510442016-08-11 16:21:29 +00001113void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001114 // Release the memory used by the different maps we
1115 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001116 PendingPHIs.clear();
Quentin Colombetccd77252016-02-11 21:48:32 +00001117 ValToVReg.clear();
Tim Northovercdf23f12016-10-31 18:30:59 +00001118 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001119 MachinePreds.clear();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001120}
1121
Tim Northover50db7f412016-12-07 21:17:47 +00001122bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1123 MF = &CurMF;
1124 const Function &F = *MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001125 if (F.empty())
1126 return false;
Tim Northover50db7f412016-12-07 21:17:47 +00001127 CLI = MF->getSubtarget().getCallLowering();
Tim Northoverc53606e2016-12-07 21:29:15 +00001128 CurBuilder.setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001129 EntryBuilder.setMF(*MF);
1130 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001131 DL = &F.getParent()->getDataLayout();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001132 TPC = &getAnalysis<TargetPassConfig>();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001133 ORE = make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001134
Tim Northover14e7f732016-08-05 17:50:36 +00001135 assert(PendingPHIs.empty() && "stale PHIs");
1136
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001137 // Release the per-function state when we return, whether we succeeded or not.
1138 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1139
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001140 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001141 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1142 MF->push_back(EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001143 EntryBuilder.setMBB(*EntryBB);
1144
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001145 // Create all blocks, in IR order, to preserve the layout.
1146 for (const BasicBlock &BB: F) {
1147 auto *&MBB = BBToMBB[&BB];
1148
1149 MBB = MF->CreateMachineBasicBlock(&BB);
1150 MF->push_back(MBB);
1151
1152 if (BB.hasAddressTaken())
1153 MBB->setHasAddressTaken();
1154 }
1155
1156 // Make our arguments/constants entry block fallthrough to the IR entry block.
1157 EntryBB->addSuccessor(&getMBB(F.front()));
1158
Tim Northover05cc4852016-12-07 21:05:38 +00001159 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001160 SmallVector<unsigned, 8> VRegArgs;
1161 for (const Argument &Arg: F.args())
Quentin Colombete225e252016-03-11 17:27:54 +00001162 VRegArgs.push_back(getOrCreateVReg(Arg));
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001163 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001164 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1165 MF->getFunction()->getSubprogram(),
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001166 &MF->getFunction()->getEntryBlock());
1167 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1168 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001169 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001170 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001171
Tim Northover05cc4852016-12-07 21:05:38 +00001172 // And translate the function!
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001173 for (const BasicBlock &BB: F) {
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001174 MachineBasicBlock &MBB = getMBB(BB);
Quentin Colombet91ebd712016-03-11 17:27:47 +00001175 // Set the insertion point of all the following translations to
1176 // the end of this basic block.
Tim Northoverc53606e2016-12-07 21:29:15 +00001177 CurBuilder.setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001178
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001179 for (const Instruction &Inst: BB) {
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001180 if (translate(Inst))
1181 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001182
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001183 std::string InstStrStorage;
1184 raw_string_ostream InstStr(InstStrStorage);
1185 InstStr << Inst;
1186
Ahmed Bougacha7daaf882017-02-24 00:34:47 +00001187 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1188 Inst.getDebugLoc(), &BB);
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001189 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst)
1190 << ": '" << InstStr.str() << "'";
1191 reportTranslationError(*MF, *TPC, *ORE, R);
1192 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001193 }
1194 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001195
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001196 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001197
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001198 // Now that the MachineFrameInfo has been configured, no further changes to
1199 // the reserved registers are possible.
1200 MRI->freezeReservedRegs(*MF);
Quentin Colombet327f9422016-12-15 23:32:25 +00001201
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001202 // Merge the argument lowering and constants block with its single
1203 // successor, the LLVM-IR entry block. We want the basic block to
1204 // be maximal.
1205 assert(EntryBB->succ_size() == 1 &&
1206 "Custom BB used for lowering should have only one successor");
1207 // Get the successor of the current entry block.
1208 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1209 assert(NewEntryBB.pred_size() == 1 &&
1210 "LLVM-IR entry block has a predecessor!?");
1211 // Move all the instruction from the current entry block to the
1212 // new entry block.
1213 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1214 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001215
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001216 // Update the live-in information for the new entry block.
1217 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1218 NewEntryBB.addLiveIn(LiveIn);
1219 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001220
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001221 // Get rid of the now empty basic block.
1222 EntryBB->removeSuccessor(&NewEntryBB);
1223 MF->remove(EntryBB);
1224 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001225
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001226 assert(&MF->front() == &NewEntryBB &&
1227 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001228
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001229 return false;
1230}