blob: 80da50562d3232c638ada50fdd158a4b86ee9416 [file] [log] [blame]
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001//===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
Quentin Colombet105cf2b2016-01-20 20:58:56 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This file implements the IRTranslator class.
11//===----------------------------------------------------------------------===//
12
13#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
Amara Emerson6cdfe292018-08-01 02:17:42 +000014#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000015#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +000016#include "llvm/ADT/ScopeExit.h"
Tim Northoverb6636fd2017-01-17 22:13:50 +000017#include "llvm/ADT/SmallSet.h"
Quentin Colombetfd9d0a02016-02-11 19:59:41 +000018#include "llvm/ADT/SmallVector.h"
Adam Nemet0965da22017-10-09 23:19:02 +000019#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Tim Northovera9105be2016-11-09 22:39:54 +000020#include "llvm/CodeGen/Analysis.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000021#include "llvm/CodeGen/GlobalISel/CallLowering.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000022#include "llvm/CodeGen/LowLevelType.h"
23#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northoverbd505462016-07-22 16:59:52 +000024#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000025#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineMemOperand.h"
28#include "llvm/CodeGen/MachineOperand.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Matthias Braun90ad6832018-07-13 00:08:38 +000030#include "llvm/CodeGen/StackProtector.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000031#include "llvm/CodeGen/TargetFrameLowering.h"
32#include "llvm/CodeGen/TargetLowering.h"
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000033#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000034#include "llvm/CodeGen/TargetRegisterInfo.h"
35#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000036#include "llvm/IR/BasicBlock.h"
Amara Emerson6cdfe292018-08-01 02:17:42 +000037#include "llvm/IR/CFG.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000038#include "llvm/IR/Constant.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000039#include "llvm/IR/Constants.h"
40#include "llvm/IR/DataLayout.h"
Tim Northover09aac4a2017-01-26 23:39:14 +000041#include "llvm/IR/DebugInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000042#include "llvm/IR/DerivedTypes.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000043#include "llvm/IR/Function.h"
Tim Northovera7653b32016-09-12 11:20:22 +000044#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000045#include "llvm/IR/InlineAsm.h"
46#include "llvm/IR/InstrTypes.h"
47#include "llvm/IR/Instructions.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000048#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000049#include "llvm/IR/Intrinsics.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Metadata.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000052#include "llvm/IR/Type.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000053#include "llvm/IR/User.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000054#include "llvm/IR/Value.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000055#include "llvm/MC/MCContext.h"
56#include "llvm/Pass.h"
57#include "llvm/Support/Casting.h"
58#include "llvm/Support/CodeGen.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/ErrorHandling.h"
61#include "llvm/Support/LowLevelTypeImpl.h"
62#include "llvm/Support/MathExtras.h"
63#include "llvm/Support/raw_ostream.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000064#include "llvm/Target/TargetIntrinsicInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000065#include "llvm/Target/TargetMachine.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000066#include <algorithm>
67#include <cassert>
68#include <cstdint>
69#include <iterator>
70#include <string>
71#include <utility>
72#include <vector>
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000073
74#define DEBUG_TYPE "irtranslator"
75
Quentin Colombet105cf2b2016-01-20 20:58:56 +000076using namespace llvm;
77
78char IRTranslator::ID = 0;
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000079
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000080INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
81 false, false)
82INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
83INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
Tim Northover884b47e2016-07-26 03:29:18 +000084 false, false)
Quentin Colombet105cf2b2016-01-20 20:58:56 +000085
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000086static void reportTranslationError(MachineFunction &MF,
87 const TargetPassConfig &TPC,
88 OptimizationRemarkEmitter &ORE,
89 OptimizationRemarkMissed &R) {
90 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
91
92 // Print the function name explicitly if we don't have a debug location (which
93 // makes the diagnostic less useful) or if we're going to emit a raw error.
94 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
95 R << (" (in function: " + MF.getName() + ")").str();
96
97 if (TPC.isGlobalISelAbortEnabled())
98 report_fatal_error(R.getMsg());
99 else
100 ORE.emit(R);
Tim Northover60f23492016-11-08 01:12:17 +0000101}
102
Eugene Zelenko76bf48d2017-06-26 22:44:03 +0000103IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
Quentin Colombet39293d32016-03-08 01:38:55 +0000104 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
Quentin Colombeta7fae162016-02-11 17:53:23 +0000105}
106
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000107void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
Matthias Braun90ad6832018-07-13 00:08:38 +0000108 AU.addRequired<StackProtector>();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000109 AU.addRequired<TargetPassConfig>();
Matthias Braun90ad6832018-07-13 00:08:38 +0000110 getSelectionDAGFallbackAnalysisUsage(AU);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000111 MachineFunctionPass::getAnalysisUsage(AU);
112}
113
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000114static void computeValueLLTs(const DataLayout &DL, Type &Ty,
115 SmallVectorImpl<LLT> &ValueTys,
116 SmallVectorImpl<uint64_t> *Offsets = nullptr,
117 uint64_t StartingOffset = 0) {
118 // Given a struct type, recursively traverse the elements.
119 if (StructType *STy = dyn_cast<StructType>(&Ty)) {
120 const StructLayout *SL = DL.getStructLayout(STy);
121 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
122 computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
123 StartingOffset + SL->getElementOffset(I));
124 return;
125 }
126 // Given an array type, recursively traverse the elements.
127 if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
128 Type *EltTy = ATy->getElementType();
129 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
130 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
131 computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
132 StartingOffset + i * EltSize);
133 return;
134 }
135 // Interpret void as zero return values.
136 if (Ty.isVoidTy())
137 return;
138 // Base case: we can get an LLT for this LLVM IR type.
139 ValueTys.push_back(getLLTForType(Ty, DL));
140 if (Offsets != nullptr)
141 Offsets->push_back(StartingOffset * 8);
142}
Tim Northover5ed648e2016-08-09 21:28:04 +0000143
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000144IRTranslator::ValueToVRegInfo::VRegListT &
145IRTranslator::allocateVRegs(const Value &Val) {
146 assert(!VMap.contains(Val) && "Value already allocated in VMap");
147 auto *Regs = VMap.getVRegs(Val);
148 auto *Offsets = VMap.getOffsets(Val);
149 SmallVector<LLT, 4> SplitTys;
150 computeValueLLTs(*DL, *Val.getType(), SplitTys,
151 Offsets->empty() ? Offsets : nullptr);
152 for (unsigned i = 0; i < SplitTys.size(); ++i)
153 Regs->push_back(0);
154 return *Regs;
155}
Tim Northover9e35f1e2017-01-25 20:58:22 +0000156
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000157ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
158 auto VRegsIt = VMap.findVRegs(Val);
159 if (VRegsIt != VMap.vregs_end())
160 return *VRegsIt->second;
161
162 if (Val.getType()->isVoidTy())
163 return *VMap.getVRegs(Val);
164
165 // Create entry for this type.
166 auto *VRegs = VMap.getVRegs(Val);
167 auto *Offsets = VMap.getOffsets(Val);
168
Tim Northover9e35f1e2017-01-25 20:58:22 +0000169 assert(Val.getType()->isSized() &&
170 "Don't know how to create an empty vreg");
Tim Northover9e35f1e2017-01-25 20:58:22 +0000171
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000172 SmallVector<LLT, 4> SplitTys;
173 computeValueLLTs(*DL, *Val.getType(), SplitTys,
174 Offsets->empty() ? Offsets : nullptr);
175
176 if (!isa<Constant>(Val)) {
177 for (auto Ty : SplitTys)
178 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
179 return *VRegs;
180 }
181
182 if (Val.getType()->isAggregateType()) {
183 // UndefValue, ConstantAggregateZero
184 auto &C = cast<Constant>(Val);
185 unsigned Idx = 0;
186 while (auto Elt = C.getAggregateElement(Idx++)) {
187 auto EltRegs = getOrCreateVRegs(*Elt);
188 std::copy(EltRegs.begin(), EltRegs.end(), std::back_inserter(*VRegs));
189 }
190 } else {
191 assert(SplitTys.size() == 1 && "unexpectedly split LLT");
192 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
193 bool Success = translate(cast<Constant>(Val), VRegs->front());
Tim Northover9e35f1e2017-01-25 20:58:22 +0000194 if (!Success) {
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000195 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +0000196 MF->getFunction().getSubprogram(),
197 &MF->getFunction().getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000198 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
199 reportTranslationError(*MF, *TPC, *ORE, R);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000200 return *VRegs;
Tim Northover5ed648e2016-08-09 21:28:04 +0000201 }
Quentin Colombet17c494b2016-02-11 17:51:31 +0000202 }
Tim Northover7f3ad2e2017-01-20 23:25:17 +0000203
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000204 return *VRegs;
Quentin Colombet17c494b2016-02-11 17:51:31 +0000205}
206
Tim Northovercdf23f12016-10-31 18:30:59 +0000207int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
208 if (FrameIndices.find(&AI) != FrameIndices.end())
209 return FrameIndices[&AI];
210
Tim Northovercdf23f12016-10-31 18:30:59 +0000211 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
212 unsigned Size =
213 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
214
215 // Always allocate at least one byte.
216 Size = std::max(Size, 1u);
217
218 unsigned Alignment = AI.getAlignment();
219 if (!Alignment)
220 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
221
222 int &FI = FrameIndices[&AI];
Tim Northover50db7f412016-12-07 21:17:47 +0000223 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
Tim Northovercdf23f12016-10-31 18:30:59 +0000224 return FI;
225}
226
Tim Northoverad2b7172016-07-26 20:23:26 +0000227unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
228 unsigned Alignment = 0;
229 Type *ValTy = nullptr;
230 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
231 Alignment = SI->getAlignment();
232 ValTy = SI->getValueOperand()->getType();
233 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
234 Alignment = LI->getAlignment();
235 ValTy = LI->getType();
Daniel Sanders94813992018-07-09 19:33:40 +0000236 } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
237 // TODO(PR27168): This instruction has no alignment attribute, but unlike
238 // the default alignment for load/store, the default here is to assume
239 // it has NATURAL alignment, not DataLayout-specified alignment.
240 const DataLayout &DL = AI->getModule()->getDataLayout();
241 Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
242 ValTy = AI->getCompareOperand()->getType();
243 } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
244 // TODO(PR27168): This instruction has no alignment attribute, but unlike
245 // the default alignment for load/store, the default here is to assume
246 // it has NATURAL alignment, not DataLayout-specified alignment.
247 const DataLayout &DL = AI->getModule()->getDataLayout();
248 Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
249 ValTy = AI->getType();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000250 } else {
251 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
252 R << "unable to translate memop: " << ore::NV("Opcode", &I);
253 reportTranslationError(*MF, *TPC, *ORE, R);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000254 return 1;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000255 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000256
257 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
258}
259
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000260MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
Quentin Colombet53237a92016-03-11 17:27:43 +0000261 MachineBasicBlock *&MBB = BBToMBB[&BB];
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000262 assert(MBB && "BasicBlock was not encountered before");
Quentin Colombet17c494b2016-02-11 17:51:31 +0000263 return *MBB;
264}
265
Tim Northoverb6636fd2017-01-17 22:13:50 +0000266void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
267 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
268 MachinePreds[Edge].push_back(NewPred);
269}
270
Tim Northoverc53606e2016-12-07 21:29:15 +0000271bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
272 MachineIRBuilder &MIRBuilder) {
Tim Northover0d56e052016-07-29 18:11:21 +0000273 // FIXME: handle signed/unsigned wrapping flags.
274
Quentin Colombet2ecff3b2016-02-10 22:59:27 +0000275 // Get or create a virtual register for each value.
276 // Unless the value is a Constant => loadimm cst?
277 // or inline constant each time?
278 // Creation of a virtual register needs to have a size.
Tim Northover357f1be2016-08-10 23:02:41 +0000279 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
280 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
281 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000282 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
Quentin Colombet17c494b2016-02-11 17:51:31 +0000283 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000284}
285
Volkan Keles20d3c422017-03-07 18:03:28 +0000286bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
287 // -0.0 - X --> G_FNEG
288 if (isa<Constant>(U.getOperand(0)) &&
289 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
290 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
291 .addDef(getOrCreateVReg(U))
292 .addUse(getOrCreateVReg(*U.getOperand(1)));
293 return true;
294 }
295 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
296}
297
Tim Northoverc53606e2016-12-07 21:29:15 +0000298bool IRTranslator::translateCompare(const User &U,
299 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000300 const CmpInst *CI = dyn_cast<CmpInst>(&U);
301 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
302 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
303 unsigned Res = getOrCreateVReg(U);
304 CmpInst::Predicate Pred =
305 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
306 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000307 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000308 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000309 else if (Pred == CmpInst::FCMP_FALSE)
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000310 MIRBuilder.buildCopy(
311 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
312 else if (Pred == CmpInst::FCMP_TRUE)
313 MIRBuilder.buildCopy(
314 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000315 else
Tim Northover0f140c72016-09-09 11:46:34 +0000316 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000317
Tim Northoverde3aea0412016-08-17 20:25:25 +0000318 return true;
319}
320
Tim Northoverc53606e2016-12-07 21:29:15 +0000321bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000322 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000323 const Value *Ret = RI.getReturnValue();
Amara Emersond78d65c2017-11-30 20:06:02 +0000324 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
325 Ret = nullptr;
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000326 // The target may mess up with the insertion point, but
327 // this is not important as a return is the last instruction
328 // of the block anyway.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000329
330 // FIXME: this interface should simplify when CallLowering gets adapted to
331 // multiple VRegs per Value.
332 unsigned VReg = Ret ? packRegs(*Ret, MIRBuilder) : 0;
333 return CLI->lowerReturn(MIRBuilder, Ret, VReg);
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000334}
335
Tim Northoverc53606e2016-12-07 21:29:15 +0000336bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000337 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000338 unsigned Succ = 0;
339 if (!BrInst.isUnconditional()) {
340 // We want a G_BRCOND to the true BB followed by an unconditional branch.
341 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
342 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000343 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000344 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000345 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000346
347 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000348 MachineBasicBlock &TgtBB = getMBB(BrTgt);
Ahmed Bougachae8e1fa32017-03-21 23:42:50 +0000349 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
350
351 // If the unconditional target is the layout successor, fallthrough.
352 if (!CurBB.isLayoutSuccessor(&TgtBB))
353 MIRBuilder.buildBr(TgtBB);
Tim Northover69c2ba52016-07-29 17:58:00 +0000354
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000355 // Link successors.
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000356 for (const BasicBlock *Succ : BrInst.successors())
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000357 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000358 return true;
359}
360
Kristof Beylseced0712017-01-05 11:28:51 +0000361bool IRTranslator::translateSwitch(const User &U,
362 MachineIRBuilder &MIRBuilder) {
363 // For now, just translate as a chain of conditional branches.
364 // FIXME: could we share most of the logic/code in
365 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
366 // At first sight, it seems most of the logic in there is independent of
367 // SelectionDAG-specifics and a lot of work went in to optimize switch
368 // lowering in there.
369
370 const SwitchInst &SwInst = cast<SwitchInst>(U);
371 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000372 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000373
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000374 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000375 for (auto &CaseIt : SwInst.cases()) {
376 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
377 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
378 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000379 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
380 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000381 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000382
Tim Northoverb6636fd2017-01-17 22:13:50 +0000383 MIRBuilder.buildBrCond(Tst, TrueMBB);
384 CurMBB.addSuccessor(&TrueMBB);
385 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000386
Tim Northoverb6636fd2017-01-17 22:13:50 +0000387 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000388 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000389 // Insert the comparison blocks one after the other.
390 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000391 MIRBuilder.buildBr(*FalseMBB);
392 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000393
Tim Northoverb6636fd2017-01-17 22:13:50 +0000394 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000395 }
396 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000397 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000398 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000399 MIRBuilder.buildBr(DefaultMBB);
400 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
401 CurMBB.addSuccessor(&DefaultMBB);
402 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000403
404 return true;
405}
406
Kristof Beyls65a12c02017-01-30 09:13:18 +0000407bool IRTranslator::translateIndirectBr(const User &U,
408 MachineIRBuilder &MIRBuilder) {
409 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
410
411 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
412 MIRBuilder.buildBrIndirect(Tgt);
413
414 // Link successors.
415 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
416 for (const BasicBlock *Succ : BrInst.successors())
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000417 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000418
419 return true;
420}
421
Tim Northoverc53606e2016-12-07 21:29:15 +0000422bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000423 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000424
Tim Northover7152dca2016-10-19 15:55:06 +0000425 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
426 : MachineMemOperand::MONone;
427 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000428
Amara Emersond78d65c2017-11-30 20:06:02 +0000429 if (DL->getTypeStoreSize(LI.getType()) == 0)
430 return true;
431
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000432 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
433 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
434 unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000435
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000436 for (unsigned i = 0; i < Regs.size(); ++i) {
437 unsigned Addr = 0;
438 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
439
440 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
441 unsigned BaseAlign = getMemOpAlignment(LI);
442 auto MMO = MF->getMachineMemOperand(
443 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
444 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
445 LI.getSyncScopeID(), LI.getOrdering());
446 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
447 }
448
Tim Northoverad2b7172016-07-26 20:23:26 +0000449 return true;
450}
451
Tim Northoverc53606e2016-12-07 21:29:15 +0000452bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000453 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000454 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
455 : MachineMemOperand::MONone;
456 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000457
Amara Emersond78d65c2017-11-30 20:06:02 +0000458 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
459 return true;
460
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000461 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
462 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
463 unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000464
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000465 for (unsigned i = 0; i < Vals.size(); ++i) {
466 unsigned Addr = 0;
467 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
468
469 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
470 unsigned BaseAlign = getMemOpAlignment(SI);
471 auto MMO = MF->getMachineMemOperand(
472 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
473 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
474 SI.getSyncScopeID(), SI.getOrdering());
475 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
476 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000477 return true;
478}
479
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000480static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
Tim Northoverb6046222016-08-19 20:09:03 +0000481 const Value *Src = U.getOperand(0);
482 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Volkan Keles6a36c642017-05-19 09:47:02 +0000483
Tim Northover6f80b082016-08-19 17:47:05 +0000484 // getIndexedOffsetInType is designed for GEPs, so the first index is the
485 // usual array element rather than looking into the actual aggregate.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000486 SmallVector<Value *, 1> Indices;
Tim Northover6f80b082016-08-19 17:47:05 +0000487 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000488
489 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
490 for (auto Idx : EVI->indices())
491 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000492 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
493 for (auto Idx : IVI->indices())
494 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Tim Northoverb6046222016-08-19 20:09:03 +0000495 } else {
496 for (unsigned i = 1; i < U.getNumOperands(); ++i)
497 Indices.push_back(U.getOperand(i));
498 }
Tim Northover6f80b082016-08-19 17:47:05 +0000499
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000500 return 8 * static_cast<uint64_t>(
501 DL.getIndexedOffsetInType(Src->getType(), Indices));
502}
Tim Northover6f80b082016-08-19 17:47:05 +0000503
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000504bool IRTranslator::translateExtractValue(const User &U,
505 MachineIRBuilder &MIRBuilder) {
506 const Value *Src = U.getOperand(0);
507 uint64_t Offset = getOffsetFromIndices(U, *DL);
508 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
509 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
510 unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
511 Offsets.begin();
512 auto &DstRegs = allocateVRegs(U);
513
514 for (unsigned i = 0; i < DstRegs.size(); ++i)
515 DstRegs[i] = SrcRegs[Idx++];
Tim Northover6f80b082016-08-19 17:47:05 +0000516
517 return true;
518}
519
Tim Northoverc53606e2016-12-07 21:29:15 +0000520bool IRTranslator::translateInsertValue(const User &U,
521 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000522 const Value *Src = U.getOperand(0);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000523 uint64_t Offset = getOffsetFromIndices(U, *DL);
524 auto &DstRegs = allocateVRegs(U);
525 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
526 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
527 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
528 auto InsertedIt = InsertedRegs.begin();
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000529
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000530 for (unsigned i = 0; i < DstRegs.size(); ++i) {
531 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
532 DstRegs[i] = *InsertedIt++;
533 else
534 DstRegs[i] = SrcRegs[i];
Tim Northoverb6046222016-08-19 20:09:03 +0000535 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000536
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000537 return true;
538}
539
Tim Northoverc53606e2016-12-07 21:29:15 +0000540bool IRTranslator::translateSelect(const User &U,
541 MachineIRBuilder &MIRBuilder) {
Kristof Beyls7a713502017-04-19 06:38:37 +0000542 unsigned Tst = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000543 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
544 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
545 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
546
547 for (unsigned i = 0; i < ResRegs.size(); ++i)
548 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i]);
549
Tim Northover5a28c362016-08-19 20:09:07 +0000550 return true;
551}
552
Tim Northoverc53606e2016-12-07 21:29:15 +0000553bool IRTranslator::translateBitCast(const User &U,
554 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000555 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000556 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
557 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000558 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000559 auto &Regs = *VMap.getVRegs(U);
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000560 // If we already assigned a vreg for this bitcast, we can't change that.
561 // Emit a copy to satisfy the users we already emitted.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000562 if (!Regs.empty())
563 MIRBuilder.buildCopy(Regs[0], SrcReg);
564 else {
565 Regs.push_back(SrcReg);
566 VMap.getOffsets(U)->push_back(0);
567 }
Tim Northover7c9eba92016-07-25 21:01:29 +0000568 return true;
569 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000570 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000571}
572
Tim Northoverc53606e2016-12-07 21:29:15 +0000573bool IRTranslator::translateCast(unsigned Opcode, const User &U,
574 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000575 unsigned Op = getOrCreateVReg(*U.getOperand(0));
576 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000577 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
Tim Northover7c9eba92016-07-25 21:01:29 +0000578 return true;
579}
580
Tim Northoverc53606e2016-12-07 21:29:15 +0000581bool IRTranslator::translateGetElementPtr(const User &U,
582 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000583 // FIXME: support vector GEPs.
584 if (U.getType()->isVectorTy())
585 return false;
586
587 Value &Op0 = *U.getOperand(0);
588 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000589 Type *PtrIRTy = Op0.getType();
590 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
591 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
592 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000593
594 int64_t Offset = 0;
595 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
596 GTI != E; ++GTI) {
597 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000598 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000599 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
600 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
601 continue;
602 } else {
603 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
604
605 // If this is a scalar constant or a splat vector of constants,
606 // handle it quickly.
607 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
608 Offset += ElementSize * CI->getSExtValue();
609 continue;
610 }
611
612 if (Offset != 0) {
613 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000614 unsigned OffsetReg =
615 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000616 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
617
618 BaseReg = NewBaseReg;
619 Offset = 0;
620 }
621
Tim Northovera7653b32016-09-12 11:20:22 +0000622 unsigned IdxReg = getOrCreateVReg(*Idx);
623 if (MRI->getType(IdxReg) != OffsetTy) {
624 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
625 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
626 IdxReg = NewIdxReg;
627 }
628
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000629 // N = N + Idx * ElementSize;
630 // Avoid doing it for ElementSize of 1.
631 unsigned GepOffsetReg;
632 if (ElementSize != 1) {
633 unsigned ElementSizeReg =
634 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
635
636 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
637 MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
638 } else
639 GepOffsetReg = IdxReg;
Tim Northovera7653b32016-09-12 11:20:22 +0000640
641 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000642 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
Tim Northovera7653b32016-09-12 11:20:22 +0000643 BaseReg = NewBaseReg;
644 }
645 }
646
647 if (Offset != 0) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000648 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000649 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
650 return true;
651 }
652
653 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
654 return true;
655}
656
Tim Northover79f43f12017-01-30 19:33:07 +0000657bool IRTranslator::translateMemfunc(const CallInst &CI,
658 MachineIRBuilder &MIRBuilder,
659 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000660 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000661 Type *DstTy = CI.getArgOperand(0)->getType();
662 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000663 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
664 return false;
665
666 SmallVector<CallLowering::ArgInfo, 8> Args;
667 for (int i = 0; i < 3; ++i) {
668 const auto &Arg = CI.getArgOperand(i);
669 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
670 }
671
Tim Northover79f43f12017-01-30 19:33:07 +0000672 const char *Callee;
673 switch (ID) {
674 case Intrinsic::memmove:
675 case Intrinsic::memcpy: {
676 Type *SrcTy = CI.getArgOperand(1)->getType();
677 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
678 return false;
679 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
680 break;
681 }
682 case Intrinsic::memset:
683 Callee = "memset";
684 break;
685 default:
686 return false;
687 }
Tim Northover3f186032016-10-18 20:03:45 +0000688
Diana Picusd79253a2017-03-20 14:40:18 +0000689 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
690 MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000691 CallLowering::ArgInfo(0, CI.getType()), Args);
692}
Tim Northovera7653b32016-09-12 11:20:22 +0000693
Tim Northoverc53606e2016-12-07 21:29:15 +0000694void IRTranslator::getStackGuard(unsigned DstReg,
695 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000696 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
697 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000698 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
699 MIB.addDef(DstReg);
700
Tim Northover50db7f412016-12-07 21:17:47 +0000701 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +0000702 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000703 if (!Global)
704 return;
705
706 MachinePointerInfo MPInfo(Global);
Tim Northover50db7f412016-12-07 21:17:47 +0000707 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
Tim Northovercdf23f12016-10-31 18:30:59 +0000708 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
709 MachineMemOperand::MODereferenceable;
710 *MemRefs =
Tim Northover50db7f412016-12-07 21:17:47 +0000711 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
Fangrui Songe73534462017-11-15 06:17:32 +0000712 DL->getPointerABIAlignment(0));
Tim Northovercdf23f12016-10-31 18:30:59 +0000713 MIB.setMemRefs(MemRefs, MemRefs + 1);
714}
715
Tim Northover1e656ec2016-12-08 22:44:00 +0000716bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
717 MachineIRBuilder &MIRBuilder) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000718 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
Tim Northover1e656ec2016-12-08 22:44:00 +0000719 auto MIB = MIRBuilder.buildInstr(Op)
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000720 .addDef(ResRegs[0])
721 .addDef(ResRegs[1])
Tim Northover1e656ec2016-12-08 22:44:00 +0000722 .addUse(getOrCreateVReg(*CI.getOperand(0)))
723 .addUse(getOrCreateVReg(*CI.getOperand(1)));
724
725 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000726 unsigned Zero = getOrCreateVReg(
727 *Constant::getNullValue(Type::getInt1Ty(CI.getContext())));
Tim Northover1e656ec2016-12-08 22:44:00 +0000728 MIB.addUse(Zero);
729 }
730
Tim Northover1e656ec2016-12-08 22:44:00 +0000731 return true;
732}
733
Tim Northoverc53606e2016-12-07 21:29:15 +0000734bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
735 MachineIRBuilder &MIRBuilder) {
Tim Northover91c81732016-08-19 17:17:06 +0000736 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000737 default:
738 break;
Tim Northover0e011702017-02-10 19:10:38 +0000739 case Intrinsic::lifetime_start:
740 case Intrinsic::lifetime_end:
741 // Stack coloring is not enabled in O0 (which we care about now) so we can
742 // drop these. Make sure someone notices when we start compiling at higher
743 // opts though.
744 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
745 return false;
746 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000747 case Intrinsic::dbg_declare: {
748 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
749 assert(DI.getVariable() && "Missing variable");
750
751 const Value *Address = DI.getAddress();
752 if (!Address || isa<UndefValue>(Address)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000753 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Tim Northover09aac4a2017-01-26 23:39:14 +0000754 return true;
755 }
756
Tim Northover09aac4a2017-01-26 23:39:14 +0000757 assert(DI.getVariable()->isValidLocationForIntrinsic(
758 MIRBuilder.getDebugLoc()) &&
759 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000760 auto AI = dyn_cast<AllocaInst>(Address);
761 if (AI && AI->isStaticAlloca()) {
762 // Static allocas are tracked at the MF level, no need for DBG_VALUE
763 // instructions (in fact, they get ignored if they *do* exist).
764 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
765 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Tim Northover09aac4a2017-01-26 23:39:14 +0000766 } else
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000767 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
768 DI.getVariable(), DI.getExpression());
Tim Northoverb58346f2016-12-08 22:44:13 +0000769 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000770 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000771 case Intrinsic::vaend:
772 // No target I know of cares about va_end. Certainly no in-tree target
773 // does. Simplest intrinsic ever!
774 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000775 case Intrinsic::vastart: {
776 auto &TLI = *MF->getSubtarget().getTargetLowering();
777 Value *Ptr = CI.getArgOperand(0);
778 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
779
780 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
781 .addUse(getOrCreateVReg(*Ptr))
782 .addMemOperand(MF->getMachineMemOperand(
783 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
784 return true;
785 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000786 case Intrinsic::dbg_value: {
787 // This form of DBG_VALUE is target-independent.
788 const DbgValueInst &DI = cast<DbgValueInst>(CI);
789 const Value *V = DI.getValue();
790 assert(DI.getVariable()->isValidLocationForIntrinsic(
791 MIRBuilder.getDebugLoc()) &&
792 "Expected inlined-at fields to agree");
793 if (!V) {
794 // Currently the optimizer can produce this; insert an undef to
795 // help debugging. Probably the optimizer should not do this.
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000796 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000797 } else if (const auto *CI = dyn_cast<Constant>(V)) {
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000798 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000799 } else {
800 unsigned Reg = getOrCreateVReg(*V);
801 // FIXME: This does not handle register-indirect values at offset 0. The
802 // direct/indirect thing shouldn't really be handled by something as
803 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
804 // pretty baked in right now.
Adrian Prantlabe04752017-07-28 20:21:02 +0000805 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000806 }
807 return true;
808 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000809 case Intrinsic::uadd_with_overflow:
810 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
811 case Intrinsic::sadd_with_overflow:
812 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
813 case Intrinsic::usub_with_overflow:
814 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
815 case Intrinsic::ssub_with_overflow:
816 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
817 case Intrinsic::umul_with_overflow:
818 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
819 case Intrinsic::smul_with_overflow:
820 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Tim Northoverb38b4e22017-02-08 23:23:32 +0000821 case Intrinsic::pow:
822 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
823 .addDef(getOrCreateVReg(CI))
824 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
825 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
826 return true;
Aditya Nandakumarcca75d22017-06-27 22:19:32 +0000827 case Intrinsic::exp:
828 MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
829 .addDef(getOrCreateVReg(CI))
830 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
831 return true;
832 case Intrinsic::exp2:
833 MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
834 .addDef(getOrCreateVReg(CI))
835 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
836 return true;
Aditya Nandakumar20f62072017-06-29 23:43:44 +0000837 case Intrinsic::log:
838 MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
839 .addDef(getOrCreateVReg(CI))
840 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
841 return true;
842 case Intrinsic::log2:
843 MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
844 .addDef(getOrCreateVReg(CI))
845 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
846 return true;
Volkan Keles2bc42e92018-03-05 22:31:55 +0000847 case Intrinsic::fabs:
848 MIRBuilder.buildInstr(TargetOpcode::G_FABS)
849 .addDef(getOrCreateVReg(CI))
850 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
851 return true;
Aditya Nandakumarc6a41912017-06-20 19:25:23 +0000852 case Intrinsic::fma:
853 MIRBuilder.buildInstr(TargetOpcode::G_FMA)
854 .addDef(getOrCreateVReg(CI))
855 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
856 .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
857 .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
858 return true;
Volkan Keles92837632018-02-13 00:47:46 +0000859 case Intrinsic::fmuladd: {
860 const TargetMachine &TM = MF->getTarget();
861 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
862 unsigned Dst = getOrCreateVReg(CI);
863 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
864 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
865 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
866 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
867 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
868 // TODO: Revisit this to see if we should move this part of the
869 // lowering to the combiner.
870 MIRBuilder.buildInstr(TargetOpcode::G_FMA, Dst, Op0, Op1, Op2);
871 } else {
872 LLT Ty = getLLTForType(*CI.getType(), *DL);
873 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, Ty, Op0, Op1);
874 MIRBuilder.buildInstr(TargetOpcode::G_FADD, Dst, FMul, Op2);
875 }
876 return true;
877 }
Tim Northover3f186032016-10-18 20:03:45 +0000878 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +0000879 case Intrinsic::memmove:
880 case Intrinsic::memset:
881 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +0000882 case Intrinsic::eh_typeid_for: {
883 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
884 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +0000885 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +0000886 MIRBuilder.buildConstant(Reg, TypeID);
887 return true;
888 }
Tim Northover6e904302016-10-18 20:03:51 +0000889 case Intrinsic::objectsize: {
890 // If we don't know by now, we're never going to know.
891 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
892
893 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
894 return true;
895 }
Tim Northovercdf23f12016-10-31 18:30:59 +0000896 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +0000897 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000898 return true;
899 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000900 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +0000901 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +0000902 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +0000903
904 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
905 MIRBuilder.buildStore(
906 GuardVal, getOrCreateVReg(*Slot),
Tim Northover50db7f412016-12-07 21:17:47 +0000907 *MF->getMachineMemOperand(
908 MachinePointerInfo::getFixedStack(*MF,
909 getOrCreateFrameIndex(*Slot)),
Tim Northovercdf23f12016-10-31 18:30:59 +0000910 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
911 PtrTy.getSizeInBits() / 8, 8));
912 return true;
913 }
Tim Northover91c81732016-08-19 17:17:06 +0000914 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000915 return false;
Tim Northover91c81732016-08-19 17:17:06 +0000916}
917
Tim Northoveraa995c92017-03-09 23:36:26 +0000918bool IRTranslator::translateInlineAsm(const CallInst &CI,
919 MachineIRBuilder &MIRBuilder) {
920 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
921 if (!IA.getConstraintString().empty())
922 return false;
923
924 unsigned ExtraInfo = 0;
925 if (IA.hasSideEffects())
926 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
927 if (IA.getDialect() == InlineAsm::AD_Intel)
928 ExtraInfo |= InlineAsm::Extra_AsmDialect;
929
930 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
931 .addExternalSymbol(IA.getAsmString().c_str())
932 .addImm(ExtraInfo);
933
934 return true;
935}
936
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000937unsigned IRTranslator::packRegs(const Value &V,
938 MachineIRBuilder &MIRBuilder) {
939 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
940 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
941 LLT BigTy = getLLTForType(*V.getType(), *DL);
942
943 if (Regs.size() == 1)
944 return Regs[0];
945
946 unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
947 MIRBuilder.buildUndef(Dst);
948 for (unsigned i = 0; i < Regs.size(); ++i) {
949 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
950 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
951 Dst = NewDst;
952 }
953 return Dst;
954}
955
956void IRTranslator::unpackRegs(const Value &V, unsigned Src,
957 MachineIRBuilder &MIRBuilder) {
958 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
959 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
960
961 for (unsigned i = 0; i < Regs.size(); ++i)
962 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
963}
964
Tim Northoverc53606e2016-12-07 21:29:15 +0000965bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000966 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +0000967 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +0000968 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +0000969
Martin Storsjocc981d22018-01-30 19:50:58 +0000970 // FIXME: support Windows dllimport function calls.
971 if (F && F->hasDLLImportStorageClass())
972 return false;
973
Tim Northover3babfef2017-01-19 23:59:35 +0000974 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +0000975 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +0000976
Amara Emerson913918c2018-01-02 18:56:39 +0000977 Intrinsic::ID ID = Intrinsic::not_intrinsic;
978 if (F && F->isIntrinsic()) {
979 ID = F->getIntrinsicID();
980 if (TII && ID == Intrinsic::not_intrinsic)
981 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
982 }
983
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000984 bool IsSplitType = valueIsSplit(CI);
Amara Emerson913918c2018-01-02 18:56:39 +0000985 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000986 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
987 getLLTForType(*CI.getType(), *DL))
988 : getOrCreateVReg(CI);
989
Tim Northover406024a2016-08-10 21:44:01 +0000990 SmallVector<unsigned, 8> Args;
991 for (auto &Arg: CI.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000992 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northover406024a2016-08-10 21:44:01 +0000993
Tim Northoverd1e951e2017-03-09 22:00:39 +0000994 MF->getFrameInfo().setHasCalls(true);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000995 bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
Tim Northoverfe5f89b2016-08-29 19:07:08 +0000996 return getOrCreateVReg(*CI.getCalledValue());
997 });
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000998
999 if (IsSplitType)
1000 unpackRegs(CI, Res, MIRBuilder);
1001 return Success;
Tim Northover406024a2016-08-10 21:44:01 +00001002 }
1003
Tim Northover406024a2016-08-10 21:44:01 +00001004 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +00001005
Tim Northoverc53606e2016-12-07 21:29:15 +00001006 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +00001007 return true;
1008
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001009 unsigned Res = 0;
1010 if (!CI.getType()->isVoidTy()) {
1011 if (IsSplitType)
1012 Res =
1013 MRI->createGenericVirtualRegister(getLLTForType(*CI.getType(), *DL));
1014 else
1015 Res = getOrCreateVReg(CI);
1016 }
Tim Northover5fb414d2016-07-29 22:32:36 +00001017 MachineInstrBuilder MIB =
Tim Northover0f140c72016-09-09 11:46:34 +00001018 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
Tim Northover5fb414d2016-07-29 22:32:36 +00001019
1020 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +00001021 // Some intrinsics take metadata parameters. Reject them.
1022 if (isa<MetadataAsValue>(Arg))
1023 return false;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001024 MIB.addUse(packRegs(*Arg, MIRBuilder));
Tim Northover5fb414d2016-07-29 22:32:36 +00001025 }
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001026
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001027 if (IsSplitType)
1028 unpackRegs(CI, Res, MIRBuilder);
1029
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001030 // Add a MachineMemOperand if it is a target mem intrinsic.
1031 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1032 TargetLowering::IntrinsicInfo Info;
1033 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
Matt Arsenault7d7adf42017-12-14 22:34:10 +00001034 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
Jonas Paulssonf0ff20f2017-11-28 14:44:32 +00001035 uint64_t Size = Info.memVT.getStoreSize();
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001036 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
Matt Arsenault11171332017-12-14 21:39:51 +00001037 Info.flags, Size, Info.align));
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001038 }
1039
Tim Northover5fb414d2016-07-29 22:32:36 +00001040 return true;
1041}
1042
Tim Northoverc53606e2016-12-07 21:29:15 +00001043bool IRTranslator::translateInvoke(const User &U,
1044 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001045 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001046 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +00001047
1048 const BasicBlock *ReturnBB = I.getSuccessor(0);
1049 const BasicBlock *EHPadBB = I.getSuccessor(1);
1050
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001051 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +00001052 const Function *Fn = dyn_cast<Function>(Callee);
1053 if (isa<InlineAsm>(Callee))
1054 return false;
1055
1056 // FIXME: support invoking patchpoint and statepoint intrinsics.
1057 if (Fn && Fn->isIntrinsic())
1058 return false;
1059
1060 // FIXME: support whatever these are.
1061 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1062 return false;
1063
1064 // FIXME: support Windows exception handling.
1065 if (!isa<LandingPadInst>(EHPadBB->front()))
1066 return false;
1067
Matthias Braund0ee66c2016-12-01 19:32:15 +00001068 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +00001069 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +00001070 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001071 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1072
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001073 unsigned Res =
1074 MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
Tim Northover293f7432017-01-31 18:36:11 +00001075 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +00001076 for (auto &Arg: I.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001077 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northovera9105be2016-11-09 22:39:54 +00001078
Ahmed Bougachad22b84b2017-03-10 00:25:44 +00001079 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001080 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1081 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001082
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001083 unpackRegs(I, Res, MIRBuilder);
1084
Matthias Braund0ee66c2016-12-01 19:32:15 +00001085 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001086 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1087
1088 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001089 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1090 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +00001091 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +00001092 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1093 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +00001094 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001095
1096 return true;
1097}
1098
Tim Northoverc53606e2016-12-07 21:29:15 +00001099bool IRTranslator::translateLandingPad(const User &U,
1100 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001101 const LandingPadInst &LP = cast<LandingPadInst>(U);
1102
1103 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Matthias Braund0ee66c2016-12-01 19:32:15 +00001104 addLandingPadInfo(LP, MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001105
1106 MBB.setIsEHPad();
1107
1108 // If there aren't registers to copy the values into (e.g., during SjLj
1109 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +00001110 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +00001111 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +00001112 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1113 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1114 return true;
1115
1116 // If landingpad's return type is token type, we don't create DAG nodes
1117 // for its exception pointer and selector value. The extraction of exception
1118 // pointer or selector value from token type landingpads is not currently
1119 // supported.
1120 if (LP.getType()->isTokenTy())
1121 return true;
1122
1123 // Add a label to mark the beginning of the landing pad. Deletion of the
1124 // landing pad can thus be detected via the MachineModuleInfo.
1125 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +00001126 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +00001127
Daniel Sanders1351db42017-03-07 23:32:10 +00001128 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +00001129 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1130 MIRBuilder.buildUndef(Undef);
1131
Justin Bognera0295312017-01-25 00:16:53 +00001132 SmallVector<LLT, 2> Tys;
1133 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001134 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +00001135 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1136
Tim Northovera9105be2016-11-09 22:39:54 +00001137 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +00001138 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1139 if (!ExceptionReg)
1140 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001141
Tim Northover542d1c12017-03-07 23:04:06 +00001142 MBB.addLiveIn(ExceptionReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001143 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1144 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
Tim Northoverc9449702017-01-30 20:52:42 +00001145
Tim Northover542d1c12017-03-07 23:04:06 +00001146 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1147 if (!SelectorReg)
1148 return false;
Tim Northoverc9449702017-01-30 20:52:42 +00001149
Tim Northover542d1c12017-03-07 23:04:06 +00001150 MBB.addLiveIn(SelectorReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001151 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1152 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001153 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001154
Tim Northovera9105be2016-11-09 22:39:54 +00001155 return true;
1156}
1157
Tim Northoverc3e3f592017-02-03 18:22:45 +00001158bool IRTranslator::translateAlloca(const User &U,
1159 MachineIRBuilder &MIRBuilder) {
1160 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001161
Amara Emersonfdd089a2018-07-26 01:25:58 +00001162 if (AI.isSwiftError())
1163 return false;
1164
Tim Northoverc3e3f592017-02-03 18:22:45 +00001165 if (AI.isStaticAlloca()) {
1166 unsigned Res = getOrCreateVReg(AI);
1167 int FI = getOrCreateFrameIndex(AI);
1168 MIRBuilder.buildFrameIndex(Res, FI);
1169 return true;
1170 }
1171
Martin Storsjoa63a5b92018-02-17 14:26:32 +00001172 // FIXME: support stack probing for Windows.
1173 if (MF->getTarget().getTargetTriple().isOSWindows())
1174 return false;
1175
Tim Northoverc3e3f592017-02-03 18:22:45 +00001176 // Now we're in the harder dynamic case.
1177 Type *Ty = AI.getAllocatedType();
1178 unsigned Align =
1179 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1180
1181 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1182
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001183 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1184 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001185 if (MRI->getType(NumElts) != IntPtrTy) {
1186 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1187 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1188 NumElts = ExtElts;
1189 }
1190
1191 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001192 unsigned TySize =
1193 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +00001194 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1195
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001196 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001197 auto &TLI = *MF->getSubtarget().getTargetLowering();
1198 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1199
1200 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1201 MIRBuilder.buildCopy(SPTmp, SPReg);
1202
Tim Northoverc2f89562017-02-14 20:56:18 +00001203 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1204 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001205
1206 // Handle alignment. We have to realign if the allocation granule was smaller
1207 // than stack alignment, or the specific alloca requires more than stack
1208 // alignment.
1209 unsigned StackAlign =
1210 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1211 Align = std::max(Align, StackAlign);
1212 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1213 // Round the size of the allocation up to the stack alignment size
1214 // by add SA-1 to the size. This doesn't overflow because we're computing
1215 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +00001216 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1217 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1218 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +00001219 }
1220
Tim Northoverc2f89562017-02-14 20:56:18 +00001221 MIRBuilder.buildCopy(SPReg, AllocTmp);
1222 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001223
1224 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1225 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +00001226 return true;
1227}
1228
Tim Northover4a652222017-02-15 23:22:33 +00001229bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1230 // FIXME: We may need more info about the type. Because of how LLT works,
1231 // we're completely discarding the i64/double distinction here (amongst
1232 // others). Fortunately the ABIs I know of where that matters don't use va_arg
1233 // anyway but that's not guaranteed.
1234 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1235 .addDef(getOrCreateVReg(U))
1236 .addUse(getOrCreateVReg(*U.getOperand(0)))
1237 .addImm(DL->getABITypeAlignment(U.getType()));
1238 return true;
1239}
1240
Volkan Keles04cb08c2017-03-10 19:08:28 +00001241bool IRTranslator::translateInsertElement(const User &U,
1242 MachineIRBuilder &MIRBuilder) {
1243 // If it is a <1 x Ty> vector, use the scalar as it is
1244 // not a legal vector type in LLT.
1245 if (U.getType()->getVectorNumElements() == 1) {
1246 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001247 auto &Regs = *VMap.getVRegs(U);
1248 if (Regs.empty()) {
1249 Regs.push_back(Elt);
1250 VMap.getOffsets(U)->push_back(0);
1251 } else {
1252 MIRBuilder.buildCopy(Regs[0], Elt);
1253 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001254 return true;
1255 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001256
Kristof Beyls7a713502017-04-19 06:38:37 +00001257 unsigned Res = getOrCreateVReg(U);
1258 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1259 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1260 unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1261 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001262 return true;
1263}
1264
1265bool IRTranslator::translateExtractElement(const User &U,
1266 MachineIRBuilder &MIRBuilder) {
1267 // If it is a <1 x Ty> vector, use the scalar as it is
1268 // not a legal vector type in LLT.
1269 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1270 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001271 auto &Regs = *VMap.getVRegs(U);
1272 if (Regs.empty()) {
1273 Regs.push_back(Elt);
1274 VMap.getOffsets(U)->push_back(0);
1275 } else {
1276 MIRBuilder.buildCopy(Regs[0], Elt);
1277 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001278 return true;
1279 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001280 unsigned Res = getOrCreateVReg(U);
1281 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1282 unsigned Idx = getOrCreateVReg(*U.getOperand(1));
1283 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001284 return true;
1285}
1286
Volkan Keles75bdc762017-03-21 08:44:13 +00001287bool IRTranslator::translateShuffleVector(const User &U,
1288 MachineIRBuilder &MIRBuilder) {
1289 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1290 .addDef(getOrCreateVReg(U))
1291 .addUse(getOrCreateVReg(*U.getOperand(0)))
1292 .addUse(getOrCreateVReg(*U.getOperand(1)))
1293 .addUse(getOrCreateVReg(*U.getOperand(2)));
1294 return true;
1295}
1296
Tim Northoverc53606e2016-12-07 21:29:15 +00001297bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001298 const PHINode &PI = cast<PHINode>(U);
Tim Northover97d0cb32016-08-05 17:16:40 +00001299
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001300 SmallVector<MachineInstr *, 4> Insts;
1301 for (auto Reg : getOrCreateVRegs(PI)) {
1302 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, Reg);
1303 Insts.push_back(MIB.getInstr());
1304 }
1305
1306 PendingPHIs.emplace_back(&PI, std::move(Insts));
Tim Northover97d0cb32016-08-05 17:16:40 +00001307 return true;
1308}
1309
Daniel Sanders94813992018-07-09 19:33:40 +00001310bool IRTranslator::translateAtomicCmpXchg(const User &U,
1311 MachineIRBuilder &MIRBuilder) {
1312 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1313
1314 if (I.isWeak())
1315 return false;
1316
1317 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1318 : MachineMemOperand::MONone;
1319 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1320
1321 Type *ResType = I.getType();
1322 Type *ValType = ResType->Type::getStructElementType(0);
1323
1324 auto Res = getOrCreateVRegs(I);
1325 unsigned OldValRes = Res[0];
1326 unsigned SuccessRes = Res[1];
1327 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1328 unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1329 unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1330
1331 MIRBuilder.buildAtomicCmpXchgWithSuccess(
1332 OldValRes, SuccessRes, Addr, Cmp, NewVal,
1333 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1334 Flags, DL->getTypeStoreSize(ValType),
1335 getMemOpAlignment(I), AAMDNodes(), nullptr,
1336 I.getSyncScopeID(), I.getSuccessOrdering(),
1337 I.getFailureOrdering()));
1338 return true;
1339}
1340
1341bool IRTranslator::translateAtomicRMW(const User &U,
1342 MachineIRBuilder &MIRBuilder) {
1343 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1344
1345 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1346 : MachineMemOperand::MONone;
1347 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1348
1349 Type *ResType = I.getType();
1350
1351 unsigned Res = getOrCreateVReg(I);
1352 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1353 unsigned Val = getOrCreateVReg(*I.getValOperand());
1354
1355 unsigned Opcode = 0;
1356 switch (I.getOperation()) {
1357 default:
1358 llvm_unreachable("Unknown atomicrmw op");
1359 return false;
1360 case AtomicRMWInst::Xchg:
1361 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1362 break;
1363 case AtomicRMWInst::Add:
1364 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1365 break;
1366 case AtomicRMWInst::Sub:
1367 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1368 break;
1369 case AtomicRMWInst::And:
1370 Opcode = TargetOpcode::G_ATOMICRMW_AND;
1371 break;
1372 case AtomicRMWInst::Nand:
1373 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1374 break;
1375 case AtomicRMWInst::Or:
1376 Opcode = TargetOpcode::G_ATOMICRMW_OR;
1377 break;
1378 case AtomicRMWInst::Xor:
1379 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1380 break;
1381 case AtomicRMWInst::Max:
1382 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1383 break;
1384 case AtomicRMWInst::Min:
1385 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1386 break;
1387 case AtomicRMWInst::UMax:
1388 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1389 break;
1390 case AtomicRMWInst::UMin:
1391 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1392 break;
1393 }
1394
1395 MIRBuilder.buildAtomicRMW(
1396 Opcode, Res, Addr, Val,
1397 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1398 Flags, DL->getTypeStoreSize(ResType),
1399 getMemOpAlignment(I), AAMDNodes(), nullptr,
1400 I.getSyncScopeID(), I.getOrdering()));
1401 return true;
1402}
1403
Tim Northover97d0cb32016-08-05 17:16:40 +00001404void IRTranslator::finishPendingPhis() {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001405 for (auto &Phi : PendingPHIs) {
Tim Northover97d0cb32016-08-05 17:16:40 +00001406 const PHINode *PI = Phi.first;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001407 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
Tim Northover97d0cb32016-08-05 17:16:40 +00001408
1409 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1410 // won't create extra control flow here, otherwise we need to find the
1411 // dominating predecessor here (or perhaps force the weirder IRTranslators
1412 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001413 SmallSet<const BasicBlock *, 4> HandledPreds;
1414
Tim Northover97d0cb32016-08-05 17:16:40 +00001415 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001416 auto IRPred = PI->getIncomingBlock(i);
1417 if (HandledPreds.count(IRPred))
1418 continue;
1419
1420 HandledPreds.insert(IRPred);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001421 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
Tim Northoverb6636fd2017-01-17 22:13:50 +00001422 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001423 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
Tim Northoverb6636fd2017-01-17 22:13:50 +00001424 "incorrect CFG at MachineBasicBlock level");
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001425 for (unsigned j = 0; j < ValRegs.size(); ++j) {
1426 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1427 MIB.addUse(ValRegs[j]);
1428 MIB.addMBB(Pred);
1429 }
Tim Northoverb6636fd2017-01-17 22:13:50 +00001430 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001431 }
1432 }
1433}
1434
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001435bool IRTranslator::valueIsSplit(const Value &V,
1436 SmallVectorImpl<uint64_t> *Offsets) {
1437 SmallVector<LLT, 4> SplitTys;
1438 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1439 return SplitTys.size() > 1;
1440}
1441
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001442bool IRTranslator::translate(const Instruction &Inst) {
Tim Northoverc53606e2016-12-07 21:29:15 +00001443 CurBuilder.setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001444 switch(Inst.getOpcode()) {
Tim Northover357f1be2016-08-10 23:02:41 +00001445#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001446 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001447#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001448 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001449 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001450 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001451}
1452
Tim Northover5ed648e2016-08-09 21:28:04 +00001453bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001454 if (auto CI = dyn_cast<ConstantInt>(&C))
Tim Northovercc35f902016-12-05 21:54:17 +00001455 EntryBuilder.buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001456 else if (auto CF = dyn_cast<ConstantFP>(&C))
Tim Northover0f140c72016-09-09 11:46:34 +00001457 EntryBuilder.buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001458 else if (isa<UndefValue>(C))
Tim Northover81dafc12017-03-06 18:36:40 +00001459 EntryBuilder.buildUndef(Reg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001460 else if (isa<ConstantPointerNull>(C)) {
1461 // As we are trying to build a constant val of 0 into a pointer,
1462 // insert a cast to make them correct with respect to types.
1463 unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1464 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1465 auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1466 unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1467 EntryBuilder.buildCast(Reg, ZeroReg);
1468 } else if (auto GV = dyn_cast<GlobalValue>(&C))
Tim Northover032548f2016-09-12 12:10:41 +00001469 EntryBuilder.buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001470 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1471 if (!CAZ->getType()->isVectorTy())
1472 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001473 // Return the scalar if it is a <1 x Ty> vector.
1474 if (CAZ->getNumElements() == 1)
1475 return translate(*CAZ->getElementValue(0u), Reg);
Volkan Keles970fee42017-03-10 21:23:13 +00001476 std::vector<unsigned> Ops;
1477 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1478 Constant &Elt = *CAZ->getElementValue(i);
1479 Ops.push_back(getOrCreateVReg(Elt));
1480 }
1481 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001482 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001483 // Return the scalar if it is a <1 x Ty> vector.
1484 if (CV->getNumElements() == 1)
1485 return translate(*CV->getElementAsConstant(0), Reg);
Volkan Keles38a91a02017-03-13 21:36:19 +00001486 std::vector<unsigned> Ops;
1487 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1488 Constant &Elt = *CV->getElementAsConstant(i);
1489 Ops.push_back(getOrCreateVReg(Elt));
1490 }
1491 EntryBuilder.buildMerge(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001492 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001493 switch(CE->getOpcode()) {
1494#define HANDLE_INST(NUM, OPCODE, CLASS) \
Tim Northoverc53606e2016-12-07 21:29:15 +00001495 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
Tim Northover357f1be2016-08-10 23:02:41 +00001496#include "llvm/IR/Instruction.def"
1497 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001498 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001499 }
Aditya Nandakumar117b6672017-05-04 21:43:12 +00001500 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1501 if (CV->getNumOperands() == 1)
1502 return translate(*CV->getOperand(0), Reg);
1503 SmallVector<unsigned, 4> Ops;
1504 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1505 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1506 }
1507 EntryBuilder.buildMerge(Reg, Ops);
Amara Emerson6aff5a72018-07-31 00:08:50 +00001508 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
1509 EntryBuilder.buildBlockAddress(Reg, BA);
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001510 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001511 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001512
Tim Northoverd403a3d2016-08-09 23:01:30 +00001513 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001514}
1515
Tim Northover0d510442016-08-11 16:21:29 +00001516void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001517 // Release the memory used by the different maps we
1518 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001519 PendingPHIs.clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001520 VMap.reset();
Tim Northovercdf23f12016-10-31 18:30:59 +00001521 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001522 MachinePreds.clear();
Aditya Nandakumarbe929932017-05-17 17:41:55 +00001523 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1524 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1525 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1526 EntryBuilder = MachineIRBuilder();
1527 CurBuilder = MachineIRBuilder();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001528}
1529
Tim Northover50db7f412016-12-07 21:17:47 +00001530bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1531 MF = &CurMF;
Matthias Braunf1caa282017-12-15 22:22:58 +00001532 const Function &F = MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001533 if (F.empty())
1534 return false;
Tim Northover50db7f412016-12-07 21:17:47 +00001535 CLI = MF->getSubtarget().getCallLowering();
Tim Northoverc53606e2016-12-07 21:29:15 +00001536 CurBuilder.setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001537 EntryBuilder.setMF(*MF);
1538 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001539 DL = &F.getParent()->getDataLayout();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001540 TPC = &getAnalysis<TargetPassConfig>();
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001541 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001542
Tim Northover14e7f732016-08-05 17:50:36 +00001543 assert(PendingPHIs.empty() && "stale PHIs");
1544
Amara Emersondf9b5292017-12-11 16:58:29 +00001545 if (!DL->isLittleEndian()) {
1546 // Currently we don't properly handle big endian code.
1547 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001548 F.getSubprogram(), &F.getEntryBlock());
Amara Emersondf9b5292017-12-11 16:58:29 +00001549 R << "unable to translate in big endian mode";
1550 reportTranslationError(*MF, *TPC, *ORE, R);
1551 }
1552
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001553 // Release the per-function state when we return, whether we succeeded or not.
1554 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1555
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001556 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001557 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1558 MF->push_back(EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001559 EntryBuilder.setMBB(*EntryBB);
1560
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001561 // Create all blocks, in IR order, to preserve the layout.
1562 for (const BasicBlock &BB: F) {
1563 auto *&MBB = BBToMBB[&BB];
1564
1565 MBB = MF->CreateMachineBasicBlock(&BB);
1566 MF->push_back(MBB);
1567
1568 if (BB.hasAddressTaken())
1569 MBB->setHasAddressTaken();
1570 }
1571
1572 // Make our arguments/constants entry block fallthrough to the IR entry block.
1573 EntryBB->addSuccessor(&getMBB(F.front()));
1574
Tim Northover05cc4852016-12-07 21:05:38 +00001575 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001576 SmallVector<unsigned, 8> VRegArgs;
Amara Emersond78d65c2017-11-30 20:06:02 +00001577 for (const Argument &Arg: F.args()) {
1578 if (DL->getTypeStoreSize(Arg.getType()) == 0)
1579 continue; // Don't handle zero sized types.
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001580 VRegArgs.push_back(
1581 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
Amara Emersond78d65c2017-11-30 20:06:02 +00001582 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001583
Amara Emersonfdd089a2018-07-26 01:25:58 +00001584 // We don't currently support translating swifterror or swiftself functions.
1585 for (auto &Arg : F.args()) {
1586 if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1587 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1588 F.getSubprogram(), &F.getEntryBlock());
1589 R << "unable to lower arguments due to swifterror/swiftself: "
1590 << ore::NV("Prototype", F.getType());
1591 reportTranslationError(*MF, *TPC, *ORE, R);
1592 return false;
1593 }
1594 }
1595
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001596 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001597 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001598 F.getSubprogram(), &F.getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001599 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1600 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001601 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001602 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001603
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001604 auto ArgIt = F.arg_begin();
1605 for (auto &VArg : VRegArgs) {
1606 // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1607 // creating redundant copies.
1608 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1609 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1610 assert(VRegs.empty() && "VRegs already populated?");
1611 VRegs.push_back(VArg);
1612 } else {
1613 unpackRegs(*ArgIt, VArg, EntryBuilder);
1614 }
1615 ArgIt++;
1616 }
1617
Amara Emerson6cdfe292018-08-01 02:17:42 +00001618 // Need to visit defs before uses when translating instructions.
1619 ReversePostOrderTraversal<const Function *> RPOT(&F);
1620 for (const BasicBlock *BB : RPOT) {
1621 MachineBasicBlock &MBB = getMBB(*BB);
Quentin Colombet91ebd712016-03-11 17:27:47 +00001622 // Set the insertion point of all the following translations to
1623 // the end of this basic block.
Tim Northoverc53606e2016-12-07 21:29:15 +00001624 CurBuilder.setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001625
Amara Emerson6cdfe292018-08-01 02:17:42 +00001626 for (const Instruction &Inst : *BB) {
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001627 if (translate(Inst))
1628 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001629
Ahmed Bougacha7daaf882017-02-24 00:34:47 +00001630 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Amara Emerson6cdfe292018-08-01 02:17:42 +00001631 Inst.getDebugLoc(), BB);
Ahmed Bougachad630a922017-09-18 18:50:09 +00001632 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1633
1634 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1635 std::string InstStrStorage;
1636 raw_string_ostream InstStr(InstStrStorage);
1637 InstStr << Inst;
1638
1639 R << ": '" << InstStr.str() << "'";
1640 }
1641
Ahmed Bougacha8f9e99b2017-02-24 00:34:41 +00001642 reportTranslationError(*MF, *TPC, *ORE, R);
1643 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001644 }
1645 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001646
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001647 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001648
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001649 // Merge the argument lowering and constants block with its single
1650 // successor, the LLVM-IR entry block. We want the basic block to
1651 // be maximal.
1652 assert(EntryBB->succ_size() == 1 &&
1653 "Custom BB used for lowering should have only one successor");
1654 // Get the successor of the current entry block.
1655 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1656 assert(NewEntryBB.pred_size() == 1 &&
1657 "LLVM-IR entry block has a predecessor!?");
1658 // Move all the instruction from the current entry block to the
1659 // new entry block.
1660 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1661 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001662
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001663 // Update the live-in information for the new entry block.
1664 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1665 NewEntryBB.addLiveIn(LiveIn);
1666 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001667
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001668 // Get rid of the now empty basic block.
1669 EntryBB->removeSuccessor(&NewEntryBB);
1670 MF->remove(EntryBB);
1671 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001672
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001673 assert(&MF->front() == &NewEntryBB &&
1674 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001675
Matthias Braun90ad6832018-07-13 00:08:38 +00001676 // Initialize stack protector information.
1677 StackProtector &SP = getAnalysis<StackProtector>();
1678 SP.copyToMachineFrameInfo(MF->getFrameInfo());
1679
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001680 return false;
1681}