blob: 3c7eeffbbd54517a92782f820690c8c98902d836 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Quentin Colombet105cf2b2016-01-20 20:58:56 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements the IRTranslator class.
10//===----------------------------------------------------------------------===//
11
12#include "llvm/CodeGen/GlobalISel/IRTranslator.h"
Amara Emerson6cdfe292018-08-01 02:17:42 +000013#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000014#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +000015#include "llvm/ADT/ScopeExit.h"
Tim Northoverb6636fd2017-01-17 22:13:50 +000016#include "llvm/ADT/SmallSet.h"
Quentin Colombetfd9d0a02016-02-11 19:59:41 +000017#include "llvm/ADT/SmallVector.h"
Adam Nemet0965da22017-10-09 23:19:02 +000018#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Jessica Paquette2e35dc52019-01-28 19:22:29 +000019#include "llvm/Analysis/ValueTracking.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"
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +000022#include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000023#include "llvm/CodeGen/LowLevelType.h"
24#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northoverbd505462016-07-22 16:59:52 +000025#include "llvm/CodeGen/MachineFrameInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000026#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000027#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/MachineMemOperand.h"
29#include "llvm/CodeGen/MachineOperand.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000030#include "llvm/CodeGen/MachineRegisterInfo.h"
Matthias Braun90ad6832018-07-13 00:08:38 +000031#include "llvm/CodeGen/StackProtector.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000032#include "llvm/CodeGen/TargetFrameLowering.h"
33#include "llvm/CodeGen/TargetLowering.h"
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000034#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000035#include "llvm/CodeGen/TargetRegisterInfo.h"
36#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000037#include "llvm/IR/BasicBlock.h"
Amara Emerson6cdfe292018-08-01 02:17:42 +000038#include "llvm/IR/CFG.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000039#include "llvm/IR/Constant.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000040#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
Tim Northover09aac4a2017-01-26 23:39:14 +000042#include "llvm/IR/DebugInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000043#include "llvm/IR/DerivedTypes.h"
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000044#include "llvm/IR/Function.h"
Tim Northovera7653b32016-09-12 11:20:22 +000045#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000046#include "llvm/IR/InlineAsm.h"
47#include "llvm/IR/InstrTypes.h"
48#include "llvm/IR/Instructions.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000049#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000050#include "llvm/IR/Intrinsics.h"
51#include "llvm/IR/LLVMContext.h"
52#include "llvm/IR/Metadata.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000053#include "llvm/IR/Type.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000054#include "llvm/IR/User.h"
Quentin Colombet17c494b2016-02-11 17:51:31 +000055#include "llvm/IR/Value.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000056#include "llvm/MC/MCContext.h"
57#include "llvm/Pass.h"
58#include "llvm/Support/Casting.h"
59#include "llvm/Support/CodeGen.h"
60#include "llvm/Support/Debug.h"
61#include "llvm/Support/ErrorHandling.h"
62#include "llvm/Support/LowLevelTypeImpl.h"
63#include "llvm/Support/MathExtras.h"
64#include "llvm/Support/raw_ostream.h"
Tim Northover5fb414d2016-07-29 22:32:36 +000065#include "llvm/Target/TargetIntrinsicInfo.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000066#include "llvm/Target/TargetMachine.h"
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000067#include <algorithm>
68#include <cassert>
69#include <cstdint>
70#include <iterator>
71#include <string>
72#include <utility>
73#include <vector>
Quentin Colombet2ecff3b2016-02-10 22:59:27 +000074
75#define DEBUG_TYPE "irtranslator"
76
Quentin Colombet105cf2b2016-01-20 20:58:56 +000077using namespace llvm;
78
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +000079static cl::opt<bool>
80 EnableCSEInIRTranslator("enable-cse-in-irtranslator",
81 cl::desc("Should enable CSE in irtranslator"),
82 cl::Optional, cl::init(false));
Quentin Colombet105cf2b2016-01-20 20:58:56 +000083char IRTranslator::ID = 0;
Eugene Zelenko76bf48d2017-06-26 22:44:03 +000084
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000085INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
86 false, false)
87INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +000088INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
Quentin Colombet3bb32cc2016-08-26 23:49:05 +000089INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
Tim Northover884b47e2016-07-26 03:29:18 +000090 false, false)
Quentin Colombet105cf2b2016-01-20 20:58:56 +000091
Ahmed Bougachaae9dade2017-02-23 21:05:42 +000092static void reportTranslationError(MachineFunction &MF,
93 const TargetPassConfig &TPC,
94 OptimizationRemarkEmitter &ORE,
95 OptimizationRemarkMissed &R) {
96 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
97
98 // Print the function name explicitly if we don't have a debug location (which
99 // makes the diagnostic less useful) or if we're going to emit a raw error.
100 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
101 R << (" (in function: " + MF.getName() + ")").str();
102
103 if (TPC.isGlobalISelAbortEnabled())
104 report_fatal_error(R.getMsg());
105 else
106 ORE.emit(R);
Tim Northover60f23492016-11-08 01:12:17 +0000107}
108
Tom Stellard1f7f6462019-06-18 02:05:06 +0000109IRTranslator::IRTranslator() : MachineFunctionPass(ID) { }
Quentin Colombeta7fae162016-02-11 17:53:23 +0000110
Daniel Sanders3b390402018-10-31 17:31:23 +0000111#ifndef NDEBUG
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000112namespace {
Daniel Sanders3b390402018-10-31 17:31:23 +0000113/// Verify that every instruction created has the same DILocation as the
114/// instruction being translated.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000115class DILocationVerifier : public GISelChangeObserver {
Daniel Sanders3b390402018-10-31 17:31:23 +0000116 const Instruction *CurrInst = nullptr;
117
118public:
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000119 DILocationVerifier() = default;
120 ~DILocationVerifier() = default;
Daniel Sanders3b390402018-10-31 17:31:23 +0000121
122 const Instruction *getCurrentInst() const { return CurrInst; }
123 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
124
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000125 void erasingInstr(MachineInstr &MI) override {}
126 void changingInstr(MachineInstr &MI) override {}
127 void changedInstr(MachineInstr &MI) override {}
128
129 void createdInstr(MachineInstr &MI) override {
Daniel Sanders3b390402018-10-31 17:31:23 +0000130 assert(getCurrentInst() && "Inserted instruction without a current MI");
131
132 // Only print the check message if we're actually checking it.
133#ifndef NDEBUG
134 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
135 << " was copied to " << MI);
136#endif
Amara Emersonfb0a40f2019-06-13 22:15:35 +0000137 // We allow insts in the entry block to have a debug loc line of 0 because
138 // they could have originated from constants, and we don't want a jumpy
139 // debug experience.
140 assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
141 MI.getDebugLoc().getLine() == 0) &&
Daniel Sanders3b390402018-10-31 17:31:23 +0000142 "Line info was not transferred to all instructions");
143 }
Daniel Sanders3b390402018-10-31 17:31:23 +0000144};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000145} // namespace
Daniel Sanders3b390402018-10-31 17:31:23 +0000146#endif // ifndef NDEBUG
147
148
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000149void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
Matthias Braun90ad6832018-07-13 00:08:38 +0000150 AU.addRequired<StackProtector>();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000151 AU.addRequired<TargetPassConfig>();
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000152 AU.addRequired<GISelCSEAnalysisWrapperPass>();
Matthias Braun90ad6832018-07-13 00:08:38 +0000153 getSelectionDAGFallbackAnalysisUsage(AU);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000154 MachineFunctionPass::getAnalysisUsage(AU);
155}
156
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000157IRTranslator::ValueToVRegInfo::VRegListT &
158IRTranslator::allocateVRegs(const Value &Val) {
159 assert(!VMap.contains(Val) && "Value already allocated in VMap");
160 auto *Regs = VMap.getVRegs(Val);
161 auto *Offsets = VMap.getOffsets(Val);
162 SmallVector<LLT, 4> SplitTys;
163 computeValueLLTs(*DL, *Val.getType(), SplitTys,
164 Offsets->empty() ? Offsets : nullptr);
165 for (unsigned i = 0; i < SplitTys.size(); ++i)
166 Regs->push_back(0);
167 return *Regs;
168}
Tim Northover9e35f1e2017-01-25 20:58:22 +0000169
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000170ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
171 auto VRegsIt = VMap.findVRegs(Val);
172 if (VRegsIt != VMap.vregs_end())
173 return *VRegsIt->second;
174
175 if (Val.getType()->isVoidTy())
176 return *VMap.getVRegs(Val);
177
178 // Create entry for this type.
179 auto *VRegs = VMap.getVRegs(Val);
180 auto *Offsets = VMap.getOffsets(Val);
181
Tim Northover9e35f1e2017-01-25 20:58:22 +0000182 assert(Val.getType()->isSized() &&
183 "Don't know how to create an empty vreg");
Tim Northover9e35f1e2017-01-25 20:58:22 +0000184
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000185 SmallVector<LLT, 4> SplitTys;
186 computeValueLLTs(*DL, *Val.getType(), SplitTys,
187 Offsets->empty() ? Offsets : nullptr);
188
189 if (!isa<Constant>(Val)) {
190 for (auto Ty : SplitTys)
191 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
192 return *VRegs;
193 }
194
195 if (Val.getType()->isAggregateType()) {
196 // UndefValue, ConstantAggregateZero
197 auto &C = cast<Constant>(Val);
198 unsigned Idx = 0;
199 while (auto Elt = C.getAggregateElement(Idx++)) {
200 auto EltRegs = getOrCreateVRegs(*Elt);
Fangrui Song75709322018-11-17 01:44:25 +0000201 llvm::copy(EltRegs, std::back_inserter(*VRegs));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000202 }
203 } else {
204 assert(SplitTys.size() == 1 && "unexpectedly split LLT");
205 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
206 bool Success = translate(cast<Constant>(Val), VRegs->front());
Tim Northover9e35f1e2017-01-25 20:58:22 +0000207 if (!Success) {
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000208 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +0000209 MF->getFunction().getSubprogram(),
210 &MF->getFunction().getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000211 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
212 reportTranslationError(*MF, *TPC, *ORE, R);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000213 return *VRegs;
Tim Northover5ed648e2016-08-09 21:28:04 +0000214 }
Quentin Colombet17c494b2016-02-11 17:51:31 +0000215 }
Tim Northover7f3ad2e2017-01-20 23:25:17 +0000216
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000217 return *VRegs;
Quentin Colombet17c494b2016-02-11 17:51:31 +0000218}
219
Tim Northovercdf23f12016-10-31 18:30:59 +0000220int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
221 if (FrameIndices.find(&AI) != FrameIndices.end())
222 return FrameIndices[&AI];
223
Quentin Colombetc9256cc2019-05-03 01:23:56 +0000224 unsigned ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
Tim Northovercdf23f12016-10-31 18:30:59 +0000225 unsigned Size =
226 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
227
228 // Always allocate at least one byte.
229 Size = std::max(Size, 1u);
230
231 unsigned Alignment = AI.getAlignment();
232 if (!Alignment)
233 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
234
235 int &FI = FrameIndices[&AI];
Tim Northover50db7f412016-12-07 21:17:47 +0000236 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
Tim Northovercdf23f12016-10-31 18:30:59 +0000237 return FI;
238}
239
Tim Northoverad2b7172016-07-26 20:23:26 +0000240unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
241 unsigned Alignment = 0;
242 Type *ValTy = nullptr;
243 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
244 Alignment = SI->getAlignment();
245 ValTy = SI->getValueOperand()->getType();
246 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
247 Alignment = LI->getAlignment();
248 ValTy = LI->getType();
Daniel Sanders94813992018-07-09 19:33:40 +0000249 } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
250 // TODO(PR27168): This instruction has no alignment attribute, but unlike
251 // the default alignment for load/store, the default here is to assume
252 // it has NATURAL alignment, not DataLayout-specified alignment.
253 const DataLayout &DL = AI->getModule()->getDataLayout();
254 Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
255 ValTy = AI->getCompareOperand()->getType();
256 } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
257 // TODO(PR27168): This instruction has no alignment attribute, but unlike
258 // the default alignment for load/store, the default here is to assume
259 // it has NATURAL alignment, not DataLayout-specified alignment.
260 const DataLayout &DL = AI->getModule()->getDataLayout();
261 Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
262 ValTy = AI->getType();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000263 } else {
264 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
265 R << "unable to translate memop: " << ore::NV("Opcode", &I);
266 reportTranslationError(*MF, *TPC, *ORE, R);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000267 return 1;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000268 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000269
270 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
271}
272
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000273MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
Quentin Colombet53237a92016-03-11 17:27:43 +0000274 MachineBasicBlock *&MBB = BBToMBB[&BB];
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000275 assert(MBB && "BasicBlock was not encountered before");
Quentin Colombet17c494b2016-02-11 17:51:31 +0000276 return *MBB;
277}
278
Tim Northoverb6636fd2017-01-17 22:13:50 +0000279void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
280 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
281 MachinePreds[Edge].push_back(NewPred);
282}
283
Tim Northoverc53606e2016-12-07 21:29:15 +0000284bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
285 MachineIRBuilder &MIRBuilder) {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +0000286 // Get or create a virtual register for each value.
287 // Unless the value is a Constant => loadimm cst?
288 // or inline constant each time?
289 // Creation of a virtual register needs to have a size.
Tim Northover357f1be2016-08-10 23:02:41 +0000290 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
291 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
292 unsigned Res = getOrCreateVReg(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000293 uint16_t Flags = 0;
Michael Berg894c39f2018-09-19 18:52:08 +0000294 if (isa<Instruction>(U)) {
Michael Berg894c39f2018-09-19 18:52:08 +0000295 const Instruction &I = cast<Instruction>(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000296 Flags = MachineInstr::copyFlagsFromInstruction(I);
Michael Berg894c39f2018-09-19 18:52:08 +0000297 }
Michael Bergf0d81a32019-02-06 19:57:06 +0000298
299 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
Quentin Colombet17c494b2016-02-11 17:51:31 +0000300 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000301}
302
Volkan Keles20d3c422017-03-07 18:03:28 +0000303bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
304 // -0.0 - X --> G_FNEG
305 if (isa<Constant>(U.getOperand(0)) &&
306 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
Michael Bergf9bff2a2019-06-17 23:19:40 +0000307 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
308 unsigned Res = getOrCreateVReg(U);
309 uint16_t Flags = 0;
310 if (isa<Instruction>(U)) {
311 const Instruction &I = cast<Instruction>(U);
312 Flags = MachineInstr::copyFlagsFromInstruction(I);
313 }
314 // Negate the last operand of the FSUB
315 MIRBuilder.buildInstr(TargetOpcode::G_FNEG, {Res}, {Op1}, Flags);
Volkan Keles20d3c422017-03-07 18:03:28 +0000316 return true;
317 }
318 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
319}
320
Cameron McInallycbde0d92018-11-13 18:15:47 +0000321bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
Michael Bergf9bff2a2019-06-17 23:19:40 +0000322 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
323 unsigned Res = getOrCreateVReg(U);
324 uint16_t Flags = 0;
325 if (isa<Instruction>(U)) {
326 const Instruction &I = cast<Instruction>(U);
327 Flags = MachineInstr::copyFlagsFromInstruction(I);
328 }
329 MIRBuilder.buildInstr(TargetOpcode::G_FNEG, {Res}, {Op0}, Flags);
Cameron McInallycbde0d92018-11-13 18:15:47 +0000330 return true;
331}
332
Tim Northoverc53606e2016-12-07 21:29:15 +0000333bool IRTranslator::translateCompare(const User &U,
334 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000335 const CmpInst *CI = dyn_cast<CmpInst>(&U);
336 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
337 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
338 unsigned Res = getOrCreateVReg(U);
339 CmpInst::Predicate Pred =
340 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
341 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000342 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000343 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000344 else if (Pred == CmpInst::FCMP_FALSE)
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000345 MIRBuilder.buildCopy(
346 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
347 else if (Pred == CmpInst::FCMP_TRUE)
348 MIRBuilder.buildCopy(
349 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
Michael Bergc6a52452018-12-18 17:54:52 +0000350 else {
Michael Bergf0d81a32019-02-06 19:57:06 +0000351 MIRBuilder.buildInstr(TargetOpcode::G_FCMP, {Res}, {Pred, Op0, Op1},
352 MachineInstr::copyFlagsFromInstruction(*CI));
Michael Bergc6a52452018-12-18 17:54:52 +0000353 }
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000354
Tim Northoverde3aea0412016-08-17 20:25:25 +0000355 return true;
356}
357
Tim Northoverc53606e2016-12-07 21:29:15 +0000358bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000359 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000360 const Value *Ret = RI.getReturnValue();
Amara Emersond78d65c2017-11-30 20:06:02 +0000361 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
362 Ret = nullptr;
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000363
364 ArrayRef<unsigned> VRegs;
365 if (Ret)
366 VRegs = getOrCreateVRegs(*Ret);
367
Tim Northover3b2157a2019-05-24 08:40:13 +0000368 unsigned SwiftErrorVReg = 0;
369 if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
370 SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
371 &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
372 }
373
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000374 // The target may mess up with the insertion point, but
375 // this is not important as a return is the last instruction
376 // of the block anyway.
Tim Northover3b2157a2019-05-24 08:40:13 +0000377 return CLI->lowerReturn(MIRBuilder, Ret, VRegs, SwiftErrorVReg);
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000378}
379
Tim Northoverc53606e2016-12-07 21:29:15 +0000380bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000381 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000382 unsigned Succ = 0;
383 if (!BrInst.isUnconditional()) {
384 // We want a G_BRCOND to the true BB followed by an unconditional branch.
385 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
386 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000387 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000388 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000389 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000390
391 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000392 MachineBasicBlock &TgtBB = getMBB(BrTgt);
Ahmed Bougachae8e1fa32017-03-21 23:42:50 +0000393 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
394
395 // If the unconditional target is the layout successor, fallthrough.
396 if (!CurBB.isLayoutSuccessor(&TgtBB))
397 MIRBuilder.buildBr(TgtBB);
Tim Northover69c2ba52016-07-29 17:58:00 +0000398
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000399 // Link successors.
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000400 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000401 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000402 return true;
403}
404
Kristof Beylseced0712017-01-05 11:28:51 +0000405bool IRTranslator::translateSwitch(const User &U,
406 MachineIRBuilder &MIRBuilder) {
407 // For now, just translate as a chain of conditional branches.
408 // FIXME: could we share most of the logic/code in
409 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
410 // At first sight, it seems most of the logic in there is independent of
411 // SelectionDAG-specifics and a lot of work went in to optimize switch
412 // lowering in there.
413
414 const SwitchInst &SwInst = cast<SwitchInst>(U);
415 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000416 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000417
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000418 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000419 for (auto &CaseIt : SwInst.cases()) {
420 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
421 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
422 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000423 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
424 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000425 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000426
Tim Northoverb6636fd2017-01-17 22:13:50 +0000427 MIRBuilder.buildBrCond(Tst, TrueMBB);
428 CurMBB.addSuccessor(&TrueMBB);
429 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000430
Tim Northoverb6636fd2017-01-17 22:13:50 +0000431 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000432 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000433 // Insert the comparison blocks one after the other.
434 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000435 MIRBuilder.buildBr(*FalseMBB);
436 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000437
Tim Northoverb6636fd2017-01-17 22:13:50 +0000438 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000439 }
440 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000441 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000442 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000443 MIRBuilder.buildBr(DefaultMBB);
444 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
445 CurMBB.addSuccessor(&DefaultMBB);
446 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000447
448 return true;
449}
450
Kristof Beyls65a12c02017-01-30 09:13:18 +0000451bool IRTranslator::translateIndirectBr(const User &U,
452 MachineIRBuilder &MIRBuilder) {
453 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
454
455 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
456 MIRBuilder.buildBrIndirect(Tgt);
457
458 // Link successors.
459 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000460 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000461 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000462
463 return true;
464}
465
Tim Northover3b2157a2019-05-24 08:40:13 +0000466static bool isSwiftError(const Value *V) {
467 if (auto Arg = dyn_cast<Argument>(V))
468 return Arg->hasSwiftErrorAttr();
469 if (auto AI = dyn_cast<AllocaInst>(V))
470 return AI->isSwiftError();
471 return false;
472}
473
Tim Northoverc53606e2016-12-07 21:29:15 +0000474bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000475 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000476
Tim Northover7152dca2016-10-19 15:55:06 +0000477 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
478 : MachineMemOperand::MONone;
479 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000480
Amara Emersond78d65c2017-11-30 20:06:02 +0000481 if (DL->getTypeStoreSize(LI.getType()) == 0)
482 return true;
483
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000484 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
485 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
486 unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000487
Diana Picusa5682222019-05-14 09:25:17 +0000488 Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType());
489 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
490
Tim Northover3b2157a2019-05-24 08:40:13 +0000491 if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) {
492 assert(Regs.size() == 1 && "swifterror should be single pointer");
493 unsigned VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(),
494 LI.getPointerOperand());
495 MIRBuilder.buildCopy(Regs[0], VReg);
496 return true;
497 }
498
499
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000500 for (unsigned i = 0; i < Regs.size(); ++i) {
501 unsigned Addr = 0;
Diana Picusa5682222019-05-14 09:25:17 +0000502 MIRBuilder.materializeGEP(Addr, Base, OffsetTy, Offsets[i] / 8);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000503
504 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
505 unsigned BaseAlign = getMemOpAlignment(LI);
506 auto MMO = MF->getMachineMemOperand(
507 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
508 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
509 LI.getSyncScopeID(), LI.getOrdering());
510 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
511 }
512
Tim Northoverad2b7172016-07-26 20:23:26 +0000513 return true;
514}
515
Tim Northoverc53606e2016-12-07 21:29:15 +0000516bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000517 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000518 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
519 : MachineMemOperand::MONone;
520 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000521
Amara Emersond78d65c2017-11-30 20:06:02 +0000522 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
523 return true;
524
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000525 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
526 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
527 unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000528
Diana Picusa5682222019-05-14 09:25:17 +0000529 Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType());
530 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
531
Tim Northover3b2157a2019-05-24 08:40:13 +0000532 if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
533 assert(Vals.size() == 1 && "swifterror should be single pointer");
534
535 unsigned VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
536 SI.getPointerOperand());
537 MIRBuilder.buildCopy(VReg, Vals[0]);
538 return true;
539 }
540
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000541 for (unsigned i = 0; i < Vals.size(); ++i) {
542 unsigned Addr = 0;
Diana Picusa5682222019-05-14 09:25:17 +0000543 MIRBuilder.materializeGEP(Addr, Base, OffsetTy, Offsets[i] / 8);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000544
545 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
546 unsigned BaseAlign = getMemOpAlignment(SI);
547 auto MMO = MF->getMachineMemOperand(
548 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
549 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
550 SI.getSyncScopeID(), SI.getOrdering());
551 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
552 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000553 return true;
554}
555
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000556static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
Tim Northoverb6046222016-08-19 20:09:03 +0000557 const Value *Src = U.getOperand(0);
558 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Volkan Keles6a36c642017-05-19 09:47:02 +0000559
Tim Northover6f80b082016-08-19 17:47:05 +0000560 // getIndexedOffsetInType is designed for GEPs, so the first index is the
561 // usual array element rather than looking into the actual aggregate.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000562 SmallVector<Value *, 1> Indices;
Tim Northover6f80b082016-08-19 17:47:05 +0000563 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000564
565 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
566 for (auto Idx : EVI->indices())
567 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000568 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
569 for (auto Idx : IVI->indices())
570 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Tim Northoverb6046222016-08-19 20:09:03 +0000571 } else {
572 for (unsigned i = 1; i < U.getNumOperands(); ++i)
573 Indices.push_back(U.getOperand(i));
574 }
Tim Northover6f80b082016-08-19 17:47:05 +0000575
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000576 return 8 * static_cast<uint64_t>(
577 DL.getIndexedOffsetInType(Src->getType(), Indices));
578}
Tim Northover6f80b082016-08-19 17:47:05 +0000579
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000580bool IRTranslator::translateExtractValue(const User &U,
581 MachineIRBuilder &MIRBuilder) {
582 const Value *Src = U.getOperand(0);
583 uint64_t Offset = getOffsetFromIndices(U, *DL);
584 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
585 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
Fangrui Songcecc4352019-04-12 02:02:06 +0000586 unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000587 auto &DstRegs = allocateVRegs(U);
588
589 for (unsigned i = 0; i < DstRegs.size(); ++i)
590 DstRegs[i] = SrcRegs[Idx++];
Tim Northover6f80b082016-08-19 17:47:05 +0000591
592 return true;
593}
594
Tim Northoverc53606e2016-12-07 21:29:15 +0000595bool IRTranslator::translateInsertValue(const User &U,
596 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000597 const Value *Src = U.getOperand(0);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000598 uint64_t Offset = getOffsetFromIndices(U, *DL);
599 auto &DstRegs = allocateVRegs(U);
600 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
601 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
602 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
603 auto InsertedIt = InsertedRegs.begin();
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000604
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000605 for (unsigned i = 0; i < DstRegs.size(); ++i) {
606 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
607 DstRegs[i] = *InsertedIt++;
608 else
609 DstRegs[i] = SrcRegs[i];
Tim Northoverb6046222016-08-19 20:09:03 +0000610 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000611
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000612 return true;
613}
614
Tim Northoverc53606e2016-12-07 21:29:15 +0000615bool IRTranslator::translateSelect(const User &U,
616 MachineIRBuilder &MIRBuilder) {
Kristof Beyls7a713502017-04-19 06:38:37 +0000617 unsigned Tst = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000618 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
619 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
620 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
621
Michael Bergc6a52452018-12-18 17:54:52 +0000622 const SelectInst &SI = cast<SelectInst>(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000623 uint16_t Flags = 0;
624 if (const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
625 Flags = MachineInstr::copyFlagsFromInstruction(*Cmp);
626
Michael Bergc6a52452018-12-18 17:54:52 +0000627 for (unsigned i = 0; i < ResRegs.size(); ++i) {
Michael Bergf0d81a32019-02-06 19:57:06 +0000628 MIRBuilder.buildInstr(TargetOpcode::G_SELECT, {ResRegs[i]},
629 {Tst, Op0Regs[i], Op1Regs[i]}, Flags);
Michael Bergc6a52452018-12-18 17:54:52 +0000630 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000631
Tim Northover5a28c362016-08-19 20:09:07 +0000632 return true;
633}
634
Tim Northoverc53606e2016-12-07 21:29:15 +0000635bool IRTranslator::translateBitCast(const User &U,
636 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000637 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000638 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
639 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000640 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000641 auto &Regs = *VMap.getVRegs(U);
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000642 // If we already assigned a vreg for this bitcast, we can't change that.
643 // Emit a copy to satisfy the users we already emitted.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000644 if (!Regs.empty())
645 MIRBuilder.buildCopy(Regs[0], SrcReg);
646 else {
647 Regs.push_back(SrcReg);
648 VMap.getOffsets(U)->push_back(0);
649 }
Tim Northover7c9eba92016-07-25 21:01:29 +0000650 return true;
651 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000652 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000653}
654
Tim Northoverc53606e2016-12-07 21:29:15 +0000655bool IRTranslator::translateCast(unsigned Opcode, const User &U,
656 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000657 unsigned Op = getOrCreateVReg(*U.getOperand(0));
658 unsigned Res = getOrCreateVReg(U);
Aditya Nandakumar92663372019-04-18 02:19:29 +0000659 MIRBuilder.buildInstr(Opcode, {Res}, {Op});
Tim Northover7c9eba92016-07-25 21:01:29 +0000660 return true;
661}
662
Tim Northoverc53606e2016-12-07 21:29:15 +0000663bool IRTranslator::translateGetElementPtr(const User &U,
664 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000665 // FIXME: support vector GEPs.
666 if (U.getType()->isVectorTy())
667 return false;
668
669 Value &Op0 = *U.getOperand(0);
670 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000671 Type *PtrIRTy = Op0.getType();
672 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
673 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
674 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000675
676 int64_t Offset = 0;
677 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
678 GTI != E; ++GTI) {
679 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000680 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000681 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
682 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
683 continue;
684 } else {
685 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
686
687 // If this is a scalar constant or a splat vector of constants,
688 // handle it quickly.
689 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
690 Offset += ElementSize * CI->getSExtValue();
691 continue;
692 }
693
694 if (Offset != 0) {
695 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Amara Emerson946b1242019-04-15 05:04:20 +0000696 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
697 auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
698 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetMIB.getReg(0));
Tim Northovera7653b32016-09-12 11:20:22 +0000699
700 BaseReg = NewBaseReg;
701 Offset = 0;
702 }
703
Tim Northovera7653b32016-09-12 11:20:22 +0000704 unsigned IdxReg = getOrCreateVReg(*Idx);
705 if (MRI->getType(IdxReg) != OffsetTy) {
706 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
707 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
708 IdxReg = NewIdxReg;
709 }
710
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000711 // N = N + Idx * ElementSize;
712 // Avoid doing it for ElementSize of 1.
713 unsigned GepOffsetReg;
714 if (ElementSize != 1) {
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000715 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
Amara Emerson946b1242019-04-15 05:04:20 +0000716 auto ElementSizeMIB = MIRBuilder.buildConstant(
717 getLLTForType(*OffsetIRTy, *DL), ElementSize);
718 MIRBuilder.buildMul(GepOffsetReg, ElementSizeMIB.getReg(0), IdxReg);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000719 } else
720 GepOffsetReg = IdxReg;
Tim Northovera7653b32016-09-12 11:20:22 +0000721
722 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000723 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
Tim Northovera7653b32016-09-12 11:20:22 +0000724 BaseReg = NewBaseReg;
725 }
726 }
727
728 if (Offset != 0) {
Amara Emerson946b1242019-04-15 05:04:20 +0000729 auto OffsetMIB =
730 MIRBuilder.buildConstant(getLLTForType(*OffsetIRTy, *DL), Offset);
731 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
Tim Northovera7653b32016-09-12 11:20:22 +0000732 return true;
733 }
734
735 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
736 return true;
737}
738
Tim Northover79f43f12017-01-30 19:33:07 +0000739bool IRTranslator::translateMemfunc(const CallInst &CI,
740 MachineIRBuilder &MIRBuilder,
741 unsigned ID) {
Jessica Paquetteb2295432019-06-10 21:53:56 +0000742
743 // If the source is undef, then just emit a nop.
744 if (isa<UndefValue>(CI.getArgOperand(1))) {
745 switch (ID) {
746 case Intrinsic::memmove:
747 case Intrinsic::memcpy:
748 case Intrinsic::memset:
749 return true;
750 default:
751 break;
752 }
753 }
754
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000755 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000756 Type *DstTy = CI.getArgOperand(0)->getType();
757 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000758 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
759 return false;
760
761 SmallVector<CallLowering::ArgInfo, 8> Args;
762 for (int i = 0; i < 3; ++i) {
763 const auto &Arg = CI.getArgOperand(i);
764 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
765 }
766
Tim Northover79f43f12017-01-30 19:33:07 +0000767 const char *Callee;
768 switch (ID) {
769 case Intrinsic::memmove:
770 case Intrinsic::memcpy: {
771 Type *SrcTy = CI.getArgOperand(1)->getType();
772 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
773 return false;
774 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
775 break;
776 }
777 case Intrinsic::memset:
778 Callee = "memset";
779 break;
780 default:
781 return false;
782 }
Tim Northover3f186032016-10-18 20:03:45 +0000783
Diana Picusd79253a2017-03-20 14:40:18 +0000784 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
785 MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000786 CallLowering::ArgInfo(0, CI.getType()), Args);
787}
Tim Northovera7653b32016-09-12 11:20:22 +0000788
Tim Northoverc53606e2016-12-07 21:29:15 +0000789void IRTranslator::getStackGuard(unsigned DstReg,
790 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000791 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
792 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000793 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
794 MIB.addDef(DstReg);
795
Tim Northover50db7f412016-12-07 21:17:47 +0000796 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +0000797 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000798 if (!Global)
799 return;
800
801 MachinePointerInfo MPInfo(Global);
Tim Northovercdf23f12016-10-31 18:30:59 +0000802 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
803 MachineMemOperand::MODereferenceable;
Chandler Carruthc73c0302018-08-16 21:30:05 +0000804 MachineMemOperand *MemRef =
Tim Northover50db7f412016-12-07 21:17:47 +0000805 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
Fangrui Songe73534462017-11-15 06:17:32 +0000806 DL->getPointerABIAlignment(0));
Chandler Carruthc73c0302018-08-16 21:30:05 +0000807 MIB.setMemRefs({MemRef});
Tim Northovercdf23f12016-10-31 18:30:59 +0000808}
809
Tim Northover1e656ec2016-12-08 22:44:00 +0000810bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
811 MachineIRBuilder &MIRBuilder) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000812 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000813 MIRBuilder.buildInstr(Op)
814 .addDef(ResRegs[0])
815 .addDef(ResRegs[1])
816 .addUse(getOrCreateVReg(*CI.getOperand(0)))
817 .addUse(getOrCreateVReg(*CI.getOperand(1)));
Tim Northover1e656ec2016-12-08 22:44:00 +0000818
Tim Northover1e656ec2016-12-08 22:44:00 +0000819 return true;
820}
821
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000822unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000823 switch (ID) {
824 default:
825 break;
Jessica Paquette0e71e732019-02-12 17:28:17 +0000826 case Intrinsic::bswap:
827 return TargetOpcode::G_BSWAP;
Jessica Paquettee288c522019-02-06 17:25:54 +0000828 case Intrinsic::ceil:
829 return TargetOpcode::G_FCEIL;
830 case Intrinsic::cos:
831 return TargetOpcode::G_FCOS;
832 case Intrinsic::ctpop:
833 return TargetOpcode::G_CTPOP;
834 case Intrinsic::exp:
835 return TargetOpcode::G_FEXP;
836 case Intrinsic::exp2:
837 return TargetOpcode::G_FEXP2;
838 case Intrinsic::fabs:
839 return TargetOpcode::G_FABS;
Matt Arsenault55146d32019-05-16 04:08:39 +0000840 case Intrinsic::copysign:
841 return TargetOpcode::G_FCOPYSIGN;
Matt Arsenault9dba67f2019-02-11 17:05:20 +0000842 case Intrinsic::canonicalize:
843 return TargetOpcode::G_FCANONICALIZE;
Jessica Paquettef472f312019-02-11 17:16:32 +0000844 case Intrinsic::floor:
845 return TargetOpcode::G_FFLOOR;
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000846 case Intrinsic::fma:
847 return TargetOpcode::G_FMA;
Jessica Paquettee288c522019-02-06 17:25:54 +0000848 case Intrinsic::log:
849 return TargetOpcode::G_FLOG;
850 case Intrinsic::log2:
851 return TargetOpcode::G_FLOG2;
852 case Intrinsic::log10:
853 return TargetOpcode::G_FLOG10;
Jessica Paquettebd7ac302019-04-25 16:39:28 +0000854 case Intrinsic::nearbyint:
855 return TargetOpcode::G_FNEARBYINT;
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000856 case Intrinsic::pow:
857 return TargetOpcode::G_FPOW;
Jessica Paquettead69af32019-04-19 21:46:12 +0000858 case Intrinsic::rint:
859 return TargetOpcode::G_FRINT;
Jessica Paquettee288c522019-02-06 17:25:54 +0000860 case Intrinsic::round:
861 return TargetOpcode::G_INTRINSIC_ROUND;
862 case Intrinsic::sin:
863 return TargetOpcode::G_FSIN;
864 case Intrinsic::sqrt:
865 return TargetOpcode::G_FSQRT;
866 case Intrinsic::trunc:
867 return TargetOpcode::G_INTRINSIC_TRUNC;
868 }
869 return Intrinsic::not_intrinsic;
870}
871
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000872bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
873 Intrinsic::ID ID,
874 MachineIRBuilder &MIRBuilder) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000875
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000876 unsigned Op = getSimpleIntrinsicOpcode(ID);
Jessica Paquettee288c522019-02-06 17:25:54 +0000877
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000878 // Is this a simple intrinsic?
Jessica Paquettee288c522019-02-06 17:25:54 +0000879 if (Op == Intrinsic::not_intrinsic)
880 return false;
881
882 // Yes. Let's translate it.
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000883 SmallVector<llvm::SrcOp, 4> VRegs;
884 for (auto &Arg : CI.arg_operands())
885 VRegs.push_back(getOrCreateVReg(*Arg));
886
887 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
Michael Bergf0d81a32019-02-06 19:57:06 +0000888 MachineInstr::copyFlagsFromInstruction(CI));
Jessica Paquettee288c522019-02-06 17:25:54 +0000889 return true;
890}
891
Tim Northoverc53606e2016-12-07 21:29:15 +0000892bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
893 MachineIRBuilder &MIRBuilder) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000894
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000895 // If this is a simple intrinsic (that is, we just need to add a def of
896 // a vreg, and uses for each arg operand, then translate it.
897 if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
Jessica Paquettee288c522019-02-06 17:25:54 +0000898 return true;
899
Tim Northover91c81732016-08-19 17:17:06 +0000900 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000901 default:
902 break;
Tim Northover0e011702017-02-10 19:10:38 +0000903 case Intrinsic::lifetime_start:
Jessica Paquette2e35dc52019-01-28 19:22:29 +0000904 case Intrinsic::lifetime_end: {
905 // No stack colouring in O0, discard region information.
906 if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
907 return true;
908
909 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
910 : TargetOpcode::LIFETIME_END;
911
912 // Get the underlying objects for the location passed on the lifetime
913 // marker.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000914 SmallVector<const Value *, 4> Allocas;
Jessica Paquette2e35dc52019-01-28 19:22:29 +0000915 GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
916
917 // Iterate over each underlying object, creating lifetime markers for each
918 // static alloca. Quit if we find a non-static alloca.
Bjorn Pettersson71e8c6f2019-04-24 06:55:50 +0000919 for (const Value *V : Allocas) {
920 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Jessica Paquette2e35dc52019-01-28 19:22:29 +0000921 if (!AI)
922 continue;
923
924 if (!AI->isStaticAlloca())
925 return true;
926
927 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
928 }
Tim Northover0e011702017-02-10 19:10:38 +0000929 return true;
Jessica Paquette2e35dc52019-01-28 19:22:29 +0000930 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000931 case Intrinsic::dbg_declare: {
932 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
933 assert(DI.getVariable() && "Missing variable");
934
935 const Value *Address = DI.getAddress();
936 if (!Address || isa<UndefValue>(Address)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000937 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Tim Northover09aac4a2017-01-26 23:39:14 +0000938 return true;
939 }
940
Tim Northover09aac4a2017-01-26 23:39:14 +0000941 assert(DI.getVariable()->isValidLocationForIntrinsic(
942 MIRBuilder.getDebugLoc()) &&
943 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000944 auto AI = dyn_cast<AllocaInst>(Address);
945 if (AI && AI->isStaticAlloca()) {
946 // Static allocas are tracked at the MF level, no need for DBG_VALUE
947 // instructions (in fact, they get ignored if they *do* exist).
948 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
949 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Josh Stonef446fac2018-09-11 17:52:01 +0000950 } else {
951 // A dbg.declare describes the address of a source variable, so lower it
952 // into an indirect DBG_VALUE.
953 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
954 DI.getVariable(), DI.getExpression());
955 }
Tim Northoverb58346f2016-12-08 22:44:13 +0000956 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000957 }
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000958 case Intrinsic::dbg_label: {
959 const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
960 assert(DI.getLabel() && "Missing label");
961
962 assert(DI.getLabel()->isValidLocationForIntrinsic(
963 MIRBuilder.getDebugLoc()) &&
964 "Expected inlined-at fields to agree");
965
966 MIRBuilder.buildDbgLabel(DI.getLabel());
967 return true;
968 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000969 case Intrinsic::vaend:
970 // No target I know of cares about va_end. Certainly no in-tree target
971 // does. Simplest intrinsic ever!
972 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000973 case Intrinsic::vastart: {
974 auto &TLI = *MF->getSubtarget().getTargetLowering();
975 Value *Ptr = CI.getArgOperand(0);
976 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
977
Matt Arsenault2a645982019-01-31 01:38:47 +0000978 // FIXME: Get alignment
Tim Northoverf19d4672017-02-08 17:57:20 +0000979 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
980 .addUse(getOrCreateVReg(*Ptr))
981 .addMemOperand(MF->getMachineMemOperand(
Matt Arsenault2a645982019-01-31 01:38:47 +0000982 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
Tim Northoverf19d4672017-02-08 17:57:20 +0000983 return true;
984 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000985 case Intrinsic::dbg_value: {
986 // This form of DBG_VALUE is target-independent.
987 const DbgValueInst &DI = cast<DbgValueInst>(CI);
988 const Value *V = DI.getValue();
989 assert(DI.getVariable()->isValidLocationForIntrinsic(
990 MIRBuilder.getDebugLoc()) &&
991 "Expected inlined-at fields to agree");
992 if (!V) {
993 // Currently the optimizer can produce this; insert an undef to
994 // help debugging. Probably the optimizer should not do this.
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000995 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000996 } else if (const auto *CI = dyn_cast<Constant>(V)) {
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000997 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000998 } else {
999 unsigned Reg = getOrCreateVReg(*V);
1000 // FIXME: This does not handle register-indirect values at offset 0. The
1001 // direct/indirect thing shouldn't really be handled by something as
1002 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
1003 // pretty baked in right now.
Adrian Prantlabe04752017-07-28 20:21:02 +00001004 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +00001005 }
1006 return true;
1007 }
Tim Northover1e656ec2016-12-08 22:44:00 +00001008 case Intrinsic::uadd_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +00001009 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +00001010 case Intrinsic::sadd_with_overflow:
1011 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
1012 case Intrinsic::usub_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +00001013 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +00001014 case Intrinsic::ssub_with_overflow:
1015 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
1016 case Intrinsic::umul_with_overflow:
1017 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
1018 case Intrinsic::smul_with_overflow:
1019 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Volkan Keles92837632018-02-13 00:47:46 +00001020 case Intrinsic::fmuladd: {
1021 const TargetMachine &TM = MF->getTarget();
1022 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1023 unsigned Dst = getOrCreateVReg(CI);
1024 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
1025 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
1026 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
1027 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
1028 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
1029 // TODO: Revisit this to see if we should move this part of the
1030 // lowering to the combiner.
Michael Bergf0d81a32019-02-06 19:57:06 +00001031 MIRBuilder.buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2},
1032 MachineInstr::copyFlagsFromInstruction(CI));
Volkan Keles92837632018-02-13 00:47:46 +00001033 } else {
1034 LLT Ty = getLLTForType(*CI.getType(), *DL);
Michael Bergf0d81a32019-02-06 19:57:06 +00001035 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1},
1036 MachineInstr::copyFlagsFromInstruction(CI));
1037 MIRBuilder.buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2},
1038 MachineInstr::copyFlagsFromInstruction(CI));
Volkan Keles92837632018-02-13 00:47:46 +00001039 }
1040 return true;
1041 }
Tim Northover3f186032016-10-18 20:03:45 +00001042 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +00001043 case Intrinsic::memmove:
1044 case Intrinsic::memset:
1045 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +00001046 case Intrinsic::eh_typeid_for: {
1047 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
1048 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +00001049 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +00001050 MIRBuilder.buildConstant(Reg, TypeID);
1051 return true;
1052 }
Tim Northover6e904302016-10-18 20:03:51 +00001053 case Intrinsic::objectsize: {
1054 // If we don't know by now, we're never going to know.
1055 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
1056
1057 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
1058 return true;
1059 }
James Y Knight72f76bf2018-11-07 15:24:12 +00001060 case Intrinsic::is_constant:
1061 // If this wasn't constant-folded away by now, then it's not a
1062 // constant.
1063 MIRBuilder.buildConstant(getOrCreateVReg(CI), 0);
1064 return true;
Tim Northovercdf23f12016-10-31 18:30:59 +00001065 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +00001066 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +00001067 return true;
1068 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001069 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +00001070 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +00001071 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +00001072
1073 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
Petr Pavlu84e89ff2018-12-10 15:15:05 +00001074 int FI = getOrCreateFrameIndex(*Slot);
1075 MF->getFrameInfo().setStackProtectorIndex(FI);
1076
Tim Northovercdf23f12016-10-31 18:30:59 +00001077 MIRBuilder.buildStore(
1078 GuardVal, getOrCreateVReg(*Slot),
Petr Pavlu84e89ff2018-12-10 15:15:05 +00001079 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1080 MachineMemOperand::MOStore |
1081 MachineMemOperand::MOVolatile,
1082 PtrTy.getSizeInBits() / 8, 8));
Tim Northovercdf23f12016-10-31 18:30:59 +00001083 return true;
1084 }
Jessica Paquetteed233522019-04-02 22:46:31 +00001085 case Intrinsic::stacksave: {
1086 // Save the stack pointer to the location provided by the intrinsic.
1087 unsigned Reg = getOrCreateVReg(CI);
1088 unsigned StackPtr = MF->getSubtarget()
1089 .getTargetLowering()
1090 ->getStackPointerRegisterToSaveRestore();
1091
1092 // If the target doesn't specify a stack pointer, then fall back.
1093 if (!StackPtr)
1094 return false;
1095
1096 MIRBuilder.buildCopy(Reg, StackPtr);
1097 return true;
1098 }
1099 case Intrinsic::stackrestore: {
1100 // Restore the stack pointer from the location provided by the intrinsic.
1101 unsigned Reg = getOrCreateVReg(*CI.getArgOperand(0));
1102 unsigned StackPtr = MF->getSubtarget()
1103 .getTargetLowering()
1104 ->getStackPointerRegisterToSaveRestore();
1105
1106 // If the target doesn't specify a stack pointer, then fall back.
1107 if (!StackPtr)
1108 return false;
1109
1110 MIRBuilder.buildCopy(StackPtr, Reg);
1111 return true;
1112 }
Aditya Nandakumare07b3b72018-08-04 01:22:12 +00001113 case Intrinsic::cttz:
1114 case Intrinsic::ctlz: {
1115 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1116 bool isTrailing = ID == Intrinsic::cttz;
1117 unsigned Opcode = isTrailing
1118 ? Cst->isZero() ? TargetOpcode::G_CTTZ
1119 : TargetOpcode::G_CTTZ_ZERO_UNDEF
1120 : Cst->isZero() ? TargetOpcode::G_CTLZ
1121 : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1122 MIRBuilder.buildInstr(Opcode)
1123 .addDef(getOrCreateVReg(CI))
1124 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
1125 return true;
1126 }
Jessica Paquetteb328d952018-10-05 21:02:46 +00001127 case Intrinsic::invariant_start: {
1128 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1129 unsigned Undef = MRI->createGenericVirtualRegister(PtrTy);
1130 MIRBuilder.buildUndef(Undef);
1131 return true;
1132 }
1133 case Intrinsic::invariant_end:
1134 return true;
Volkan Keles97204a62019-06-07 20:19:27 +00001135 case Intrinsic::assume:
1136 case Intrinsic::var_annotation:
1137 case Intrinsic::sideeffect:
1138 // Discard annotate attributes, assumptions, and artificial side-effects.
1139 return true;
Tim Northover91c81732016-08-19 17:17:06 +00001140 }
Tim Northover1e656ec2016-12-08 22:44:00 +00001141 return false;
Tim Northover91c81732016-08-19 17:17:06 +00001142}
1143
Tim Northoveraa995c92017-03-09 23:36:26 +00001144bool IRTranslator::translateInlineAsm(const CallInst &CI,
1145 MachineIRBuilder &MIRBuilder) {
1146 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1147 if (!IA.getConstraintString().empty())
1148 return false;
1149
1150 unsigned ExtraInfo = 0;
1151 if (IA.hasSideEffects())
1152 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1153 if (IA.getDialect() == InlineAsm::AD_Intel)
1154 ExtraInfo |= InlineAsm::Extra_AsmDialect;
1155
1156 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1157 .addExternalSymbol(IA.getAsmString().c_str())
1158 .addImm(ExtraInfo);
1159
1160 return true;
1161}
1162
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001163unsigned IRTranslator::packRegs(const Value &V,
1164 MachineIRBuilder &MIRBuilder) {
1165 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1166 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1167 LLT BigTy = getLLTForType(*V.getType(), *DL);
1168
1169 if (Regs.size() == 1)
1170 return Regs[0];
1171
1172 unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
1173 MIRBuilder.buildUndef(Dst);
1174 for (unsigned i = 0; i < Regs.size(); ++i) {
1175 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
1176 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
1177 Dst = NewDst;
1178 }
1179 return Dst;
1180}
1181
1182void IRTranslator::unpackRegs(const Value &V, unsigned Src,
1183 MachineIRBuilder &MIRBuilder) {
1184 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1185 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1186
1187 for (unsigned i = 0; i < Regs.size(); ++i)
1188 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
1189}
1190
Tim Northoverc53606e2016-12-07 21:29:15 +00001191bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001192 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001193 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +00001194 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +00001195
Martin Storsjocc981d22018-01-30 19:50:58 +00001196 // FIXME: support Windows dllimport function calls.
1197 if (F && F->hasDLLImportStorageClass())
1198 return false;
1199
Tim Northover3babfef2017-01-19 23:59:35 +00001200 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +00001201 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +00001202
Amara Emerson913918c2018-01-02 18:56:39 +00001203 Intrinsic::ID ID = Intrinsic::not_intrinsic;
1204 if (F && F->isIntrinsic()) {
1205 ID = F->getIntrinsicID();
1206 if (TII && ID == Intrinsic::not_intrinsic)
1207 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1208 }
1209
1210 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
Matt Arsenault13371692019-03-14 14:18:56 +00001211 bool IsSplitType = valueIsSplit(CI);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001212 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
1213 getLLTForType(*CI.getType(), *DL))
1214 : getOrCreateVReg(CI);
1215
Tim Northover406024a2016-08-10 21:44:01 +00001216 SmallVector<unsigned, 8> Args;
Tim Northover3b2157a2019-05-24 08:40:13 +00001217 unsigned SwiftErrorVReg = 0;
1218 for (auto &Arg: CI.arg_operands()) {
1219 if (CLI->supportSwiftError() && isSwiftError(Arg)) {
1220 LLT Ty = getLLTForType(*Arg->getType(), *DL);
1221 unsigned InVReg = MRI->createGenericVirtualRegister(Ty);
1222 MIRBuilder.buildCopy(InVReg, SwiftError.getOrCreateVRegUseAt(
1223 &CI, &MIRBuilder.getMBB(), Arg));
1224 Args.push_back(InVReg);
1225 SwiftErrorVReg =
1226 SwiftError.getOrCreateVRegDefAt(&CI, &MIRBuilder.getMBB(), Arg);
1227 continue;
1228 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001229 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northover3b2157a2019-05-24 08:40:13 +00001230 }
Tim Northover406024a2016-08-10 21:44:01 +00001231
Tim Northoverd1e951e2017-03-09 22:00:39 +00001232 MF->getFrameInfo().setHasCalls(true);
Tim Northover3b2157a2019-05-24 08:40:13 +00001233 bool Success =
1234 CLI->lowerCall(MIRBuilder, &CI, Res, Args, SwiftErrorVReg,
1235 [&]() { return getOrCreateVReg(*CI.getCalledValue()); });
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001236
1237 if (IsSplitType)
1238 unpackRegs(CI, Res, MIRBuilder);
Tim Northover3b2157a2019-05-24 08:40:13 +00001239
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001240 return Success;
Tim Northover406024a2016-08-10 21:44:01 +00001241 }
1242
Tim Northover406024a2016-08-10 21:44:01 +00001243 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +00001244
Tim Northoverc53606e2016-12-07 21:29:15 +00001245 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +00001246 return true;
1247
Matt Arsenault13371692019-03-14 14:18:56 +00001248 ArrayRef<unsigned> ResultRegs;
1249 if (!CI.getType()->isVoidTy())
1250 ResultRegs = getOrCreateVRegs(CI);
1251
Matt Arsenault3e140062019-06-17 17:01:35 +00001252 // Ignore the callsite attributes. Backend code is most likely not expecting
1253 // an intrinsic to sometimes have side effects and sometimes not.
Tim Northover5fb414d2016-07-29 22:32:36 +00001254 MachineInstrBuilder MIB =
Matt Arsenault3e140062019-06-17 17:01:35 +00001255 MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory());
Michael Bergd573aa02019-04-18 18:48:57 +00001256 if (isa<FPMathOperator>(CI))
1257 MIB->copyIRFlags(CI);
Tim Northover5fb414d2016-07-29 22:32:36 +00001258
1259 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +00001260 // Some intrinsics take metadata parameters. Reject them.
1261 if (isa<MetadataAsValue>(Arg))
1262 return false;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001263 MIB.addUse(packRegs(*Arg, MIRBuilder));
Tim Northover5fb414d2016-07-29 22:32:36 +00001264 }
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001265
1266 // Add a MachineMemOperand if it is a target mem intrinsic.
1267 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1268 TargetLowering::IntrinsicInfo Info;
1269 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
Matt Arsenault7d7adf42017-12-14 22:34:10 +00001270 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
Matt Arsenault50d65792019-01-31 23:41:23 +00001271 unsigned Align = Info.align;
1272 if (Align == 0)
1273 Align = DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext()));
Matt Arsenault2a645982019-01-31 01:38:47 +00001274
Matt Arsenault50d65792019-01-31 23:41:23 +00001275 uint64_t Size = Info.memVT.getStoreSize();
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001276 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
Matt Arsenault50d65792019-01-31 23:41:23 +00001277 Info.flags, Size, Align));
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001278 }
1279
Tim Northover5fb414d2016-07-29 22:32:36 +00001280 return true;
1281}
1282
Tim Northoverc53606e2016-12-07 21:29:15 +00001283bool IRTranslator::translateInvoke(const User &U,
1284 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001285 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001286 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +00001287
1288 const BasicBlock *ReturnBB = I.getSuccessor(0);
1289 const BasicBlock *EHPadBB = I.getSuccessor(1);
1290
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001291 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +00001292 const Function *Fn = dyn_cast<Function>(Callee);
1293 if (isa<InlineAsm>(Callee))
1294 return false;
1295
1296 // FIXME: support invoking patchpoint and statepoint intrinsics.
1297 if (Fn && Fn->isIntrinsic())
1298 return false;
1299
1300 // FIXME: support whatever these are.
1301 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1302 return false;
1303
1304 // FIXME: support Windows exception handling.
1305 if (!isa<LandingPadInst>(EHPadBB->front()))
1306 return false;
1307
Matthias Braund0ee66c2016-12-01 19:32:15 +00001308 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +00001309 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +00001310 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001311 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1312
Matt Arsenault0aab9992019-04-10 17:27:55 +00001313 unsigned Res = 0;
1314 if (!I.getType()->isVoidTy())
1315 Res = MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
Tim Northover293f7432017-01-31 18:36:11 +00001316 SmallVector<unsigned, 8> Args;
Tim Northover3b2157a2019-05-24 08:40:13 +00001317 unsigned SwiftErrorVReg = 0;
1318 for (auto &Arg : I.arg_operands()) {
1319 if (CLI->supportSwiftError() && isSwiftError(Arg)) {
1320 LLT Ty = getLLTForType(*Arg->getType(), *DL);
1321 unsigned InVReg = MRI->createGenericVirtualRegister(Ty);
1322 MIRBuilder.buildCopy(InVReg, SwiftError.getOrCreateVRegUseAt(
1323 &I, &MIRBuilder.getMBB(), Arg));
1324 Args.push_back(InVReg);
1325 SwiftErrorVReg =
1326 SwiftError.getOrCreateVRegDefAt(&I, &MIRBuilder.getMBB(), Arg);
1327 continue;
1328 }
Tim Northovera9105be2016-11-09 22:39:54 +00001329
Tim Northover3b2157a2019-05-24 08:40:13 +00001330 Args.push_back(packRegs(*Arg, MIRBuilder));
1331 }
1332
1333 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args, SwiftErrorVReg,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001334 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1335 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001336
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001337 unpackRegs(I, Res, MIRBuilder);
1338
Matthias Braund0ee66c2016-12-01 19:32:15 +00001339 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001340 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1341
1342 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001343 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1344 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +00001345 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +00001346 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1347 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +00001348 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001349
1350 return true;
1351}
1352
Craig Topper784929d2019-02-08 20:48:56 +00001353bool IRTranslator::translateCallBr(const User &U,
1354 MachineIRBuilder &MIRBuilder) {
1355 // FIXME: Implement this.
1356 return false;
1357}
1358
Tim Northoverc53606e2016-12-07 21:29:15 +00001359bool IRTranslator::translateLandingPad(const User &U,
1360 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001361 const LandingPadInst &LP = cast<LandingPadInst>(U);
1362
1363 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Tim Northovera9105be2016-11-09 22:39:54 +00001364
1365 MBB.setIsEHPad();
1366
1367 // If there aren't registers to copy the values into (e.g., during SjLj
1368 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +00001369 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +00001370 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +00001371 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1372 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1373 return true;
1374
1375 // If landingpad's return type is token type, we don't create DAG nodes
1376 // for its exception pointer and selector value. The extraction of exception
1377 // pointer or selector value from token type landingpads is not currently
1378 // supported.
1379 if (LP.getType()->isTokenTy())
1380 return true;
1381
1382 // Add a label to mark the beginning of the landing pad. Deletion of the
1383 // landing pad can thus be detected via the MachineModuleInfo.
1384 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +00001385 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +00001386
Daniel Sanders1351db42017-03-07 23:32:10 +00001387 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +00001388 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1389 MIRBuilder.buildUndef(Undef);
1390
Justin Bognera0295312017-01-25 00:16:53 +00001391 SmallVector<LLT, 2> Tys;
1392 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001393 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +00001394 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1395
Tim Northovera9105be2016-11-09 22:39:54 +00001396 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +00001397 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1398 if (!ExceptionReg)
1399 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001400
Tim Northover542d1c12017-03-07 23:04:06 +00001401 MBB.addLiveIn(ExceptionReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001402 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1403 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
Tim Northoverc9449702017-01-30 20:52:42 +00001404
Tim Northover542d1c12017-03-07 23:04:06 +00001405 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1406 if (!SelectorReg)
1407 return false;
Tim Northoverc9449702017-01-30 20:52:42 +00001408
Tim Northover542d1c12017-03-07 23:04:06 +00001409 MBB.addLiveIn(SelectorReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001410 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1411 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001412 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001413
Tim Northovera9105be2016-11-09 22:39:54 +00001414 return true;
1415}
1416
Tim Northoverc3e3f592017-02-03 18:22:45 +00001417bool IRTranslator::translateAlloca(const User &U,
1418 MachineIRBuilder &MIRBuilder) {
1419 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001420
Amara Emersonfdd089a2018-07-26 01:25:58 +00001421 if (AI.isSwiftError())
Tim Northover3b2157a2019-05-24 08:40:13 +00001422 return true;
Amara Emersonfdd089a2018-07-26 01:25:58 +00001423
Tim Northoverc3e3f592017-02-03 18:22:45 +00001424 if (AI.isStaticAlloca()) {
1425 unsigned Res = getOrCreateVReg(AI);
1426 int FI = getOrCreateFrameIndex(AI);
1427 MIRBuilder.buildFrameIndex(Res, FI);
1428 return true;
1429 }
1430
Martin Storsjoa63a5b92018-02-17 14:26:32 +00001431 // FIXME: support stack probing for Windows.
1432 if (MF->getTarget().getTargetTriple().isOSWindows())
1433 return false;
1434
Tim Northoverc3e3f592017-02-03 18:22:45 +00001435 // Now we're in the harder dynamic case.
1436 Type *Ty = AI.getAllocatedType();
1437 unsigned Align =
1438 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1439
1440 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1441
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001442 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1443 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001444 if (MRI->getType(NumElts) != IntPtrTy) {
1445 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1446 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1447 NumElts = ExtElts;
1448 }
1449
1450 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001451 unsigned TySize =
1452 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +00001453 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1454
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001455 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001456 auto &TLI = *MF->getSubtarget().getTargetLowering();
1457 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1458
1459 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1460 MIRBuilder.buildCopy(SPTmp, SPReg);
1461
Tim Northoverc2f89562017-02-14 20:56:18 +00001462 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1463 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001464
1465 // Handle alignment. We have to realign if the allocation granule was smaller
1466 // than stack alignment, or the specific alloca requires more than stack
1467 // alignment.
1468 unsigned StackAlign =
1469 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1470 Align = std::max(Align, StackAlign);
1471 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1472 // Round the size of the allocation up to the stack alignment size
1473 // by add SA-1 to the size. This doesn't overflow because we're computing
1474 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +00001475 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1476 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1477 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +00001478 }
1479
Tim Northoverc2f89562017-02-14 20:56:18 +00001480 MIRBuilder.buildCopy(SPReg, AllocTmp);
1481 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001482
1483 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1484 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +00001485 return true;
1486}
1487
Tim Northover4a652222017-02-15 23:22:33 +00001488bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1489 // FIXME: We may need more info about the type. Because of how LLT works,
1490 // we're completely discarding the i64/double distinction here (amongst
1491 // others). Fortunately the ABIs I know of where that matters don't use va_arg
1492 // anyway but that's not guaranteed.
1493 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1494 .addDef(getOrCreateVReg(U))
1495 .addUse(getOrCreateVReg(*U.getOperand(0)))
1496 .addImm(DL->getABITypeAlignment(U.getType()));
1497 return true;
1498}
1499
Volkan Keles04cb08c2017-03-10 19:08:28 +00001500bool IRTranslator::translateInsertElement(const User &U,
1501 MachineIRBuilder &MIRBuilder) {
1502 // If it is a <1 x Ty> vector, use the scalar as it is
1503 // not a legal vector type in LLT.
1504 if (U.getType()->getVectorNumElements() == 1) {
1505 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001506 auto &Regs = *VMap.getVRegs(U);
1507 if (Regs.empty()) {
1508 Regs.push_back(Elt);
1509 VMap.getOffsets(U)->push_back(0);
1510 } else {
1511 MIRBuilder.buildCopy(Regs[0], Elt);
1512 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001513 return true;
1514 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001515
Kristof Beyls7a713502017-04-19 06:38:37 +00001516 unsigned Res = getOrCreateVReg(U);
1517 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1518 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1519 unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1520 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001521 return true;
1522}
1523
1524bool IRTranslator::translateExtractElement(const User &U,
1525 MachineIRBuilder &MIRBuilder) {
1526 // If it is a <1 x Ty> vector, use the scalar as it is
1527 // not a legal vector type in LLT.
1528 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1529 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001530 auto &Regs = *VMap.getVRegs(U);
1531 if (Regs.empty()) {
1532 Regs.push_back(Elt);
1533 VMap.getOffsets(U)->push_back(0);
1534 } else {
1535 MIRBuilder.buildCopy(Regs[0], Elt);
1536 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001537 return true;
1538 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001539 unsigned Res = getOrCreateVReg(U);
1540 unsigned Val = getOrCreateVReg(*U.getOperand(0));
Amara Emersoncbd86d82018-10-25 14:04:54 +00001541 const auto &TLI = *MF->getSubtarget().getTargetLowering();
1542 unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1543 unsigned Idx = 0;
1544 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1545 if (CI->getBitWidth() != PreferredVecIdxWidth) {
1546 APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1547 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1548 Idx = getOrCreateVReg(*NewIdxCI);
1549 }
1550 }
1551 if (!Idx)
1552 Idx = getOrCreateVReg(*U.getOperand(1));
1553 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1554 const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1555 Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg();
1556 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001557 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001558 return true;
1559}
1560
Volkan Keles75bdc762017-03-21 08:44:13 +00001561bool IRTranslator::translateShuffleVector(const User &U,
1562 MachineIRBuilder &MIRBuilder) {
1563 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1564 .addDef(getOrCreateVReg(U))
1565 .addUse(getOrCreateVReg(*U.getOperand(0)))
1566 .addUse(getOrCreateVReg(*U.getOperand(1)))
1567 .addUse(getOrCreateVReg(*U.getOperand(2)));
1568 return true;
1569}
1570
Tim Northoverc53606e2016-12-07 21:29:15 +00001571bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001572 const PHINode &PI = cast<PHINode>(U);
Tim Northover97d0cb32016-08-05 17:16:40 +00001573
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001574 SmallVector<MachineInstr *, 4> Insts;
1575 for (auto Reg : getOrCreateVRegs(PI)) {
Aditya Nandakumarcef44a22018-12-11 00:48:50 +00001576 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001577 Insts.push_back(MIB.getInstr());
1578 }
1579
1580 PendingPHIs.emplace_back(&PI, std::move(Insts));
Tim Northover97d0cb32016-08-05 17:16:40 +00001581 return true;
1582}
1583
Daniel Sanders94813992018-07-09 19:33:40 +00001584bool IRTranslator::translateAtomicCmpXchg(const User &U,
1585 MachineIRBuilder &MIRBuilder) {
1586 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1587
1588 if (I.isWeak())
1589 return false;
1590
1591 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1592 : MachineMemOperand::MONone;
1593 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1594
1595 Type *ResType = I.getType();
1596 Type *ValType = ResType->Type::getStructElementType(0);
1597
1598 auto Res = getOrCreateVRegs(I);
1599 unsigned OldValRes = Res[0];
1600 unsigned SuccessRes = Res[1];
1601 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1602 unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1603 unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1604
1605 MIRBuilder.buildAtomicCmpXchgWithSuccess(
1606 OldValRes, SuccessRes, Addr, Cmp, NewVal,
1607 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1608 Flags, DL->getTypeStoreSize(ValType),
1609 getMemOpAlignment(I), AAMDNodes(), nullptr,
1610 I.getSyncScopeID(), I.getSuccessOrdering(),
1611 I.getFailureOrdering()));
1612 return true;
1613}
1614
1615bool IRTranslator::translateAtomicRMW(const User &U,
1616 MachineIRBuilder &MIRBuilder) {
1617 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1618
1619 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1620 : MachineMemOperand::MONone;
1621 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1622
1623 Type *ResType = I.getType();
1624
1625 unsigned Res = getOrCreateVReg(I);
1626 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1627 unsigned Val = getOrCreateVReg(*I.getValOperand());
1628
1629 unsigned Opcode = 0;
1630 switch (I.getOperation()) {
1631 default:
1632 llvm_unreachable("Unknown atomicrmw op");
1633 return false;
1634 case AtomicRMWInst::Xchg:
1635 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1636 break;
1637 case AtomicRMWInst::Add:
1638 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1639 break;
1640 case AtomicRMWInst::Sub:
1641 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1642 break;
1643 case AtomicRMWInst::And:
1644 Opcode = TargetOpcode::G_ATOMICRMW_AND;
1645 break;
1646 case AtomicRMWInst::Nand:
1647 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1648 break;
1649 case AtomicRMWInst::Or:
1650 Opcode = TargetOpcode::G_ATOMICRMW_OR;
1651 break;
1652 case AtomicRMWInst::Xor:
1653 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1654 break;
1655 case AtomicRMWInst::Max:
1656 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1657 break;
1658 case AtomicRMWInst::Min:
1659 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1660 break;
1661 case AtomicRMWInst::UMax:
1662 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1663 break;
1664 case AtomicRMWInst::UMin:
1665 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1666 break;
1667 }
1668
1669 MIRBuilder.buildAtomicRMW(
1670 Opcode, Res, Addr, Val,
1671 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1672 Flags, DL->getTypeStoreSize(ResType),
1673 getMemOpAlignment(I), AAMDNodes(), nullptr,
1674 I.getSyncScopeID(), I.getOrdering()));
1675 return true;
1676}
1677
Tim Northover97d0cb32016-08-05 17:16:40 +00001678void IRTranslator::finishPendingPhis() {
Daniel Sanders3b390402018-10-31 17:31:23 +00001679#ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001680 DILocationVerifier Verifier;
1681 GISelObserverWrapper WrapperObserver(&Verifier);
1682 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
Daniel Sanders3b390402018-10-31 17:31:23 +00001683#endif // ifndef NDEBUG
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001684 for (auto &Phi : PendingPHIs) {
Tim Northover97d0cb32016-08-05 17:16:40 +00001685 const PHINode *PI = Phi.first;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001686 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001687 EntryBuilder->setDebugLoc(PI->getDebugLoc());
Daniel Sanders3b390402018-10-31 17:31:23 +00001688#ifndef NDEBUG
1689 Verifier.setCurrentInst(PI);
1690#endif // ifndef NDEBUG
Tim Northover97d0cb32016-08-05 17:16:40 +00001691
1692 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1693 // won't create extra control flow here, otherwise we need to find the
1694 // dominating predecessor here (or perhaps force the weirder IRTranslators
1695 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001696 SmallSet<const BasicBlock *, 4> HandledPreds;
1697
Tim Northover97d0cb32016-08-05 17:16:40 +00001698 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001699 auto IRPred = PI->getIncomingBlock(i);
1700 if (HandledPreds.count(IRPred))
1701 continue;
1702
1703 HandledPreds.insert(IRPred);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001704 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
Tim Northoverb6636fd2017-01-17 22:13:50 +00001705 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001706 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
Tim Northoverb6636fd2017-01-17 22:13:50 +00001707 "incorrect CFG at MachineBasicBlock level");
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001708 for (unsigned j = 0; j < ValRegs.size(); ++j) {
1709 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1710 MIB.addUse(ValRegs[j]);
1711 MIB.addMBB(Pred);
1712 }
Tim Northoverb6636fd2017-01-17 22:13:50 +00001713 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001714 }
1715 }
1716}
1717
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001718bool IRTranslator::valueIsSplit(const Value &V,
1719 SmallVectorImpl<uint64_t> *Offsets) {
1720 SmallVector<LLT, 4> SplitTys;
Amara Emerson30e61402018-08-14 12:04:25 +00001721 if (Offsets && !Offsets->empty())
1722 Offsets->clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001723 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1724 return SplitTys.size() > 1;
1725}
1726
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001727bool IRTranslator::translate(const Instruction &Inst) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001728 CurBuilder->setDebugLoc(Inst.getDebugLoc());
Amara Emersonfb0a40f2019-06-13 22:15:35 +00001729 // We only emit constants into the entry block from here. To prevent jumpy
1730 // debug behaviour set the line to 0.
1731 if (const DebugLoc &DL = Inst.getDebugLoc())
1732 EntryBuilder->setDebugLoc(
1733 DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
1734 else
1735 EntryBuilder->setDebugLoc(DebugLoc());
1736
1737 switch (Inst.getOpcode()) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001738#define HANDLE_INST(NUM, OPCODE, CLASS) \
1739 case Instruction::OPCODE: \
1740 return translate##OPCODE(Inst, *CurBuilder.get());
Tim Northover357f1be2016-08-10 23:02:41 +00001741#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001742 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001743 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001744 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001745}
1746
Tim Northover5ed648e2016-08-09 21:28:04 +00001747bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001748 if (auto CI = dyn_cast<ConstantInt>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001749 EntryBuilder->buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001750 else if (auto CF = dyn_cast<ConstantFP>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001751 EntryBuilder->buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001752 else if (isa<UndefValue>(C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001753 EntryBuilder->buildUndef(Reg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001754 else if (isa<ConstantPointerNull>(C)) {
1755 // As we are trying to build a constant val of 0 into a pointer,
1756 // insert a cast to make them correct with respect to types.
1757 unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1758 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1759 auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1760 unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001761 EntryBuilder->buildCast(Reg, ZeroReg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001762 } else if (auto GV = dyn_cast<GlobalValue>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001763 EntryBuilder->buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001764 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1765 if (!CAZ->getType()->isVectorTy())
1766 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001767 // Return the scalar if it is a <1 x Ty> vector.
1768 if (CAZ->getNumElements() == 1)
1769 return translate(*CAZ->getElementValue(0u), Reg);
Amara Emerson5ec14602018-12-10 18:44:58 +00001770 SmallVector<unsigned, 4> Ops;
Volkan Keles970fee42017-03-10 21:23:13 +00001771 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1772 Constant &Elt = *CAZ->getElementValue(i);
1773 Ops.push_back(getOrCreateVReg(Elt));
1774 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001775 EntryBuilder->buildBuildVector(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001776 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001777 // Return the scalar if it is a <1 x Ty> vector.
1778 if (CV->getNumElements() == 1)
1779 return translate(*CV->getElementAsConstant(0), Reg);
Amara Emerson5ec14602018-12-10 18:44:58 +00001780 SmallVector<unsigned, 4> Ops;
Volkan Keles38a91a02017-03-13 21:36:19 +00001781 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1782 Constant &Elt = *CV->getElementAsConstant(i);
1783 Ops.push_back(getOrCreateVReg(Elt));
1784 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001785 EntryBuilder->buildBuildVector(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001786 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001787 switch(CE->getOpcode()) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001788#define HANDLE_INST(NUM, OPCODE, CLASS) \
1789 case Instruction::OPCODE: \
1790 return translate##OPCODE(*CE, *EntryBuilder.get());
Tim Northover357f1be2016-08-10 23:02:41 +00001791#include "llvm/IR/Instruction.def"
1792 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001793 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001794 }
Aditya Nandakumar117b6672017-05-04 21:43:12 +00001795 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1796 if (CV->getNumOperands() == 1)
1797 return translate(*CV->getOperand(0), Reg);
1798 SmallVector<unsigned, 4> Ops;
1799 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1800 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1801 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001802 EntryBuilder->buildBuildVector(Reg, Ops);
Amara Emerson6aff5a72018-07-31 00:08:50 +00001803 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001804 EntryBuilder->buildBlockAddress(Reg, BA);
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001805 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001806 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001807
Tim Northoverd403a3d2016-08-09 23:01:30 +00001808 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001809}
1810
Tim Northover0d510442016-08-11 16:21:29 +00001811void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001812 // Release the memory used by the different maps we
1813 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001814 PendingPHIs.clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001815 VMap.reset();
Tim Northovercdf23f12016-10-31 18:30:59 +00001816 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001817 MachinePreds.clear();
Aditya Nandakumarbe929932017-05-17 17:41:55 +00001818 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1819 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1820 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001821 EntryBuilder.reset();
1822 CurBuilder.reset();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001823}
1824
Tim Northover50db7f412016-12-07 21:17:47 +00001825bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1826 MF = &CurMF;
Matthias Braunf1caa282017-12-15 22:22:58 +00001827 const Function &F = MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001828 if (F.empty())
1829 return false;
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001830 GISelCSEAnalysisWrapper &Wrapper =
1831 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
1832 // Set the CSEConfig and run the analysis.
1833 GISelCSEInfo *CSEInfo = nullptr;
1834 TPC = &getAnalysis<TargetPassConfig>();
Aditya Nandakumar3ba0d942019-01-24 23:11:25 +00001835 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
1836 ? EnableCSEInIRTranslator
1837 : TPC->isGISelCSEEnabled();
1838
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001839 if (EnableCSE) {
1840 EntryBuilder = make_unique<CSEMIRBuilder>(CurMF);
Amara Emersond1896802019-04-15 04:53:46 +00001841 CSEInfo = &Wrapper.get(TPC->getCSEConfig());
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001842 EntryBuilder->setCSEInfo(CSEInfo);
1843 CurBuilder = make_unique<CSEMIRBuilder>(CurMF);
1844 CurBuilder->setCSEInfo(CSEInfo);
1845 } else {
1846 EntryBuilder = make_unique<MachineIRBuilder>();
1847 CurBuilder = make_unique<MachineIRBuilder>();
1848 }
Tim Northover50db7f412016-12-07 21:17:47 +00001849 CLI = MF->getSubtarget().getCallLowering();
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001850 CurBuilder->setMF(*MF);
1851 EntryBuilder->setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001852 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001853 DL = &F.getParent()->getDataLayout();
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001854 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001855
Tim Northover14e7f732016-08-05 17:50:36 +00001856 assert(PendingPHIs.empty() && "stale PHIs");
1857
Amara Emersondf9b5292017-12-11 16:58:29 +00001858 if (!DL->isLittleEndian()) {
1859 // Currently we don't properly handle big endian code.
1860 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001861 F.getSubprogram(), &F.getEntryBlock());
Amara Emersondf9b5292017-12-11 16:58:29 +00001862 R << "unable to translate in big endian mode";
1863 reportTranslationError(*MF, *TPC, *ORE, R);
1864 }
1865
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001866 // Release the per-function state when we return, whether we succeeded or not.
1867 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1868
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001869 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001870 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1871 MF->push_back(EntryBB);
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001872 EntryBuilder->setMBB(*EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001873
Tim Northover3b2157a2019-05-24 08:40:13 +00001874 DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc();
1875 SwiftError.setFunction(CurMF);
1876 SwiftError.createEntriesInEntryBlock(DbgLoc);
1877
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001878 // Create all blocks, in IR order, to preserve the layout.
1879 for (const BasicBlock &BB: F) {
1880 auto *&MBB = BBToMBB[&BB];
1881
1882 MBB = MF->CreateMachineBasicBlock(&BB);
1883 MF->push_back(MBB);
1884
1885 if (BB.hasAddressTaken())
1886 MBB->setHasAddressTaken();
1887 }
1888
1889 // Make our arguments/constants entry block fallthrough to the IR entry block.
1890 EntryBB->addSuccessor(&getMBB(F.front()));
1891
Tim Northover05cc4852016-12-07 21:05:38 +00001892 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001893 SmallVector<unsigned, 8> VRegArgs;
Amara Emersond78d65c2017-11-30 20:06:02 +00001894 for (const Argument &Arg: F.args()) {
1895 if (DL->getTypeStoreSize(Arg.getType()) == 0)
1896 continue; // Don't handle zero sized types.
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001897 VRegArgs.push_back(
1898 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
Tim Northover3b2157a2019-05-24 08:40:13 +00001899
1900 if (Arg.hasSwiftErrorAttr())
1901 SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(),
1902 VRegArgs.back());
Amara Emersond78d65c2017-11-30 20:06:02 +00001903 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001904
Amara Emersonfdd089a2018-07-26 01:25:58 +00001905 // We don't currently support translating swifterror or swiftself functions.
1906 for (auto &Arg : F.args()) {
Tim Northover3b2157a2019-05-24 08:40:13 +00001907 if (Arg.hasSwiftSelfAttr()) {
Amara Emersonfdd089a2018-07-26 01:25:58 +00001908 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1909 F.getSubprogram(), &F.getEntryBlock());
Tim Northover3b2157a2019-05-24 08:40:13 +00001910 R << "unable to lower arguments due to swiftself: "
Amara Emersonfdd089a2018-07-26 01:25:58 +00001911 << ore::NV("Prototype", F.getType());
1912 reportTranslationError(*MF, *TPC, *ORE, R);
1913 return false;
1914 }
1915 }
1916
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001917 if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001918 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001919 F.getSubprogram(), &F.getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001920 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1921 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001922 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001923 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001924
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001925 auto ArgIt = F.arg_begin();
1926 for (auto &VArg : VRegArgs) {
1927 // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1928 // creating redundant copies.
1929 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1930 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1931 assert(VRegs.empty() && "VRegs already populated?");
1932 VRegs.push_back(VArg);
1933 } else {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001934 unpackRegs(*ArgIt, VArg, *EntryBuilder.get());
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001935 }
1936 ArgIt++;
1937 }
1938
Amara Emerson6cdfe292018-08-01 02:17:42 +00001939 // Need to visit defs before uses when translating instructions.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001940 GISelObserverWrapper WrapperObserver;
1941 if (EnableCSE && CSEInfo)
1942 WrapperObserver.addObserver(CSEInfo);
Daniel Sanders3b390402018-10-31 17:31:23 +00001943 {
1944 ReversePostOrderTraversal<const Function *> RPOT(&F);
1945#ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001946 DILocationVerifier Verifier;
1947 WrapperObserver.addObserver(&Verifier);
Daniel Sanders3b390402018-10-31 17:31:23 +00001948#endif // ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001949 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
Daniel Sanders3b390402018-10-31 17:31:23 +00001950 for (const BasicBlock *BB : RPOT) {
1951 MachineBasicBlock &MBB = getMBB(*BB);
1952 // Set the insertion point of all the following translations to
1953 // the end of this basic block.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001954 CurBuilder->setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001955
Daniel Sanders3b390402018-10-31 17:31:23 +00001956 for (const Instruction &Inst : *BB) {
1957#ifndef NDEBUG
1958 Verifier.setCurrentInst(&Inst);
1959#endif // ifndef NDEBUG
1960 if (translate(Inst))
1961 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001962
Daniel Sanders3b390402018-10-31 17:31:23 +00001963 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1964 Inst.getDebugLoc(), BB);
1965 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
Ahmed Bougachad630a922017-09-18 18:50:09 +00001966
Daniel Sanders3b390402018-10-31 17:31:23 +00001967 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1968 std::string InstStrStorage;
1969 raw_string_ostream InstStr(InstStrStorage);
1970 InstStr << Inst;
Ahmed Bougachad630a922017-09-18 18:50:09 +00001971
Daniel Sanders3b390402018-10-31 17:31:23 +00001972 R << ": '" << InstStr.str() << "'";
1973 }
1974
1975 reportTranslationError(*MF, *TPC, *ORE, R);
1976 return false;
Ahmed Bougachad630a922017-09-18 18:50:09 +00001977 }
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001978 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001979#ifndef NDEBUG
1980 WrapperObserver.removeObserver(&Verifier);
1981#endif
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001982 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001983
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001984 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001985
Tim Northover3b2157a2019-05-24 08:40:13 +00001986 SwiftError.propagateVRegs();
1987
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001988 // Merge the argument lowering and constants block with its single
1989 // successor, the LLVM-IR entry block. We want the basic block to
1990 // be maximal.
1991 assert(EntryBB->succ_size() == 1 &&
1992 "Custom BB used for lowering should have only one successor");
1993 // Get the successor of the current entry block.
1994 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1995 assert(NewEntryBB.pred_size() == 1 &&
1996 "LLVM-IR entry block has a predecessor!?");
1997 // Move all the instruction from the current entry block to the
1998 // new entry block.
1999 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
2000 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00002001
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00002002 // Update the live-in information for the new entry block.
2003 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
2004 NewEntryBB.addLiveIn(LiveIn);
2005 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00002006
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00002007 // Get rid of the now empty basic block.
2008 EntryBB->removeSuccessor(&NewEntryBB);
2009 MF->remove(EntryBB);
2010 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00002011
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00002012 assert(&MF->front() == &NewEntryBB &&
2013 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00002014
Matthias Braun90ad6832018-07-13 00:08:38 +00002015 // Initialize stack protector information.
2016 StackProtector &SP = getAnalysis<StackProtector>();
2017 SP.copyToMachineFrameInfo(MF->getFrameInfo());
2018
Quentin Colombet105cf2b2016-01-20 20:58:56 +00002019 return false;
2020}