blob: 8528636a67da98fe645c4f10eca9418e9da895bd [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
Eugene Zelenko76bf48d2017-06-26 22:44:03 +0000109IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
Quentin Colombet39293d32016-03-08 01:38:55 +0000110 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
Quentin Colombeta7fae162016-02-11 17:53:23 +0000111}
112
Daniel Sanders3b390402018-10-31 17:31:23 +0000113#ifndef NDEBUG
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000114namespace {
Daniel Sanders3b390402018-10-31 17:31:23 +0000115/// Verify that every instruction created has the same DILocation as the
116/// instruction being translated.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000117class DILocationVerifier : public GISelChangeObserver {
Daniel Sanders3b390402018-10-31 17:31:23 +0000118 const Instruction *CurrInst = nullptr;
119
120public:
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000121 DILocationVerifier() = default;
122 ~DILocationVerifier() = default;
Daniel Sanders3b390402018-10-31 17:31:23 +0000123
124 const Instruction *getCurrentInst() const { return CurrInst; }
125 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
126
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000127 void erasingInstr(MachineInstr &MI) override {}
128 void changingInstr(MachineInstr &MI) override {}
129 void changedInstr(MachineInstr &MI) override {}
130
131 void createdInstr(MachineInstr &MI) override {
Daniel Sanders3b390402018-10-31 17:31:23 +0000132 assert(getCurrentInst() && "Inserted instruction without a current MI");
133
134 // Only print the check message if we're actually checking it.
135#ifndef NDEBUG
136 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
137 << " was copied to " << MI);
138#endif
139 assert(CurrInst->getDebugLoc() == MI.getDebugLoc() &&
140 "Line info was not transferred to all instructions");
141 }
Daniel Sanders3b390402018-10-31 17:31:23 +0000142};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000143} // namespace
Daniel Sanders3b390402018-10-31 17:31:23 +0000144#endif // ifndef NDEBUG
145
146
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000147void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
Matthias Braun90ad6832018-07-13 00:08:38 +0000148 AU.addRequired<StackProtector>();
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000149 AU.addRequired<TargetPassConfig>();
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +0000150 AU.addRequired<GISelCSEAnalysisWrapperPass>();
Matthias Braun90ad6832018-07-13 00:08:38 +0000151 getSelectionDAGFallbackAnalysisUsage(AU);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000152 MachineFunctionPass::getAnalysisUsage(AU);
153}
154
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000155static void computeValueLLTs(const DataLayout &DL, Type &Ty,
156 SmallVectorImpl<LLT> &ValueTys,
157 SmallVectorImpl<uint64_t> *Offsets = nullptr,
158 uint64_t StartingOffset = 0) {
159 // Given a struct type, recursively traverse the elements.
160 if (StructType *STy = dyn_cast<StructType>(&Ty)) {
161 const StructLayout *SL = DL.getStructLayout(STy);
162 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
163 computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
164 StartingOffset + SL->getElementOffset(I));
165 return;
166 }
167 // Given an array type, recursively traverse the elements.
168 if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
169 Type *EltTy = ATy->getElementType();
170 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
171 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
172 computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
173 StartingOffset + i * EltSize);
174 return;
175 }
176 // Interpret void as zero return values.
177 if (Ty.isVoidTy())
178 return;
179 // Base case: we can get an LLT for this LLVM IR type.
180 ValueTys.push_back(getLLTForType(Ty, DL));
181 if (Offsets != nullptr)
182 Offsets->push_back(StartingOffset * 8);
183}
Tim Northover5ed648e2016-08-09 21:28:04 +0000184
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000185IRTranslator::ValueToVRegInfo::VRegListT &
186IRTranslator::allocateVRegs(const Value &Val) {
187 assert(!VMap.contains(Val) && "Value already allocated in VMap");
188 auto *Regs = VMap.getVRegs(Val);
189 auto *Offsets = VMap.getOffsets(Val);
190 SmallVector<LLT, 4> SplitTys;
191 computeValueLLTs(*DL, *Val.getType(), SplitTys,
192 Offsets->empty() ? Offsets : nullptr);
193 for (unsigned i = 0; i < SplitTys.size(); ++i)
194 Regs->push_back(0);
195 return *Regs;
196}
Tim Northover9e35f1e2017-01-25 20:58:22 +0000197
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000198ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
199 auto VRegsIt = VMap.findVRegs(Val);
200 if (VRegsIt != VMap.vregs_end())
201 return *VRegsIt->second;
202
203 if (Val.getType()->isVoidTy())
204 return *VMap.getVRegs(Val);
205
206 // Create entry for this type.
207 auto *VRegs = VMap.getVRegs(Val);
208 auto *Offsets = VMap.getOffsets(Val);
209
Tim Northover9e35f1e2017-01-25 20:58:22 +0000210 assert(Val.getType()->isSized() &&
211 "Don't know how to create an empty vreg");
Tim Northover9e35f1e2017-01-25 20:58:22 +0000212
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000213 SmallVector<LLT, 4> SplitTys;
214 computeValueLLTs(*DL, *Val.getType(), SplitTys,
215 Offsets->empty() ? Offsets : nullptr);
216
217 if (!isa<Constant>(Val)) {
218 for (auto Ty : SplitTys)
219 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
220 return *VRegs;
221 }
222
223 if (Val.getType()->isAggregateType()) {
224 // UndefValue, ConstantAggregateZero
225 auto &C = cast<Constant>(Val);
226 unsigned Idx = 0;
227 while (auto Elt = C.getAggregateElement(Idx++)) {
228 auto EltRegs = getOrCreateVRegs(*Elt);
Fangrui Song75709322018-11-17 01:44:25 +0000229 llvm::copy(EltRegs, std::back_inserter(*VRegs));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000230 }
231 } else {
232 assert(SplitTys.size() == 1 && "unexpectedly split LLT");
233 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
234 bool Success = translate(cast<Constant>(Val), VRegs->front());
Tim Northover9e35f1e2017-01-25 20:58:22 +0000235 if (!Success) {
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000236 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +0000237 MF->getFunction().getSubprogram(),
238 &MF->getFunction().getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000239 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
240 reportTranslationError(*MF, *TPC, *ORE, R);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000241 return *VRegs;
Tim Northover5ed648e2016-08-09 21:28:04 +0000242 }
Quentin Colombet17c494b2016-02-11 17:51:31 +0000243 }
Tim Northover7f3ad2e2017-01-20 23:25:17 +0000244
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000245 return *VRegs;
Quentin Colombet17c494b2016-02-11 17:51:31 +0000246}
247
Tim Northovercdf23f12016-10-31 18:30:59 +0000248int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
249 if (FrameIndices.find(&AI) != FrameIndices.end())
250 return FrameIndices[&AI];
251
Tim Northovercdf23f12016-10-31 18:30:59 +0000252 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
253 unsigned Size =
254 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
255
256 // Always allocate at least one byte.
257 Size = std::max(Size, 1u);
258
259 unsigned Alignment = AI.getAlignment();
260 if (!Alignment)
261 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
262
263 int &FI = FrameIndices[&AI];
Tim Northover50db7f412016-12-07 21:17:47 +0000264 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
Tim Northovercdf23f12016-10-31 18:30:59 +0000265 return FI;
266}
267
Tim Northoverad2b7172016-07-26 20:23:26 +0000268unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
269 unsigned Alignment = 0;
270 Type *ValTy = nullptr;
271 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
272 Alignment = SI->getAlignment();
273 ValTy = SI->getValueOperand()->getType();
274 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
275 Alignment = LI->getAlignment();
276 ValTy = LI->getType();
Daniel Sanders94813992018-07-09 19:33:40 +0000277 } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
278 // TODO(PR27168): This instruction has no alignment attribute, but unlike
279 // the default alignment for load/store, the default here is to assume
280 // it has NATURAL alignment, not DataLayout-specified alignment.
281 const DataLayout &DL = AI->getModule()->getDataLayout();
282 Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
283 ValTy = AI->getCompareOperand()->getType();
284 } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
285 // TODO(PR27168): This instruction has no alignment attribute, but unlike
286 // the default alignment for load/store, the default here is to assume
287 // it has NATURAL alignment, not DataLayout-specified alignment.
288 const DataLayout &DL = AI->getModule()->getDataLayout();
289 Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
290 ValTy = AI->getType();
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000291 } else {
292 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
293 R << "unable to translate memop: " << ore::NV("Opcode", &I);
294 reportTranslationError(*MF, *TPC, *ORE, R);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000295 return 1;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +0000296 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000297
298 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
299}
300
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000301MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
Quentin Colombet53237a92016-03-11 17:27:43 +0000302 MachineBasicBlock *&MBB = BBToMBB[&BB];
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000303 assert(MBB && "BasicBlock was not encountered before");
Quentin Colombet17c494b2016-02-11 17:51:31 +0000304 return *MBB;
305}
306
Tim Northoverb6636fd2017-01-17 22:13:50 +0000307void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
308 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
309 MachinePreds[Edge].push_back(NewPred);
310}
311
Tim Northoverc53606e2016-12-07 21:29:15 +0000312bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
313 MachineIRBuilder &MIRBuilder) {
Tim Northover0d56e052016-07-29 18:11:21 +0000314 // FIXME: handle signed/unsigned wrapping flags.
315
Quentin Colombet2ecff3b2016-02-10 22:59:27 +0000316 // Get or create a virtual register for each value.
317 // Unless the value is a Constant => loadimm cst?
318 // or inline constant each time?
319 // Creation of a virtual register needs to have a size.
Tim Northover357f1be2016-08-10 23:02:41 +0000320 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
321 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
322 unsigned Res = getOrCreateVReg(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000323 uint16_t Flags = 0;
Michael Berg894c39f2018-09-19 18:52:08 +0000324 if (isa<Instruction>(U)) {
Michael Berg894c39f2018-09-19 18:52:08 +0000325 const Instruction &I = cast<Instruction>(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000326 Flags = MachineInstr::copyFlagsFromInstruction(I);
Michael Berg894c39f2018-09-19 18:52:08 +0000327 }
Michael Bergf0d81a32019-02-06 19:57:06 +0000328
329 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
Quentin Colombet17c494b2016-02-11 17:51:31 +0000330 return true;
Quentin Colombet105cf2b2016-01-20 20:58:56 +0000331}
332
Volkan Keles20d3c422017-03-07 18:03:28 +0000333bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
334 // -0.0 - X --> G_FNEG
335 if (isa<Constant>(U.getOperand(0)) &&
336 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
337 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
338 .addDef(getOrCreateVReg(U))
339 .addUse(getOrCreateVReg(*U.getOperand(1)));
340 return true;
341 }
342 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
343}
344
Cameron McInallycbde0d92018-11-13 18:15:47 +0000345bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
346 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
347 .addDef(getOrCreateVReg(U))
Amara Emerson203760a2019-01-26 23:47:09 +0000348 .addUse(getOrCreateVReg(*U.getOperand(0)));
Cameron McInallycbde0d92018-11-13 18:15:47 +0000349 return true;
350}
351
Tim Northoverc53606e2016-12-07 21:29:15 +0000352bool IRTranslator::translateCompare(const User &U,
353 MachineIRBuilder &MIRBuilder) {
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000354 const CmpInst *CI = dyn_cast<CmpInst>(&U);
355 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
356 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
357 unsigned Res = getOrCreateVReg(U);
358 CmpInst::Predicate Pred =
359 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
360 cast<ConstantExpr>(U).getPredicate());
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000361 if (CmpInst::isIntPredicate(Pred))
Tim Northover0f140c72016-09-09 11:46:34 +0000362 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
Tim Northover7596bd72017-03-08 18:49:54 +0000363 else if (Pred == CmpInst::FCMP_FALSE)
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000364 MIRBuilder.buildCopy(
365 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
366 else if (Pred == CmpInst::FCMP_TRUE)
367 MIRBuilder.buildCopy(
368 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
Michael Bergc6a52452018-12-18 17:54:52 +0000369 else {
Michael Bergf0d81a32019-02-06 19:57:06 +0000370 MIRBuilder.buildInstr(TargetOpcode::G_FCMP, {Res}, {Pred, Op0, Op1},
371 MachineInstr::copyFlagsFromInstruction(*CI));
Michael Bergc6a52452018-12-18 17:54:52 +0000372 }
Tim Northoverd5c23bc2016-08-19 20:48:16 +0000373
Tim Northoverde3aea0412016-08-17 20:25:25 +0000374 return true;
375}
376
Tim Northoverc53606e2016-12-07 21:29:15 +0000377bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000378 const ReturnInst &RI = cast<ReturnInst>(U);
Tim Northover0d56e052016-07-29 18:11:21 +0000379 const Value *Ret = RI.getReturnValue();
Amara Emersond78d65c2017-11-30 20:06:02 +0000380 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
381 Ret = nullptr;
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000382
383 ArrayRef<unsigned> VRegs;
384 if (Ret)
385 VRegs = getOrCreateVRegs(*Ret);
386
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000387 // The target may mess up with the insertion point, but
388 // this is not important as a return is the last instruction
389 // of the block anyway.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000390
Alexander Ivchenko49168f62018-08-02 08:33:31 +0000391 return CLI->lowerReturn(MIRBuilder, Ret, VRegs);
Quentin Colombet74d7d2f2016-02-11 18:53:28 +0000392}
393
Tim Northoverc53606e2016-12-07 21:29:15 +0000394bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000395 const BranchInst &BrInst = cast<BranchInst>(U);
Tim Northover69c2ba52016-07-29 17:58:00 +0000396 unsigned Succ = 0;
397 if (!BrInst.isUnconditional()) {
398 // We want a G_BRCOND to the true BB followed by an unconditional branch.
399 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
400 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000401 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
Tim Northover0f140c72016-09-09 11:46:34 +0000402 MIRBuilder.buildBrCond(Tst, TrueBB);
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000403 }
Tim Northover69c2ba52016-07-29 17:58:00 +0000404
405 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000406 MachineBasicBlock &TgtBB = getMBB(BrTgt);
Ahmed Bougachae8e1fa32017-03-21 23:42:50 +0000407 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
408
409 // If the unconditional target is the layout successor, fallthrough.
410 if (!CurBB.isLayoutSuccessor(&TgtBB))
411 MIRBuilder.buildBr(TgtBB);
Tim Northover69c2ba52016-07-29 17:58:00 +0000412
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000413 // Link successors.
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000414 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000415 CurBB.addSuccessor(&getMBB(*Succ));
Quentin Colombetdd4b1372016-03-11 17:28:03 +0000416 return true;
417}
418
Kristof Beylseced0712017-01-05 11:28:51 +0000419bool IRTranslator::translateSwitch(const User &U,
420 MachineIRBuilder &MIRBuilder) {
421 // For now, just translate as a chain of conditional branches.
422 // FIXME: could we share most of the logic/code in
423 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
424 // At first sight, it seems most of the logic in there is independent of
425 // SelectionDAG-specifics and a lot of work went in to optimize switch
426 // lowering in there.
427
428 const SwitchInst &SwInst = cast<SwitchInst>(U);
429 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
Tim Northoverb6636fd2017-01-17 22:13:50 +0000430 const BasicBlock *OrigBB = SwInst.getParent();
Kristof Beylseced0712017-01-05 11:28:51 +0000431
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000432 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
Kristof Beylseced0712017-01-05 11:28:51 +0000433 for (auto &CaseIt : SwInst.cases()) {
434 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
435 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
436 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000437 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
438 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000439 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000440
Tim Northoverb6636fd2017-01-17 22:13:50 +0000441 MIRBuilder.buildBrCond(Tst, TrueMBB);
442 CurMBB.addSuccessor(&TrueMBB);
443 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000444
Tim Northoverb6636fd2017-01-17 22:13:50 +0000445 MachineBasicBlock *FalseMBB =
Kristof Beylseced0712017-01-05 11:28:51 +0000446 MF->CreateMachineBasicBlock(SwInst.getParent());
Ahmed Bougacha07f247b2017-03-15 18:22:37 +0000447 // Insert the comparison blocks one after the other.
448 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000449 MIRBuilder.buildBr(*FalseMBB);
450 CurMBB.addSuccessor(FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000451
Tim Northoverb6636fd2017-01-17 22:13:50 +0000452 MIRBuilder.setMBB(*FalseMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000453 }
454 // handle default case
Tim Northoverb6636fd2017-01-17 22:13:50 +0000455 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000456 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
Tim Northoverb6636fd2017-01-17 22:13:50 +0000457 MIRBuilder.buildBr(DefaultMBB);
458 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
459 CurMBB.addSuccessor(&DefaultMBB);
460 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
Kristof Beylseced0712017-01-05 11:28:51 +0000461
462 return true;
463}
464
Kristof Beyls65a12c02017-01-30 09:13:18 +0000465bool IRTranslator::translateIndirectBr(const User &U,
466 MachineIRBuilder &MIRBuilder) {
467 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
468
469 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
470 MIRBuilder.buildBrIndirect(Tgt);
471
472 // Link successors.
473 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
Chandler Carruth96fc1de2018-08-26 08:41:15 +0000474 for (const BasicBlock *Succ : successors(&BrInst))
Ahmed Bougachaa61c2142017-03-15 18:22:33 +0000475 CurBB.addSuccessor(&getMBB(*Succ));
Kristof Beyls65a12c02017-01-30 09:13:18 +0000476
477 return true;
478}
479
Tim Northoverc53606e2016-12-07 21:29:15 +0000480bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000481 const LoadInst &LI = cast<LoadInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +0000482
Tim Northover7152dca2016-10-19 15:55:06 +0000483 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
484 : MachineMemOperand::MONone;
485 Flags |= MachineMemOperand::MOLoad;
Tim Northoverad2b7172016-07-26 20:23:26 +0000486
Amara Emersond78d65c2017-11-30 20:06:02 +0000487 if (DL->getTypeStoreSize(LI.getType()) == 0)
488 return true;
489
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000490 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
491 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
492 unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000493
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000494 for (unsigned i = 0; i < Regs.size(); ++i) {
495 unsigned Addr = 0;
496 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
497
498 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
499 unsigned BaseAlign = getMemOpAlignment(LI);
500 auto MMO = MF->getMachineMemOperand(
501 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
502 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
503 LI.getSyncScopeID(), LI.getOrdering());
504 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
505 }
506
Tim Northoverad2b7172016-07-26 20:23:26 +0000507 return true;
508}
509
Tim Northoverc53606e2016-12-07 21:29:15 +0000510bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000511 const StoreInst &SI = cast<StoreInst>(U);
Tim Northover7152dca2016-10-19 15:55:06 +0000512 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
513 : MachineMemOperand::MONone;
514 Flags |= MachineMemOperand::MOStore;
Tim Northoverad2b7172016-07-26 20:23:26 +0000515
Amara Emersond78d65c2017-11-30 20:06:02 +0000516 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
517 return true;
518
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000519 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
520 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
521 unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
Tim Northoverad2b7172016-07-26 20:23:26 +0000522
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000523 for (unsigned i = 0; i < Vals.size(); ++i) {
524 unsigned Addr = 0;
525 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
526
527 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
528 unsigned BaseAlign = getMemOpAlignment(SI);
529 auto MMO = MF->getMachineMemOperand(
530 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
531 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
532 SI.getSyncScopeID(), SI.getOrdering());
533 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
534 }
Tim Northoverad2b7172016-07-26 20:23:26 +0000535 return true;
536}
537
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000538static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
Tim Northoverb6046222016-08-19 20:09:03 +0000539 const Value *Src = U.getOperand(0);
540 Type *Int32Ty = Type::getInt32Ty(U.getContext());
Volkan Keles6a36c642017-05-19 09:47:02 +0000541
Tim Northover6f80b082016-08-19 17:47:05 +0000542 // getIndexedOffsetInType is designed for GEPs, so the first index is the
543 // usual array element rather than looking into the actual aggregate.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000544 SmallVector<Value *, 1> Indices;
Tim Northover6f80b082016-08-19 17:47:05 +0000545 Indices.push_back(ConstantInt::get(Int32Ty, 0));
Tim Northoverb6046222016-08-19 20:09:03 +0000546
547 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
548 for (auto Idx : EVI->indices())
549 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000550 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
551 for (auto Idx : IVI->indices())
552 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
Tim Northoverb6046222016-08-19 20:09:03 +0000553 } else {
554 for (unsigned i = 1; i < U.getNumOperands(); ++i)
555 Indices.push_back(U.getOperand(i));
556 }
Tim Northover6f80b082016-08-19 17:47:05 +0000557
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000558 return 8 * static_cast<uint64_t>(
559 DL.getIndexedOffsetInType(Src->getType(), Indices));
560}
Tim Northover6f80b082016-08-19 17:47:05 +0000561
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000562bool IRTranslator::translateExtractValue(const User &U,
563 MachineIRBuilder &MIRBuilder) {
564 const Value *Src = U.getOperand(0);
565 uint64_t Offset = getOffsetFromIndices(U, *DL);
566 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
567 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
568 unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
569 Offsets.begin();
570 auto &DstRegs = allocateVRegs(U);
571
572 for (unsigned i = 0; i < DstRegs.size(); ++i)
573 DstRegs[i] = SrcRegs[Idx++];
Tim Northover6f80b082016-08-19 17:47:05 +0000574
575 return true;
576}
577
Tim Northoverc53606e2016-12-07 21:29:15 +0000578bool IRTranslator::translateInsertValue(const User &U,
579 MachineIRBuilder &MIRBuilder) {
Tim Northoverb6046222016-08-19 20:09:03 +0000580 const Value *Src = U.getOperand(0);
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000581 uint64_t Offset = getOffsetFromIndices(U, *DL);
582 auto &DstRegs = allocateVRegs(U);
583 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
584 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
585 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
586 auto InsertedIt = InsertedRegs.begin();
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000587
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000588 for (unsigned i = 0; i < DstRegs.size(); ++i) {
589 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
590 DstRegs[i] = *InsertedIt++;
591 else
592 DstRegs[i] = SrcRegs[i];
Tim Northoverb6046222016-08-19 20:09:03 +0000593 }
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000594
Tim Northoverbbbfb1c2016-08-19 20:08:55 +0000595 return true;
596}
597
Tim Northoverc53606e2016-12-07 21:29:15 +0000598bool IRTranslator::translateSelect(const User &U,
599 MachineIRBuilder &MIRBuilder) {
Kristof Beyls7a713502017-04-19 06:38:37 +0000600 unsigned Tst = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000601 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
602 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
603 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
604
Michael Bergc6a52452018-12-18 17:54:52 +0000605 const SelectInst &SI = cast<SelectInst>(U);
Michael Bergf0d81a32019-02-06 19:57:06 +0000606 uint16_t Flags = 0;
607 if (const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
608 Flags = MachineInstr::copyFlagsFromInstruction(*Cmp);
609
Michael Bergc6a52452018-12-18 17:54:52 +0000610 for (unsigned i = 0; i < ResRegs.size(); ++i) {
Michael Bergf0d81a32019-02-06 19:57:06 +0000611 MIRBuilder.buildInstr(TargetOpcode::G_SELECT, {ResRegs[i]},
612 {Tst, Op0Regs[i], Op1Regs[i]}, Flags);
Michael Bergc6a52452018-12-18 17:54:52 +0000613 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000614
Tim Northover5a28c362016-08-19 20:09:07 +0000615 return true;
616}
617
Tim Northoverc53606e2016-12-07 21:29:15 +0000618bool IRTranslator::translateBitCast(const User &U,
619 MachineIRBuilder &MIRBuilder) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000620 // If we're bitcasting to the source type, we can reuse the source vreg.
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000621 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
622 getLLTForType(*U.getType(), *DL)) {
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000623 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000624 auto &Regs = *VMap.getVRegs(U);
Ahmed Bougacha5c7924f2017-03-07 20:53:06 +0000625 // If we already assigned a vreg for this bitcast, we can't change that.
626 // Emit a copy to satisfy the users we already emitted.
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000627 if (!Regs.empty())
628 MIRBuilder.buildCopy(Regs[0], SrcReg);
629 else {
630 Regs.push_back(SrcReg);
631 VMap.getOffsets(U)->push_back(0);
632 }
Tim Northover7c9eba92016-07-25 21:01:29 +0000633 return true;
634 }
Tim Northoverc53606e2016-12-07 21:29:15 +0000635 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
Tim Northover7c9eba92016-07-25 21:01:29 +0000636}
637
Tim Northoverc53606e2016-12-07 21:29:15 +0000638bool IRTranslator::translateCast(unsigned Opcode, const User &U,
639 MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +0000640 unsigned Op = getOrCreateVReg(*U.getOperand(0));
641 unsigned Res = getOrCreateVReg(U);
Tim Northover0f140c72016-09-09 11:46:34 +0000642 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
Tim Northover7c9eba92016-07-25 21:01:29 +0000643 return true;
644}
645
Tim Northoverc53606e2016-12-07 21:29:15 +0000646bool IRTranslator::translateGetElementPtr(const User &U,
647 MachineIRBuilder &MIRBuilder) {
Tim Northovera7653b32016-09-12 11:20:22 +0000648 // FIXME: support vector GEPs.
649 if (U.getType()->isVectorTy())
650 return false;
651
652 Value &Op0 = *U.getOperand(0);
653 unsigned BaseReg = getOrCreateVReg(Op0);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000654 Type *PtrIRTy = Op0.getType();
655 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
656 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
657 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
Tim Northovera7653b32016-09-12 11:20:22 +0000658
659 int64_t Offset = 0;
660 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
661 GTI != E; ++GTI) {
662 const Value *Idx = GTI.getOperand();
Peter Collingbourne25a40752016-12-02 02:55:30 +0000663 if (StructType *StTy = GTI.getStructTypeOrNull()) {
Tim Northovera7653b32016-09-12 11:20:22 +0000664 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
665 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
666 continue;
667 } else {
668 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
669
670 // If this is a scalar constant or a splat vector of constants,
671 // handle it quickly.
672 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
673 Offset += ElementSize * CI->getSExtValue();
674 continue;
675 }
676
677 if (Offset != 0) {
678 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000679 unsigned OffsetReg =
680 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000681 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
682
683 BaseReg = NewBaseReg;
684 Offset = 0;
685 }
686
Tim Northovera7653b32016-09-12 11:20:22 +0000687 unsigned IdxReg = getOrCreateVReg(*Idx);
688 if (MRI->getType(IdxReg) != OffsetTy) {
689 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
690 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
691 IdxReg = NewIdxReg;
692 }
693
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000694 // N = N + Idx * ElementSize;
695 // Avoid doing it for ElementSize of 1.
696 unsigned GepOffsetReg;
697 if (ElementSize != 1) {
698 unsigned ElementSizeReg =
699 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
700
701 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
702 MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
703 } else
704 GepOffsetReg = IdxReg;
Tim Northovera7653b32016-09-12 11:20:22 +0000705
706 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
Aditya Nandakumar5710c442018-01-05 02:56:28 +0000707 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
Tim Northovera7653b32016-09-12 11:20:22 +0000708 BaseReg = NewBaseReg;
709 }
710 }
711
712 if (Offset != 0) {
Ahmed Bougacha2fb80302017-03-15 19:21:11 +0000713 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
Tim Northovera7653b32016-09-12 11:20:22 +0000714 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
715 return true;
716 }
717
718 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
719 return true;
720}
721
Tim Northover79f43f12017-01-30 19:33:07 +0000722bool IRTranslator::translateMemfunc(const CallInst &CI,
723 MachineIRBuilder &MIRBuilder,
724 unsigned ID) {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000725 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
Tim Northover79f43f12017-01-30 19:33:07 +0000726 Type *DstTy = CI.getArgOperand(0)->getType();
727 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
Tim Northover3f186032016-10-18 20:03:45 +0000728 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
729 return false;
730
731 SmallVector<CallLowering::ArgInfo, 8> Args;
732 for (int i = 0; i < 3; ++i) {
733 const auto &Arg = CI.getArgOperand(i);
734 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
735 }
736
Tim Northover79f43f12017-01-30 19:33:07 +0000737 const char *Callee;
738 switch (ID) {
739 case Intrinsic::memmove:
740 case Intrinsic::memcpy: {
741 Type *SrcTy = CI.getArgOperand(1)->getType();
742 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
743 return false;
744 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
745 break;
746 }
747 case Intrinsic::memset:
748 Callee = "memset";
749 break;
750 default:
751 return false;
752 }
Tim Northover3f186032016-10-18 20:03:45 +0000753
Diana Picusd79253a2017-03-20 14:40:18 +0000754 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
755 MachineOperand::CreateES(Callee),
Tim Northover3f186032016-10-18 20:03:45 +0000756 CallLowering::ArgInfo(0, CI.getType()), Args);
757}
Tim Northovera7653b32016-09-12 11:20:22 +0000758
Tim Northoverc53606e2016-12-07 21:29:15 +0000759void IRTranslator::getStackGuard(unsigned DstReg,
760 MachineIRBuilder &MIRBuilder) {
Tim Northoverd8b85582017-01-27 21:31:24 +0000761 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
762 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
Tim Northovercdf23f12016-10-31 18:30:59 +0000763 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
764 MIB.addDef(DstReg);
765
Tim Northover50db7f412016-12-07 21:17:47 +0000766 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +0000767 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
Tim Northovercdf23f12016-10-31 18:30:59 +0000768 if (!Global)
769 return;
770
771 MachinePointerInfo MPInfo(Global);
Tim Northovercdf23f12016-10-31 18:30:59 +0000772 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
773 MachineMemOperand::MODereferenceable;
Chandler Carruthc73c0302018-08-16 21:30:05 +0000774 MachineMemOperand *MemRef =
Tim Northover50db7f412016-12-07 21:17:47 +0000775 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
Fangrui Songe73534462017-11-15 06:17:32 +0000776 DL->getPointerABIAlignment(0));
Chandler Carruthc73c0302018-08-16 21:30:05 +0000777 MIB.setMemRefs({MemRef});
Tim Northovercdf23f12016-10-31 18:30:59 +0000778}
779
Tim Northover1e656ec2016-12-08 22:44:00 +0000780bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
781 MachineIRBuilder &MIRBuilder) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +0000782 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000783 MIRBuilder.buildInstr(Op)
784 .addDef(ResRegs[0])
785 .addDef(ResRegs[1])
786 .addUse(getOrCreateVReg(*CI.getOperand(0)))
787 .addUse(getOrCreateVReg(*CI.getOperand(1)));
Tim Northover1e656ec2016-12-08 22:44:00 +0000788
Tim Northover1e656ec2016-12-08 22:44:00 +0000789 return true;
790}
791
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000792unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000793 switch (ID) {
794 default:
795 break;
Jessica Paquette0e71e732019-02-12 17:28:17 +0000796 case Intrinsic::bswap:
797 return TargetOpcode::G_BSWAP;
Jessica Paquettee288c522019-02-06 17:25:54 +0000798 case Intrinsic::ceil:
799 return TargetOpcode::G_FCEIL;
800 case Intrinsic::cos:
801 return TargetOpcode::G_FCOS;
802 case Intrinsic::ctpop:
803 return TargetOpcode::G_CTPOP;
804 case Intrinsic::exp:
805 return TargetOpcode::G_FEXP;
806 case Intrinsic::exp2:
807 return TargetOpcode::G_FEXP2;
808 case Intrinsic::fabs:
809 return TargetOpcode::G_FABS;
Matt Arsenault9dba67f2019-02-11 17:05:20 +0000810 case Intrinsic::canonicalize:
811 return TargetOpcode::G_FCANONICALIZE;
Jessica Paquettef472f312019-02-11 17:16:32 +0000812 case Intrinsic::floor:
813 return TargetOpcode::G_FFLOOR;
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000814 case Intrinsic::fma:
815 return TargetOpcode::G_FMA;
Jessica Paquettee288c522019-02-06 17:25:54 +0000816 case Intrinsic::log:
817 return TargetOpcode::G_FLOG;
818 case Intrinsic::log2:
819 return TargetOpcode::G_FLOG2;
820 case Intrinsic::log10:
821 return TargetOpcode::G_FLOG10;
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000822 case Intrinsic::pow:
823 return TargetOpcode::G_FPOW;
Jessica Paquettee288c522019-02-06 17:25:54 +0000824 case Intrinsic::round:
825 return TargetOpcode::G_INTRINSIC_ROUND;
826 case Intrinsic::sin:
827 return TargetOpcode::G_FSIN;
828 case Intrinsic::sqrt:
829 return TargetOpcode::G_FSQRT;
830 case Intrinsic::trunc:
831 return TargetOpcode::G_INTRINSIC_TRUNC;
832 }
833 return Intrinsic::not_intrinsic;
834}
835
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000836bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
837 Intrinsic::ID ID,
838 MachineIRBuilder &MIRBuilder) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000839
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000840 unsigned Op = getSimpleIntrinsicOpcode(ID);
Jessica Paquettee288c522019-02-06 17:25:54 +0000841
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000842 // Is this a simple intrinsic?
Jessica Paquettee288c522019-02-06 17:25:54 +0000843 if (Op == Intrinsic::not_intrinsic)
844 return false;
845
846 // Yes. Let's translate it.
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000847 SmallVector<llvm::SrcOp, 4> VRegs;
848 for (auto &Arg : CI.arg_operands())
849 VRegs.push_back(getOrCreateVReg(*Arg));
850
851 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
Michael Bergf0d81a32019-02-06 19:57:06 +0000852 MachineInstr::copyFlagsFromInstruction(CI));
Jessica Paquettee288c522019-02-06 17:25:54 +0000853 return true;
854}
855
Tim Northoverc53606e2016-12-07 21:29:15 +0000856bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
857 MachineIRBuilder &MIRBuilder) {
Jessica Paquettee288c522019-02-06 17:25:54 +0000858
Jessica Paquetteacbb7ca2019-02-12 17:38:34 +0000859 // If this is a simple intrinsic (that is, we just need to add a def of
860 // a vreg, and uses for each arg operand, then translate it.
861 if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
Jessica Paquettee288c522019-02-06 17:25:54 +0000862 return true;
863
Tim Northover91c81732016-08-19 17:17:06 +0000864 switch (ID) {
Tim Northover1e656ec2016-12-08 22:44:00 +0000865 default:
866 break;
Tim Northover0e011702017-02-10 19:10:38 +0000867 case Intrinsic::lifetime_start:
Jessica Paquette2e35dc52019-01-28 19:22:29 +0000868 case Intrinsic::lifetime_end: {
869 // No stack colouring in O0, discard region information.
870 if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
871 return true;
872
873 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
874 : TargetOpcode::LIFETIME_END;
875
876 // Get the underlying objects for the location passed on the lifetime
877 // marker.
878 SmallVector<Value *, 4> Allocas;
879 GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
880
881 // Iterate over each underlying object, creating lifetime markers for each
882 // static alloca. Quit if we find a non-static alloca.
883 for (Value *V : Allocas) {
884 AllocaInst *AI = dyn_cast<AllocaInst>(V);
885 if (!AI)
886 continue;
887
888 if (!AI->isStaticAlloca())
889 return true;
890
891 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
892 }
Tim Northover0e011702017-02-10 19:10:38 +0000893 return true;
Jessica Paquette2e35dc52019-01-28 19:22:29 +0000894 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000895 case Intrinsic::dbg_declare: {
896 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
897 assert(DI.getVariable() && "Missing variable");
898
899 const Value *Address = DI.getAddress();
900 if (!Address || isa<UndefValue>(Address)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000901 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Tim Northover09aac4a2017-01-26 23:39:14 +0000902 return true;
903 }
904
Tim Northover09aac4a2017-01-26 23:39:14 +0000905 assert(DI.getVariable()->isValidLocationForIntrinsic(
906 MIRBuilder.getDebugLoc()) &&
907 "Expected inlined-at fields to agree");
Tim Northover7a9ea8f2017-03-09 21:12:06 +0000908 auto AI = dyn_cast<AllocaInst>(Address);
909 if (AI && AI->isStaticAlloca()) {
910 // Static allocas are tracked at the MF level, no need for DBG_VALUE
911 // instructions (in fact, they get ignored if they *do* exist).
912 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
913 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
Josh Stonef446fac2018-09-11 17:52:01 +0000914 } else {
915 // A dbg.declare describes the address of a source variable, so lower it
916 // into an indirect DBG_VALUE.
917 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
918 DI.getVariable(), DI.getExpression());
919 }
Tim Northoverb58346f2016-12-08 22:44:13 +0000920 return true;
Tim Northover09aac4a2017-01-26 23:39:14 +0000921 }
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000922 case Intrinsic::dbg_label: {
923 const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
924 assert(DI.getLabel() && "Missing label");
925
926 assert(DI.getLabel()->isValidLocationForIntrinsic(
927 MIRBuilder.getDebugLoc()) &&
928 "Expected inlined-at fields to agree");
929
930 MIRBuilder.buildDbgLabel(DI.getLabel());
931 return true;
932 }
Tim Northoverd0d025a2017-02-07 20:08:59 +0000933 case Intrinsic::vaend:
934 // No target I know of cares about va_end. Certainly no in-tree target
935 // does. Simplest intrinsic ever!
936 return true;
Tim Northoverf19d4672017-02-08 17:57:20 +0000937 case Intrinsic::vastart: {
938 auto &TLI = *MF->getSubtarget().getTargetLowering();
939 Value *Ptr = CI.getArgOperand(0);
940 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
941
Matt Arsenault2a645982019-01-31 01:38:47 +0000942 // FIXME: Get alignment
Tim Northoverf19d4672017-02-08 17:57:20 +0000943 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
944 .addUse(getOrCreateVReg(*Ptr))
945 .addMemOperand(MF->getMachineMemOperand(
Matt Arsenault2a645982019-01-31 01:38:47 +0000946 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
Tim Northoverf19d4672017-02-08 17:57:20 +0000947 return true;
948 }
Tim Northover09aac4a2017-01-26 23:39:14 +0000949 case Intrinsic::dbg_value: {
950 // This form of DBG_VALUE is target-independent.
951 const DbgValueInst &DI = cast<DbgValueInst>(CI);
952 const Value *V = DI.getValue();
953 assert(DI.getVariable()->isValidLocationForIntrinsic(
954 MIRBuilder.getDebugLoc()) &&
955 "Expected inlined-at fields to agree");
956 if (!V) {
957 // Currently the optimizer can produce this; insert an undef to
958 // help debugging. Probably the optimizer should not do this.
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000959 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000960 } else if (const auto *CI = dyn_cast<Constant>(V)) {
Adrian Prantld92ac5a2017-07-28 22:46:20 +0000961 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000962 } else {
963 unsigned Reg = getOrCreateVReg(*V);
964 // FIXME: This does not handle register-indirect values at offset 0. The
965 // direct/indirect thing shouldn't really be handled by something as
966 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
967 // pretty baked in right now.
Adrian Prantlabe04752017-07-28 20:21:02 +0000968 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
Tim Northover09aac4a2017-01-26 23:39:14 +0000969 }
970 return true;
971 }
Tim Northover1e656ec2016-12-08 22:44:00 +0000972 case Intrinsic::uadd_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000973 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +0000974 case Intrinsic::sadd_with_overflow:
975 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
976 case Intrinsic::usub_with_overflow:
Aditya Nandakumar6b4d3432018-08-28 18:54:10 +0000977 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
Tim Northover1e656ec2016-12-08 22:44:00 +0000978 case Intrinsic::ssub_with_overflow:
979 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
980 case Intrinsic::umul_with_overflow:
981 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
982 case Intrinsic::smul_with_overflow:
983 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
Volkan Keles92837632018-02-13 00:47:46 +0000984 case Intrinsic::fmuladd: {
985 const TargetMachine &TM = MF->getTarget();
986 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
987 unsigned Dst = getOrCreateVReg(CI);
988 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
989 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
990 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
991 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
992 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
993 // TODO: Revisit this to see if we should move this part of the
994 // lowering to the combiner.
Michael Bergf0d81a32019-02-06 19:57:06 +0000995 MIRBuilder.buildInstr(TargetOpcode::G_FMA, {Dst}, {Op0, Op1, Op2},
996 MachineInstr::copyFlagsFromInstruction(CI));
Volkan Keles92837632018-02-13 00:47:46 +0000997 } else {
998 LLT Ty = getLLTForType(*CI.getType(), *DL);
Michael Bergf0d81a32019-02-06 19:57:06 +0000999 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, {Ty}, {Op0, Op1},
1000 MachineInstr::copyFlagsFromInstruction(CI));
1001 MIRBuilder.buildInstr(TargetOpcode::G_FADD, {Dst}, {FMul, Op2},
1002 MachineInstr::copyFlagsFromInstruction(CI));
Volkan Keles92837632018-02-13 00:47:46 +00001003 }
1004 return true;
1005 }
Tim Northover3f186032016-10-18 20:03:45 +00001006 case Intrinsic::memcpy:
Tim Northover79f43f12017-01-30 19:33:07 +00001007 case Intrinsic::memmove:
1008 case Intrinsic::memset:
1009 return translateMemfunc(CI, MIRBuilder, ID);
Tim Northovera9105be2016-11-09 22:39:54 +00001010 case Intrinsic::eh_typeid_for: {
1011 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
1012 unsigned Reg = getOrCreateVReg(CI);
Tim Northover50db7f412016-12-07 21:17:47 +00001013 unsigned TypeID = MF->getTypeIDFor(GV);
Tim Northovera9105be2016-11-09 22:39:54 +00001014 MIRBuilder.buildConstant(Reg, TypeID);
1015 return true;
1016 }
Tim Northover6e904302016-10-18 20:03:51 +00001017 case Intrinsic::objectsize: {
1018 // If we don't know by now, we're never going to know.
1019 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
1020
1021 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
1022 return true;
1023 }
James Y Knight72f76bf2018-11-07 15:24:12 +00001024 case Intrinsic::is_constant:
1025 // If this wasn't constant-folded away by now, then it's not a
1026 // constant.
1027 MIRBuilder.buildConstant(getOrCreateVReg(CI), 0);
1028 return true;
Tim Northovercdf23f12016-10-31 18:30:59 +00001029 case Intrinsic::stackguard:
Tim Northoverc53606e2016-12-07 21:29:15 +00001030 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +00001031 return true;
1032 case Intrinsic::stackprotector: {
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001033 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
Tim Northovercdf23f12016-10-31 18:30:59 +00001034 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
Tim Northoverc53606e2016-12-07 21:29:15 +00001035 getStackGuard(GuardVal, MIRBuilder);
Tim Northovercdf23f12016-10-31 18:30:59 +00001036
1037 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
Petr Pavlu84e89ff2018-12-10 15:15:05 +00001038 int FI = getOrCreateFrameIndex(*Slot);
1039 MF->getFrameInfo().setStackProtectorIndex(FI);
1040
Tim Northovercdf23f12016-10-31 18:30:59 +00001041 MIRBuilder.buildStore(
1042 GuardVal, getOrCreateVReg(*Slot),
Petr Pavlu84e89ff2018-12-10 15:15:05 +00001043 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1044 MachineMemOperand::MOStore |
1045 MachineMemOperand::MOVolatile,
1046 PtrTy.getSizeInBits() / 8, 8));
Tim Northovercdf23f12016-10-31 18:30:59 +00001047 return true;
1048 }
Aditya Nandakumare07b3b72018-08-04 01:22:12 +00001049 case Intrinsic::cttz:
1050 case Intrinsic::ctlz: {
1051 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1052 bool isTrailing = ID == Intrinsic::cttz;
1053 unsigned Opcode = isTrailing
1054 ? Cst->isZero() ? TargetOpcode::G_CTTZ
1055 : TargetOpcode::G_CTTZ_ZERO_UNDEF
1056 : Cst->isZero() ? TargetOpcode::G_CTLZ
1057 : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1058 MIRBuilder.buildInstr(Opcode)
1059 .addDef(getOrCreateVReg(CI))
1060 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
1061 return true;
1062 }
Jessica Paquetteb328d952018-10-05 21:02:46 +00001063 case Intrinsic::invariant_start: {
1064 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1065 unsigned Undef = MRI->createGenericVirtualRegister(PtrTy);
1066 MIRBuilder.buildUndef(Undef);
1067 return true;
1068 }
1069 case Intrinsic::invariant_end:
1070 return true;
Tim Northover91c81732016-08-19 17:17:06 +00001071 }
Tim Northover1e656ec2016-12-08 22:44:00 +00001072 return false;
Tim Northover91c81732016-08-19 17:17:06 +00001073}
1074
Tim Northoveraa995c92017-03-09 23:36:26 +00001075bool IRTranslator::translateInlineAsm(const CallInst &CI,
1076 MachineIRBuilder &MIRBuilder) {
1077 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1078 if (!IA.getConstraintString().empty())
1079 return false;
1080
1081 unsigned ExtraInfo = 0;
1082 if (IA.hasSideEffects())
1083 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1084 if (IA.getDialect() == InlineAsm::AD_Intel)
1085 ExtraInfo |= InlineAsm::Extra_AsmDialect;
1086
1087 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1088 .addExternalSymbol(IA.getAsmString().c_str())
1089 .addImm(ExtraInfo);
1090
1091 return true;
1092}
1093
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001094unsigned IRTranslator::packRegs(const Value &V,
1095 MachineIRBuilder &MIRBuilder) {
1096 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1097 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1098 LLT BigTy = getLLTForType(*V.getType(), *DL);
1099
1100 if (Regs.size() == 1)
1101 return Regs[0];
1102
1103 unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
1104 MIRBuilder.buildUndef(Dst);
1105 for (unsigned i = 0; i < Regs.size(); ++i) {
1106 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
1107 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
1108 Dst = NewDst;
1109 }
1110 return Dst;
1111}
1112
1113void IRTranslator::unpackRegs(const Value &V, unsigned Src,
1114 MachineIRBuilder &MIRBuilder) {
1115 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
1116 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
1117
1118 for (unsigned i = 0; i < Regs.size(); ++i)
1119 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
1120}
1121
Tim Northoverc53606e2016-12-07 21:29:15 +00001122bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001123 const CallInst &CI = cast<CallInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001124 auto TII = MF->getTarget().getIntrinsicInfo();
Tim Northover406024a2016-08-10 21:44:01 +00001125 const Function *F = CI.getCalledFunction();
Tim Northover5fb414d2016-07-29 22:32:36 +00001126
Martin Storsjocc981d22018-01-30 19:50:58 +00001127 // FIXME: support Windows dllimport function calls.
1128 if (F && F->hasDLLImportStorageClass())
1129 return false;
1130
Tim Northover3babfef2017-01-19 23:59:35 +00001131 if (CI.isInlineAsm())
Tim Northoveraa995c92017-03-09 23:36:26 +00001132 return translateInlineAsm(CI, MIRBuilder);
Tim Northover3babfef2017-01-19 23:59:35 +00001133
Amara Emerson913918c2018-01-02 18:56:39 +00001134 Intrinsic::ID ID = Intrinsic::not_intrinsic;
1135 if (F && F->isIntrinsic()) {
1136 ID = F->getIntrinsicID();
1137 if (TII && ID == Intrinsic::not_intrinsic)
1138 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1139 }
1140
1141 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
Matt Arsenault13371692019-03-14 14:18:56 +00001142 bool IsSplitType = valueIsSplit(CI);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001143 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
1144 getLLTForType(*CI.getType(), *DL))
1145 : getOrCreateVReg(CI);
1146
Tim Northover406024a2016-08-10 21:44:01 +00001147 SmallVector<unsigned, 8> Args;
1148 for (auto &Arg: CI.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001149 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northover406024a2016-08-10 21:44:01 +00001150
Tim Northoverd1e951e2017-03-09 22:00:39 +00001151 MF->getFrameInfo().setHasCalls(true);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001152 bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
Tim Northoverfe5f89b2016-08-29 19:07:08 +00001153 return getOrCreateVReg(*CI.getCalledValue());
1154 });
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001155
1156 if (IsSplitType)
1157 unpackRegs(CI, Res, MIRBuilder);
1158 return Success;
Tim Northover406024a2016-08-10 21:44:01 +00001159 }
1160
Tim Northover406024a2016-08-10 21:44:01 +00001161 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
Tim Northover5fb414d2016-07-29 22:32:36 +00001162
Tim Northoverc53606e2016-12-07 21:29:15 +00001163 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
Tim Northover91c81732016-08-19 17:17:06 +00001164 return true;
1165
Matt Arsenault13371692019-03-14 14:18:56 +00001166 ArrayRef<unsigned> ResultRegs;
1167 if (!CI.getType()->isVoidTy())
1168 ResultRegs = getOrCreateVRegs(CI);
1169
Tim Northover5fb414d2016-07-29 22:32:36 +00001170 MachineInstrBuilder MIB =
Matt Arsenault13371692019-03-14 14:18:56 +00001171 MIRBuilder.buildIntrinsic(ID, ResultRegs, !CI.doesNotAccessMemory());
Tim Northover5fb414d2016-07-29 22:32:36 +00001172
1173 for (auto &Arg : CI.arg_operands()) {
Ahmed Bougacha55d10422017-03-07 20:53:09 +00001174 // Some intrinsics take metadata parameters. Reject them.
1175 if (isa<MetadataAsValue>(Arg))
1176 return false;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001177 MIB.addUse(packRegs(*Arg, MIRBuilder));
Tim Northover5fb414d2016-07-29 22:32:36 +00001178 }
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001179
1180 // Add a MachineMemOperand if it is a target mem intrinsic.
1181 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1182 TargetLowering::IntrinsicInfo Info;
1183 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
Matt Arsenault7d7adf42017-12-14 22:34:10 +00001184 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
Matt Arsenault50d65792019-01-31 23:41:23 +00001185 unsigned Align = Info.align;
1186 if (Align == 0)
1187 Align = DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext()));
Matt Arsenault2a645982019-01-31 01:38:47 +00001188
Matt Arsenault50d65792019-01-31 23:41:23 +00001189 uint64_t Size = Info.memVT.getStoreSize();
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001190 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
Matt Arsenault50d65792019-01-31 23:41:23 +00001191 Info.flags, Size, Align));
Volkan Kelesebe6bb92017-06-05 22:17:17 +00001192 }
1193
Tim Northover5fb414d2016-07-29 22:32:36 +00001194 return true;
1195}
1196
Tim Northoverc53606e2016-12-07 21:29:15 +00001197bool IRTranslator::translateInvoke(const User &U,
1198 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001199 const InvokeInst &I = cast<InvokeInst>(U);
Tim Northover50db7f412016-12-07 21:17:47 +00001200 MCContext &Context = MF->getContext();
Tim Northovera9105be2016-11-09 22:39:54 +00001201
1202 const BasicBlock *ReturnBB = I.getSuccessor(0);
1203 const BasicBlock *EHPadBB = I.getSuccessor(1);
1204
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001205 const Value *Callee = I.getCalledValue();
Tim Northovera9105be2016-11-09 22:39:54 +00001206 const Function *Fn = dyn_cast<Function>(Callee);
1207 if (isa<InlineAsm>(Callee))
1208 return false;
1209
1210 // FIXME: support invoking patchpoint and statepoint intrinsics.
1211 if (Fn && Fn->isIntrinsic())
1212 return false;
1213
1214 // FIXME: support whatever these are.
1215 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1216 return false;
1217
1218 // FIXME: support Windows exception handling.
1219 if (!isa<LandingPadInst>(EHPadBB->front()))
1220 return false;
1221
Matthias Braund0ee66c2016-12-01 19:32:15 +00001222 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
Tim Northovera9105be2016-11-09 22:39:54 +00001223 // the region covered by the try.
Matthias Braund0ee66c2016-12-01 19:32:15 +00001224 MCSymbol *BeginSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001225 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1226
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001227 unsigned Res =
1228 MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
Tim Northover293f7432017-01-31 18:36:11 +00001229 SmallVector<unsigned, 8> Args;
Tim Northovera9105be2016-11-09 22:39:54 +00001230 for (auto &Arg: I.arg_operands())
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001231 Args.push_back(packRegs(*Arg, MIRBuilder));
Tim Northovera9105be2016-11-09 22:39:54 +00001232
Ahmed Bougachad22b84b2017-03-10 00:25:44 +00001233 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
Ahmed Bougacha4ec6d5a2017-03-10 00:25:35 +00001234 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1235 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001236
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001237 unpackRegs(I, Res, MIRBuilder);
1238
Matthias Braund0ee66c2016-12-01 19:32:15 +00001239 MCSymbol *EndSymbol = Context.createTempSymbol();
Tim Northovera9105be2016-11-09 22:39:54 +00001240 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1241
1242 // FIXME: track probabilities.
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001243 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1244 &ReturnMBB = getMBB(*ReturnBB);
Tim Northover50db7f412016-12-07 21:17:47 +00001245 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
Tim Northovera9105be2016-11-09 22:39:54 +00001246 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1247 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
Tim Northoverc6bfa482017-01-31 20:12:18 +00001248 MIRBuilder.buildBr(ReturnMBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001249
1250 return true;
1251}
1252
Craig Topper784929d2019-02-08 20:48:56 +00001253bool IRTranslator::translateCallBr(const User &U,
1254 MachineIRBuilder &MIRBuilder) {
1255 // FIXME: Implement this.
1256 return false;
1257}
1258
Tim Northoverc53606e2016-12-07 21:29:15 +00001259bool IRTranslator::translateLandingPad(const User &U,
1260 MachineIRBuilder &MIRBuilder) {
Tim Northovera9105be2016-11-09 22:39:54 +00001261 const LandingPadInst &LP = cast<LandingPadInst>(U);
1262
1263 MachineBasicBlock &MBB = MIRBuilder.getMBB();
Tim Northovera9105be2016-11-09 22:39:54 +00001264
1265 MBB.setIsEHPad();
1266
1267 // If there aren't registers to copy the values into (e.g., during SjLj
1268 // exceptions), then don't bother.
Tim Northover50db7f412016-12-07 21:17:47 +00001269 auto &TLI = *MF->getSubtarget().getTargetLowering();
Matthias Braunf1caa282017-12-15 22:22:58 +00001270 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
Tim Northovera9105be2016-11-09 22:39:54 +00001271 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1272 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1273 return true;
1274
1275 // If landingpad's return type is token type, we don't create DAG nodes
1276 // for its exception pointer and selector value. The extraction of exception
1277 // pointer or selector value from token type landingpads is not currently
1278 // supported.
1279 if (LP.getType()->isTokenTy())
1280 return true;
1281
1282 // Add a label to mark the beginning of the landing pad. Deletion of the
1283 // landing pad can thus be detected via the MachineModuleInfo.
1284 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
Tim Northover50db7f412016-12-07 21:17:47 +00001285 .addSym(MF->addLandingPad(&MBB));
Tim Northovera9105be2016-11-09 22:39:54 +00001286
Daniel Sanders1351db42017-03-07 23:32:10 +00001287 LLT Ty = getLLTForType(*LP.getType(), *DL);
Tim Northover542d1c12017-03-07 23:04:06 +00001288 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1289 MIRBuilder.buildUndef(Undef);
1290
Justin Bognera0295312017-01-25 00:16:53 +00001291 SmallVector<LLT, 2> Tys;
1292 for (Type *Ty : cast<StructType>(LP.getType())->elements())
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001293 Tys.push_back(getLLTForType(*Ty, *DL));
Justin Bognera0295312017-01-25 00:16:53 +00001294 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1295
Tim Northovera9105be2016-11-09 22:39:54 +00001296 // Mark exception register as live in.
Tim Northover542d1c12017-03-07 23:04:06 +00001297 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1298 if (!ExceptionReg)
1299 return false;
Tim Northovera9105be2016-11-09 22:39:54 +00001300
Tim Northover542d1c12017-03-07 23:04:06 +00001301 MBB.addLiveIn(ExceptionReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001302 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1303 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
Tim Northoverc9449702017-01-30 20:52:42 +00001304
Tim Northover542d1c12017-03-07 23:04:06 +00001305 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1306 if (!SelectorReg)
1307 return false;
Tim Northoverc9449702017-01-30 20:52:42 +00001308
Tim Northover542d1c12017-03-07 23:04:06 +00001309 MBB.addLiveIn(SelectorReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001310 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1311 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001312 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
Tim Northover542d1c12017-03-07 23:04:06 +00001313
Tim Northovera9105be2016-11-09 22:39:54 +00001314 return true;
1315}
1316
Tim Northoverc3e3f592017-02-03 18:22:45 +00001317bool IRTranslator::translateAlloca(const User &U,
1318 MachineIRBuilder &MIRBuilder) {
1319 auto &AI = cast<AllocaInst>(U);
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001320
Amara Emersonfdd089a2018-07-26 01:25:58 +00001321 if (AI.isSwiftError())
1322 return false;
1323
Tim Northoverc3e3f592017-02-03 18:22:45 +00001324 if (AI.isStaticAlloca()) {
1325 unsigned Res = getOrCreateVReg(AI);
1326 int FI = getOrCreateFrameIndex(AI);
1327 MIRBuilder.buildFrameIndex(Res, FI);
1328 return true;
1329 }
1330
Martin Storsjoa63a5b92018-02-17 14:26:32 +00001331 // FIXME: support stack probing for Windows.
1332 if (MF->getTarget().getTargetTriple().isOSWindows())
1333 return false;
1334
Tim Northoverc3e3f592017-02-03 18:22:45 +00001335 // Now we're in the harder dynamic case.
1336 Type *Ty = AI.getAllocatedType();
1337 unsigned Align =
1338 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1339
1340 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1341
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001342 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1343 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001344 if (MRI->getType(NumElts) != IntPtrTy) {
1345 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1346 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1347 NumElts = ExtElts;
1348 }
1349
1350 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
Ahmed Bougacha2fb80302017-03-15 19:21:11 +00001351 unsigned TySize =
1352 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
Tim Northoverc3e3f592017-02-03 18:22:45 +00001353 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1354
Daniel Sanders52b4ce72017-03-07 23:20:35 +00001355 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001356 auto &TLI = *MF->getSubtarget().getTargetLowering();
1357 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1358
1359 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1360 MIRBuilder.buildCopy(SPTmp, SPReg);
1361
Tim Northoverc2f89562017-02-14 20:56:18 +00001362 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1363 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001364
1365 // Handle alignment. We have to realign if the allocation granule was smaller
1366 // than stack alignment, or the specific alloca requires more than stack
1367 // alignment.
1368 unsigned StackAlign =
1369 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1370 Align = std::max(Align, StackAlign);
1371 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1372 // Round the size of the allocation up to the stack alignment size
1373 // by add SA-1 to the size. This doesn't overflow because we're computing
1374 // an address inside an alloca.
Tim Northoverc2f89562017-02-14 20:56:18 +00001375 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1376 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1377 AllocTmp = AlignedAlloc;
Tim Northoverc3e3f592017-02-03 18:22:45 +00001378 }
1379
Tim Northoverc2f89562017-02-14 20:56:18 +00001380 MIRBuilder.buildCopy(SPReg, AllocTmp);
1381 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
Tim Northoverc3e3f592017-02-03 18:22:45 +00001382
1383 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1384 assert(MF->getFrameInfo().hasVarSizedObjects());
Tim Northoverbd505462016-07-22 16:59:52 +00001385 return true;
1386}
1387
Tim Northover4a652222017-02-15 23:22:33 +00001388bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1389 // FIXME: We may need more info about the type. Because of how LLT works,
1390 // we're completely discarding the i64/double distinction here (amongst
1391 // others). Fortunately the ABIs I know of where that matters don't use va_arg
1392 // anyway but that's not guaranteed.
1393 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1394 .addDef(getOrCreateVReg(U))
1395 .addUse(getOrCreateVReg(*U.getOperand(0)))
1396 .addImm(DL->getABITypeAlignment(U.getType()));
1397 return true;
1398}
1399
Volkan Keles04cb08c2017-03-10 19:08:28 +00001400bool IRTranslator::translateInsertElement(const User &U,
1401 MachineIRBuilder &MIRBuilder) {
1402 // If it is a <1 x Ty> vector, use the scalar as it is
1403 // not a legal vector type in LLT.
1404 if (U.getType()->getVectorNumElements() == 1) {
1405 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001406 auto &Regs = *VMap.getVRegs(U);
1407 if (Regs.empty()) {
1408 Regs.push_back(Elt);
1409 VMap.getOffsets(U)->push_back(0);
1410 } else {
1411 MIRBuilder.buildCopy(Regs[0], Elt);
1412 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001413 return true;
1414 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001415
Kristof Beyls7a713502017-04-19 06:38:37 +00001416 unsigned Res = getOrCreateVReg(U);
1417 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1418 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1419 unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1420 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001421 return true;
1422}
1423
1424bool IRTranslator::translateExtractElement(const User &U,
1425 MachineIRBuilder &MIRBuilder) {
1426 // If it is a <1 x Ty> vector, use the scalar as it is
1427 // not a legal vector type in LLT.
1428 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1429 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001430 auto &Regs = *VMap.getVRegs(U);
1431 if (Regs.empty()) {
1432 Regs.push_back(Elt);
1433 VMap.getOffsets(U)->push_back(0);
1434 } else {
1435 MIRBuilder.buildCopy(Regs[0], Elt);
1436 }
Volkan Keles04cb08c2017-03-10 19:08:28 +00001437 return true;
1438 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001439 unsigned Res = getOrCreateVReg(U);
1440 unsigned Val = getOrCreateVReg(*U.getOperand(0));
Amara Emersoncbd86d82018-10-25 14:04:54 +00001441 const auto &TLI = *MF->getSubtarget().getTargetLowering();
1442 unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1443 unsigned Idx = 0;
1444 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1445 if (CI->getBitWidth() != PreferredVecIdxWidth) {
1446 APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1447 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1448 Idx = getOrCreateVReg(*NewIdxCI);
1449 }
1450 }
1451 if (!Idx)
1452 Idx = getOrCreateVReg(*U.getOperand(1));
1453 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1454 const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1455 Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg();
1456 }
Kristof Beyls7a713502017-04-19 06:38:37 +00001457 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
Volkan Keles04cb08c2017-03-10 19:08:28 +00001458 return true;
1459}
1460
Volkan Keles75bdc762017-03-21 08:44:13 +00001461bool IRTranslator::translateShuffleVector(const User &U,
1462 MachineIRBuilder &MIRBuilder) {
1463 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1464 .addDef(getOrCreateVReg(U))
1465 .addUse(getOrCreateVReg(*U.getOperand(0)))
1466 .addUse(getOrCreateVReg(*U.getOperand(1)))
1467 .addUse(getOrCreateVReg(*U.getOperand(2)));
1468 return true;
1469}
1470
Tim Northoverc53606e2016-12-07 21:29:15 +00001471bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
Tim Northover357f1be2016-08-10 23:02:41 +00001472 const PHINode &PI = cast<PHINode>(U);
Tim Northover97d0cb32016-08-05 17:16:40 +00001473
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001474 SmallVector<MachineInstr *, 4> Insts;
1475 for (auto Reg : getOrCreateVRegs(PI)) {
Aditya Nandakumarcef44a22018-12-11 00:48:50 +00001476 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001477 Insts.push_back(MIB.getInstr());
1478 }
1479
1480 PendingPHIs.emplace_back(&PI, std::move(Insts));
Tim Northover97d0cb32016-08-05 17:16:40 +00001481 return true;
1482}
1483
Daniel Sanders94813992018-07-09 19:33:40 +00001484bool IRTranslator::translateAtomicCmpXchg(const User &U,
1485 MachineIRBuilder &MIRBuilder) {
1486 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1487
1488 if (I.isWeak())
1489 return false;
1490
1491 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1492 : MachineMemOperand::MONone;
1493 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1494
1495 Type *ResType = I.getType();
1496 Type *ValType = ResType->Type::getStructElementType(0);
1497
1498 auto Res = getOrCreateVRegs(I);
1499 unsigned OldValRes = Res[0];
1500 unsigned SuccessRes = Res[1];
1501 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1502 unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1503 unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1504
1505 MIRBuilder.buildAtomicCmpXchgWithSuccess(
1506 OldValRes, SuccessRes, Addr, Cmp, NewVal,
1507 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1508 Flags, DL->getTypeStoreSize(ValType),
1509 getMemOpAlignment(I), AAMDNodes(), nullptr,
1510 I.getSyncScopeID(), I.getSuccessOrdering(),
1511 I.getFailureOrdering()));
1512 return true;
1513}
1514
1515bool IRTranslator::translateAtomicRMW(const User &U,
1516 MachineIRBuilder &MIRBuilder) {
1517 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1518
1519 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1520 : MachineMemOperand::MONone;
1521 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1522
1523 Type *ResType = I.getType();
1524
1525 unsigned Res = getOrCreateVReg(I);
1526 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1527 unsigned Val = getOrCreateVReg(*I.getValOperand());
1528
1529 unsigned Opcode = 0;
1530 switch (I.getOperation()) {
1531 default:
1532 llvm_unreachable("Unknown atomicrmw op");
1533 return false;
1534 case AtomicRMWInst::Xchg:
1535 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1536 break;
1537 case AtomicRMWInst::Add:
1538 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1539 break;
1540 case AtomicRMWInst::Sub:
1541 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1542 break;
1543 case AtomicRMWInst::And:
1544 Opcode = TargetOpcode::G_ATOMICRMW_AND;
1545 break;
1546 case AtomicRMWInst::Nand:
1547 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1548 break;
1549 case AtomicRMWInst::Or:
1550 Opcode = TargetOpcode::G_ATOMICRMW_OR;
1551 break;
1552 case AtomicRMWInst::Xor:
1553 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1554 break;
1555 case AtomicRMWInst::Max:
1556 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1557 break;
1558 case AtomicRMWInst::Min:
1559 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1560 break;
1561 case AtomicRMWInst::UMax:
1562 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1563 break;
1564 case AtomicRMWInst::UMin:
1565 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1566 break;
1567 }
1568
1569 MIRBuilder.buildAtomicRMW(
1570 Opcode, Res, Addr, Val,
1571 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1572 Flags, DL->getTypeStoreSize(ResType),
1573 getMemOpAlignment(I), AAMDNodes(), nullptr,
1574 I.getSyncScopeID(), I.getOrdering()));
1575 return true;
1576}
1577
Tim Northover97d0cb32016-08-05 17:16:40 +00001578void IRTranslator::finishPendingPhis() {
Daniel Sanders3b390402018-10-31 17:31:23 +00001579#ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001580 DILocationVerifier Verifier;
1581 GISelObserverWrapper WrapperObserver(&Verifier);
1582 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
Daniel Sanders3b390402018-10-31 17:31:23 +00001583#endif // ifndef NDEBUG
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001584 for (auto &Phi : PendingPHIs) {
Tim Northover97d0cb32016-08-05 17:16:40 +00001585 const PHINode *PI = Phi.first;
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001586 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001587 EntryBuilder->setDebugLoc(PI->getDebugLoc());
Daniel Sanders3b390402018-10-31 17:31:23 +00001588#ifndef NDEBUG
1589 Verifier.setCurrentInst(PI);
1590#endif // ifndef NDEBUG
Tim Northover97d0cb32016-08-05 17:16:40 +00001591
1592 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1593 // won't create extra control flow here, otherwise we need to find the
1594 // dominating predecessor here (or perhaps force the weirder IRTranslators
1595 // to provide a simple boundary).
Tim Northoverb6636fd2017-01-17 22:13:50 +00001596 SmallSet<const BasicBlock *, 4> HandledPreds;
1597
Tim Northover97d0cb32016-08-05 17:16:40 +00001598 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
Tim Northoverb6636fd2017-01-17 22:13:50 +00001599 auto IRPred = PI->getIncomingBlock(i);
1600 if (HandledPreds.count(IRPred))
1601 continue;
1602
1603 HandledPreds.insert(IRPred);
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001604 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
Tim Northoverb6636fd2017-01-17 22:13:50 +00001605 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001606 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
Tim Northoverb6636fd2017-01-17 22:13:50 +00001607 "incorrect CFG at MachineBasicBlock level");
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001608 for (unsigned j = 0; j < ValRegs.size(); ++j) {
1609 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1610 MIB.addUse(ValRegs[j]);
1611 MIB.addMBB(Pred);
1612 }
Tim Northoverb6636fd2017-01-17 22:13:50 +00001613 }
Tim Northover97d0cb32016-08-05 17:16:40 +00001614 }
1615 }
1616}
1617
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001618bool IRTranslator::valueIsSplit(const Value &V,
1619 SmallVectorImpl<uint64_t> *Offsets) {
1620 SmallVector<LLT, 4> SplitTys;
Amara Emerson30e61402018-08-14 12:04:25 +00001621 if (Offsets && !Offsets->empty())
1622 Offsets->clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001623 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1624 return SplitTys.size() > 1;
1625}
1626
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001627bool IRTranslator::translate(const Instruction &Inst) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001628 CurBuilder->setDebugLoc(Inst.getDebugLoc());
1629 EntryBuilder->setDebugLoc(Inst.getDebugLoc());
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001630 switch(Inst.getOpcode()) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001631#define HANDLE_INST(NUM, OPCODE, CLASS) \
1632 case Instruction::OPCODE: \
1633 return translate##OPCODE(Inst, *CurBuilder.get());
Tim Northover357f1be2016-08-10 23:02:41 +00001634#include "llvm/IR/Instruction.def"
Quentin Colombet74d7d2f2016-02-11 18:53:28 +00001635 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001636 return false;
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001637 }
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001638}
1639
Tim Northover5ed648e2016-08-09 21:28:04 +00001640bool IRTranslator::translate(const Constant &C, unsigned Reg) {
Tim Northoverd403a3d2016-08-09 23:01:30 +00001641 if (auto CI = dyn_cast<ConstantInt>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001642 EntryBuilder->buildConstant(Reg, *CI);
Tim Northoverb16734f2016-08-19 20:09:15 +00001643 else if (auto CF = dyn_cast<ConstantFP>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001644 EntryBuilder->buildFConstant(Reg, *CF);
Tim Northoverd403a3d2016-08-09 23:01:30 +00001645 else if (isa<UndefValue>(C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001646 EntryBuilder->buildUndef(Reg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001647 else if (isa<ConstantPointerNull>(C)) {
1648 // As we are trying to build a constant val of 0 into a pointer,
1649 // insert a cast to make them correct with respect to types.
1650 unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1651 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1652 auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1653 unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001654 EntryBuilder->buildCast(Reg, ZeroReg);
Aditya Nandakumarb3297ef2018-03-22 17:31:38 +00001655 } else if (auto GV = dyn_cast<GlobalValue>(&C))
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001656 EntryBuilder->buildGlobalValue(Reg, GV);
Volkan Keles970fee42017-03-10 21:23:13 +00001657 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1658 if (!CAZ->getType()->isVectorTy())
1659 return false;
Volkan Keles4862c632017-03-14 23:45:06 +00001660 // Return the scalar if it is a <1 x Ty> vector.
1661 if (CAZ->getNumElements() == 1)
1662 return translate(*CAZ->getElementValue(0u), Reg);
Amara Emerson5ec14602018-12-10 18:44:58 +00001663 SmallVector<unsigned, 4> Ops;
Volkan Keles970fee42017-03-10 21:23:13 +00001664 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1665 Constant &Elt = *CAZ->getElementValue(i);
1666 Ops.push_back(getOrCreateVReg(Elt));
1667 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001668 EntryBuilder->buildBuildVector(Reg, Ops);
Volkan Keles38a91a02017-03-13 21:36:19 +00001669 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
Volkan Keles4862c632017-03-14 23:45:06 +00001670 // Return the scalar if it is a <1 x Ty> vector.
1671 if (CV->getNumElements() == 1)
1672 return translate(*CV->getElementAsConstant(0), Reg);
Amara Emerson5ec14602018-12-10 18:44:58 +00001673 SmallVector<unsigned, 4> Ops;
Volkan Keles38a91a02017-03-13 21:36:19 +00001674 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1675 Constant &Elt = *CV->getElementAsConstant(i);
1676 Ops.push_back(getOrCreateVReg(Elt));
1677 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001678 EntryBuilder->buildBuildVector(Reg, Ops);
Volkan Keles970fee42017-03-10 21:23:13 +00001679 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
Tim Northover357f1be2016-08-10 23:02:41 +00001680 switch(CE->getOpcode()) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001681#define HANDLE_INST(NUM, OPCODE, CLASS) \
1682 case Instruction::OPCODE: \
1683 return translate##OPCODE(*CE, *EntryBuilder.get());
Tim Northover357f1be2016-08-10 23:02:41 +00001684#include "llvm/IR/Instruction.def"
1685 default:
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001686 return false;
Tim Northover357f1be2016-08-10 23:02:41 +00001687 }
Aditya Nandakumar117b6672017-05-04 21:43:12 +00001688 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1689 if (CV->getNumOperands() == 1)
1690 return translate(*CV->getOperand(0), Reg);
1691 SmallVector<unsigned, 4> Ops;
1692 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1693 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1694 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001695 EntryBuilder->buildBuildVector(Reg, Ops);
Amara Emerson6aff5a72018-07-31 00:08:50 +00001696 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001697 EntryBuilder->buildBlockAddress(Reg, BA);
Quentin Colombetee8a4f52017-03-11 00:28:33 +00001698 } else
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001699 return false;
Tim Northover5ed648e2016-08-09 21:28:04 +00001700
Tim Northoverd403a3d2016-08-09 23:01:30 +00001701 return true;
Tim Northover5ed648e2016-08-09 21:28:04 +00001702}
1703
Tim Northover0d510442016-08-11 16:21:29 +00001704void IRTranslator::finalizeFunction() {
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001705 // Release the memory used by the different maps we
1706 // needed during the translation.
Tim Northover800638f2016-12-05 23:10:19 +00001707 PendingPHIs.clear();
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001708 VMap.reset();
Tim Northovercdf23f12016-10-31 18:30:59 +00001709 FrameIndices.clear();
Tim Northoverb6636fd2017-01-17 22:13:50 +00001710 MachinePreds.clear();
Aditya Nandakumarbe929932017-05-17 17:41:55 +00001711 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1712 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1713 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001714 EntryBuilder.reset();
1715 CurBuilder.reset();
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001716}
1717
Tim Northover50db7f412016-12-07 21:17:47 +00001718bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1719 MF = &CurMF;
Matthias Braunf1caa282017-12-15 22:22:58 +00001720 const Function &F = MF->getFunction();
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001721 if (F.empty())
1722 return false;
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001723 GISelCSEAnalysisWrapper &Wrapper =
1724 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
1725 // Set the CSEConfig and run the analysis.
1726 GISelCSEInfo *CSEInfo = nullptr;
1727 TPC = &getAnalysis<TargetPassConfig>();
Aditya Nandakumar3ba0d942019-01-24 23:11:25 +00001728 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
1729 ? EnableCSEInIRTranslator
1730 : TPC->isGISelCSEEnabled();
1731
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001732 if (EnableCSE) {
1733 EntryBuilder = make_unique<CSEMIRBuilder>(CurMF);
1734 std::unique_ptr<CSEConfig> Config = make_unique<CSEConfig>();
1735 CSEInfo = &Wrapper.get(std::move(Config));
1736 EntryBuilder->setCSEInfo(CSEInfo);
1737 CurBuilder = make_unique<CSEMIRBuilder>(CurMF);
1738 CurBuilder->setCSEInfo(CSEInfo);
1739 } else {
1740 EntryBuilder = make_unique<MachineIRBuilder>();
1741 CurBuilder = make_unique<MachineIRBuilder>();
1742 }
Tim Northover50db7f412016-12-07 21:17:47 +00001743 CLI = MF->getSubtarget().getCallLowering();
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001744 CurBuilder->setMF(*MF);
1745 EntryBuilder->setMF(*MF);
Tim Northover50db7f412016-12-07 21:17:47 +00001746 MRI = &MF->getRegInfo();
Tim Northoverbd505462016-07-22 16:59:52 +00001747 DL = &F.getParent()->getDataLayout();
Eugene Zelenko76bf48d2017-06-26 22:44:03 +00001748 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
Tim Northoverbd505462016-07-22 16:59:52 +00001749
Tim Northover14e7f732016-08-05 17:50:36 +00001750 assert(PendingPHIs.empty() && "stale PHIs");
1751
Amara Emersondf9b5292017-12-11 16:58:29 +00001752 if (!DL->isLittleEndian()) {
1753 // Currently we don't properly handle big endian code.
1754 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001755 F.getSubprogram(), &F.getEntryBlock());
Amara Emersondf9b5292017-12-11 16:58:29 +00001756 R << "unable to translate in big endian mode";
1757 reportTranslationError(*MF, *TPC, *ORE, R);
1758 }
1759
Ahmed Bougachaeceabdd2017-02-23 23:57:28 +00001760 // Release the per-function state when we return, whether we succeeded or not.
1761 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1762
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001763 // Setup a separate basic-block for the arguments and constants
Tim Northover50db7f412016-12-07 21:17:47 +00001764 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1765 MF->push_back(EntryBB);
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001766 EntryBuilder->setMBB(*EntryBB);
Tim Northover05cc4852016-12-07 21:05:38 +00001767
Ahmed Bougachaa61c2142017-03-15 18:22:33 +00001768 // Create all blocks, in IR order, to preserve the layout.
1769 for (const BasicBlock &BB: F) {
1770 auto *&MBB = BBToMBB[&BB];
1771
1772 MBB = MF->CreateMachineBasicBlock(&BB);
1773 MF->push_back(MBB);
1774
1775 if (BB.hasAddressTaken())
1776 MBB->setHasAddressTaken();
1777 }
1778
1779 // Make our arguments/constants entry block fallthrough to the IR entry block.
1780 EntryBB->addSuccessor(&getMBB(F.front()));
1781
Tim Northover05cc4852016-12-07 21:05:38 +00001782 // Lower the actual args into this basic block.
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001783 SmallVector<unsigned, 8> VRegArgs;
Amara Emersond78d65c2017-11-30 20:06:02 +00001784 for (const Argument &Arg: F.args()) {
1785 if (DL->getTypeStoreSize(Arg.getType()) == 0)
1786 continue; // Don't handle zero sized types.
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001787 VRegArgs.push_back(
1788 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
Amara Emersond78d65c2017-11-30 20:06:02 +00001789 }
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001790
Amara Emersonfdd089a2018-07-26 01:25:58 +00001791 // We don't currently support translating swifterror or swiftself functions.
1792 for (auto &Arg : F.args()) {
1793 if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1794 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1795 F.getSubprogram(), &F.getEntryBlock());
1796 R << "unable to lower arguments due to swifterror/swiftself: "
1797 << ore::NV("Prototype", F.getType());
1798 reportTranslationError(*MF, *TPC, *ORE, R);
1799 return false;
1800 }
1801 }
1802
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001803 if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
Ahmed Bougacha7c88a4e2017-02-24 00:34:44 +00001804 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
Matthias Braunf1caa282017-12-15 22:22:58 +00001805 F.getSubprogram(), &F.getEntryBlock());
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001806 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1807 reportTranslationError(*MF, *TPC, *ORE, R);
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001808 return false;
Quentin Colombet3bb32cc2016-08-26 23:49:05 +00001809 }
Quentin Colombetfd9d0a02016-02-11 19:59:41 +00001810
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001811 auto ArgIt = F.arg_begin();
1812 for (auto &VArg : VRegArgs) {
1813 // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1814 // creating redundant copies.
1815 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1816 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1817 assert(VRegs.empty() && "VRegs already populated?");
1818 VRegs.push_back(VArg);
1819 } else {
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001820 unpackRegs(*ArgIt, VArg, *EntryBuilder.get());
Amara Emerson0d6a26d2018-05-16 10:32:02 +00001821 }
1822 ArgIt++;
1823 }
1824
Amara Emerson6cdfe292018-08-01 02:17:42 +00001825 // Need to visit defs before uses when translating instructions.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001826 GISelObserverWrapper WrapperObserver;
1827 if (EnableCSE && CSEInfo)
1828 WrapperObserver.addObserver(CSEInfo);
Daniel Sanders3b390402018-10-31 17:31:23 +00001829 {
1830 ReversePostOrderTraversal<const Function *> RPOT(&F);
1831#ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001832 DILocationVerifier Verifier;
1833 WrapperObserver.addObserver(&Verifier);
Daniel Sanders3b390402018-10-31 17:31:23 +00001834#endif // ifndef NDEBUG
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001835 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
Daniel Sanders3b390402018-10-31 17:31:23 +00001836 for (const BasicBlock *BB : RPOT) {
1837 MachineBasicBlock &MBB = getMBB(*BB);
1838 // Set the insertion point of all the following translations to
1839 // the end of this basic block.
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001840 CurBuilder->setMBB(MBB);
Tim Northovera9105be2016-11-09 22:39:54 +00001841
Daniel Sanders3b390402018-10-31 17:31:23 +00001842 for (const Instruction &Inst : *BB) {
1843#ifndef NDEBUG
1844 Verifier.setCurrentInst(&Inst);
1845#endif // ifndef NDEBUG
1846 if (translate(Inst))
1847 continue;
Ahmed Bougachaae9dade2017-02-23 21:05:42 +00001848
Daniel Sanders3b390402018-10-31 17:31:23 +00001849 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1850 Inst.getDebugLoc(), BB);
1851 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
Ahmed Bougachad630a922017-09-18 18:50:09 +00001852
Daniel Sanders3b390402018-10-31 17:31:23 +00001853 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1854 std::string InstStrStorage;
1855 raw_string_ostream InstStr(InstStrStorage);
1856 InstStr << Inst;
Ahmed Bougachad630a922017-09-18 18:50:09 +00001857
Daniel Sanders3b390402018-10-31 17:31:23 +00001858 R << ": '" << InstStr.str() << "'";
1859 }
1860
1861 reportTranslationError(*MF, *TPC, *ORE, R);
1862 return false;
Ahmed Bougachad630a922017-09-18 18:50:09 +00001863 }
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001864 }
Aditya Nandakumar500e3ea2019-01-16 00:40:37 +00001865#ifndef NDEBUG
1866 WrapperObserver.removeObserver(&Verifier);
1867#endif
Quentin Colombet2ecff3b2016-02-10 22:59:27 +00001868 }
Tim Northover72eebfa2016-07-12 22:23:42 +00001869
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001870 finishPendingPhis();
Tim Northover97d0cb32016-08-05 17:16:40 +00001871
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001872 // Merge the argument lowering and constants block with its single
1873 // successor, the LLVM-IR entry block. We want the basic block to
1874 // be maximal.
1875 assert(EntryBB->succ_size() == 1 &&
1876 "Custom BB used for lowering should have only one successor");
1877 // Get the successor of the current entry block.
1878 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1879 assert(NewEntryBB.pred_size() == 1 &&
1880 "LLVM-IR entry block has a predecessor!?");
1881 // Move all the instruction from the current entry block to the
1882 // new entry block.
1883 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1884 EntryBB->end());
Quentin Colombet327f9422016-12-15 23:32:25 +00001885
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001886 // Update the live-in information for the new entry block.
1887 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1888 NewEntryBB.addLiveIn(LiveIn);
1889 NewEntryBB.sortUniqueLiveIns();
Quentin Colombet327f9422016-12-15 23:32:25 +00001890
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001891 // Get rid of the now empty basic block.
1892 EntryBB->removeSuccessor(&NewEntryBB);
1893 MF->remove(EntryBB);
1894 MF->DeleteMachineBasicBlock(EntryBB);
Quentin Colombet327f9422016-12-15 23:32:25 +00001895
Ahmed Bougacha4f8dd022017-02-23 23:57:36 +00001896 assert(&MF->front() == &NewEntryBB &&
1897 "New entry wasn't next in the list of basic block!");
Tim Northover800638f2016-12-05 23:10:19 +00001898
Matthias Braun90ad6832018-07-13 00:08:38 +00001899 // Initialize stack protector information.
1900 StackProtector &SP = getAnalysis<StackProtector>();
1901 SP.copyToMachineFrameInfo(MF->getFrameInfo());
1902
Quentin Colombet105cf2b2016-01-20 20:58:56 +00001903 return false;
1904}