1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements the IRTranslator class.
11 //===----------------------------------------------------------------------===//
12
13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
14 #include "llvm/ADT/PostOrderIterator.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
20 #include "llvm/CodeGen/Analysis.h"
21 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
22 #include "llvm/CodeGen/LowLevelType.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/StackProtector.h"
31 #include "llvm/CodeGen/TargetFrameLowering.h"
32 #include "llvm/CodeGen/TargetLowering.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/CodeGen/TargetRegisterInfo.h"
35 #include "llvm/CodeGen/TargetSubtargetInfo.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/CFG.h"
38 #include "llvm/IR/Constant.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugInfo.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GetElementPtrTypeIterator.h"
45 #include "llvm/IR/InlineAsm.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/User.h"
54 #include "llvm/IR/Value.h"
55 #include "llvm/MC/MCContext.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/CodeGen.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/LowLevelTypeImpl.h"
62 #include "llvm/Support/MathExtras.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Target/TargetIntrinsicInfo.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstdint>
69 #include <iterator>
70 #include <string>
71 #include <utility>
72 #include <vector>
73
74 #define DEBUG_TYPE "irtranslator"
75
76 using namespace llvm;
77
78 char IRTranslator::ID = 0;
79
80 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
81 false, false)
INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)82 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
83 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
84 false, false)
85
86 static void reportTranslationError(MachineFunction &MF,
87 const TargetPassConfig &TPC,
88 OptimizationRemarkEmitter &ORE,
89 OptimizationRemarkMissed &R) {
90 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
91
92 // Print the function name explicitly if we don't have a debug location (which
93 // makes the diagnostic less useful) or if we're going to emit a raw error.
94 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
95 R << (" (in function: " + MF.getName() + ")").str();
96
97 if (TPC.isGlobalISelAbortEnabled())
98 report_fatal_error(R.getMsg());
99 else
100 ORE.emit(R);
101 }
102
IRTranslator()103 IRTranslator::IRTranslator() : MachineFunctionPass(ID) {
104 initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
105 }
106
getAnalysisUsage(AnalysisUsage & AU) const107 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
108 AU.addRequired<StackProtector>();
109 AU.addRequired<TargetPassConfig>();
110 getSelectionDAGFallbackAnalysisUsage(AU);
111 MachineFunctionPass::getAnalysisUsage(AU);
112 }
113
computeValueLLTs(const DataLayout & DL,Type & Ty,SmallVectorImpl<LLT> & ValueTys,SmallVectorImpl<uint64_t> * Offsets=nullptr,uint64_t StartingOffset=0)114 static void computeValueLLTs(const DataLayout &DL, Type &Ty,
115 SmallVectorImpl<LLT> &ValueTys,
116 SmallVectorImpl<uint64_t> *Offsets = nullptr,
117 uint64_t StartingOffset = 0) {
118 // Given a struct type, recursively traverse the elements.
119 if (StructType *STy = dyn_cast<StructType>(&Ty)) {
120 const StructLayout *SL = DL.getStructLayout(STy);
121 for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
122 computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
123 StartingOffset + SL->getElementOffset(I));
124 return;
125 }
126 // Given an array type, recursively traverse the elements.
127 if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
128 Type *EltTy = ATy->getElementType();
129 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
130 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
131 computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
132 StartingOffset + i * EltSize);
133 return;
134 }
135 // Interpret void as zero return values.
136 if (Ty.isVoidTy())
137 return;
138 // Base case: we can get an LLT for this LLVM IR type.
139 ValueTys.push_back(getLLTForType(Ty, DL));
140 if (Offsets != nullptr)
141 Offsets->push_back(StartingOffset * 8);
142 }
143
144 IRTranslator::ValueToVRegInfo::VRegListT &
allocateVRegs(const Value & Val)145 IRTranslator::allocateVRegs(const Value &Val) {
146 assert(!VMap.contains(Val) && "Value already allocated in VMap");
147 auto *Regs = VMap.getVRegs(Val);
148 auto *Offsets = VMap.getOffsets(Val);
149 SmallVector<LLT, 4> SplitTys;
150 computeValueLLTs(*DL, *Val.getType(), SplitTys,
151 Offsets->empty() ? Offsets : nullptr);
152 for (unsigned i = 0; i < SplitTys.size(); ++i)
153 Regs->push_back(0);
154 return *Regs;
155 }
156
getOrCreateVRegs(const Value & Val)157 ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
158 auto VRegsIt = VMap.findVRegs(Val);
159 if (VRegsIt != VMap.vregs_end())
160 return *VRegsIt->second;
161
162 if (Val.getType()->isVoidTy())
163 return *VMap.getVRegs(Val);
164
165 // Create entry for this type.
166 auto *VRegs = VMap.getVRegs(Val);
167 auto *Offsets = VMap.getOffsets(Val);
168
169 assert(Val.getType()->isSized() &&
170 "Don't know how to create an empty vreg");
171
172 SmallVector<LLT, 4> SplitTys;
173 computeValueLLTs(*DL, *Val.getType(), SplitTys,
174 Offsets->empty() ? Offsets : nullptr);
175
176 if (!isa<Constant>(Val)) {
177 for (auto Ty : SplitTys)
178 VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
179 return *VRegs;
180 }
181
182 if (Val.getType()->isAggregateType()) {
183 // UndefValue, ConstantAggregateZero
184 auto &C = cast<Constant>(Val);
185 unsigned Idx = 0;
186 while (auto Elt = C.getAggregateElement(Idx++)) {
187 auto EltRegs = getOrCreateVRegs(*Elt);
188 std::copy(EltRegs.begin(), EltRegs.end(), std::back_inserter(*VRegs));
189 }
190 } else {
191 assert(SplitTys.size() == 1 && "unexpectedly split LLT");
192 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
193 bool Success = translate(cast<Constant>(Val), VRegs->front());
194 if (!Success) {
195 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
196 MF->getFunction().getSubprogram(),
197 &MF->getFunction().getEntryBlock());
198 R << "unable to translate constant: " << ore::NV("Type", Val.getType());
199 reportTranslationError(*MF, *TPC, *ORE, R);
200 return *VRegs;
201 }
202 }
203
204 return *VRegs;
205 }
206
getOrCreateFrameIndex(const AllocaInst & AI)207 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
208 if (FrameIndices.find(&AI) != FrameIndices.end())
209 return FrameIndices[&AI];
210
211 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
212 unsigned Size =
213 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
214
215 // Always allocate at least one byte.
216 Size = std::max(Size, 1u);
217
218 unsigned Alignment = AI.getAlignment();
219 if (!Alignment)
220 Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
221
222 int &FI = FrameIndices[&AI];
223 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
224 return FI;
225 }
226
getMemOpAlignment(const Instruction & I)227 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
228 unsigned Alignment = 0;
229 Type *ValTy = nullptr;
230 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
231 Alignment = SI->getAlignment();
232 ValTy = SI->getValueOperand()->getType();
233 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
234 Alignment = LI->getAlignment();
235 ValTy = LI->getType();
236 } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
237 // TODO(PR27168): This instruction has no alignment attribute, but unlike
238 // the default alignment for load/store, the default here is to assume
239 // it has NATURAL alignment, not DataLayout-specified alignment.
240 const DataLayout &DL = AI->getModule()->getDataLayout();
241 Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
242 ValTy = AI->getCompareOperand()->getType();
243 } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
244 // TODO(PR27168): This instruction has no alignment attribute, but unlike
245 // the default alignment for load/store, the default here is to assume
246 // it has NATURAL alignment, not DataLayout-specified alignment.
247 const DataLayout &DL = AI->getModule()->getDataLayout();
248 Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
249 ValTy = AI->getType();
250 } else {
251 OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
252 R << "unable to translate memop: " << ore::NV("Opcode", &I);
253 reportTranslationError(*MF, *TPC, *ORE, R);
254 return 1;
255 }
256
257 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
258 }
259
getMBB(const BasicBlock & BB)260 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
261 MachineBasicBlock *&MBB = BBToMBB[&BB];
262 assert(MBB && "BasicBlock was not encountered before");
263 return *MBB;
264 }
265
addMachineCFGPred(CFGEdge Edge,MachineBasicBlock * NewPred)266 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
267 assert(NewPred && "new predecessor must be a real MachineBasicBlock");
268 MachinePreds[Edge].push_back(NewPred);
269 }
270
translateBinaryOp(unsigned Opcode,const User & U,MachineIRBuilder & MIRBuilder)271 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
272 MachineIRBuilder &MIRBuilder) {
273 // FIXME: handle signed/unsigned wrapping flags.
274
275 // Get or create a virtual register for each value.
276 // Unless the value is a Constant => loadimm cst?
277 // or inline constant each time?
278 // Creation of a virtual register needs to have a size.
279 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
280 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
281 unsigned Res = getOrCreateVReg(U);
282 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
283 return true;
284 }
285
translateFSub(const User & U,MachineIRBuilder & MIRBuilder)286 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
287 // -0.0 - X --> G_FNEG
288 if (isa<Constant>(U.getOperand(0)) &&
289 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
290 MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
291 .addDef(getOrCreateVReg(U))
292 .addUse(getOrCreateVReg(*U.getOperand(1)));
293 return true;
294 }
295 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
296 }
297
translateCompare(const User & U,MachineIRBuilder & MIRBuilder)298 bool IRTranslator::translateCompare(const User &U,
299 MachineIRBuilder &MIRBuilder) {
300 const CmpInst *CI = dyn_cast<CmpInst>(&U);
301 unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
302 unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
303 unsigned Res = getOrCreateVReg(U);
304 CmpInst::Predicate Pred =
305 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
306 cast<ConstantExpr>(U).getPredicate());
307 if (CmpInst::isIntPredicate(Pred))
308 MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
309 else if (Pred == CmpInst::FCMP_FALSE)
310 MIRBuilder.buildCopy(
311 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
312 else if (Pred == CmpInst::FCMP_TRUE)
313 MIRBuilder.buildCopy(
314 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
315 else
316 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
317
318 return true;
319 }
320
translateRet(const User & U,MachineIRBuilder & MIRBuilder)321 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
322 const ReturnInst &RI = cast<ReturnInst>(U);
323 const Value *Ret = RI.getReturnValue();
324 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
325 Ret = nullptr;
326 // The target may mess up with the insertion point, but
327 // this is not important as a return is the last instruction
328 // of the block anyway.
329
330 // FIXME: this interface should simplify when CallLowering gets adapted to
331 // multiple VRegs per Value.
332 unsigned VReg = Ret ? packRegs(*Ret, MIRBuilder) : 0;
333 return CLI->lowerReturn(MIRBuilder, Ret, VReg);
334 }
335
translateBr(const User & U,MachineIRBuilder & MIRBuilder)336 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
337 const BranchInst &BrInst = cast<BranchInst>(U);
338 unsigned Succ = 0;
339 if (!BrInst.isUnconditional()) {
340 // We want a G_BRCOND to the true BB followed by an unconditional branch.
341 unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
342 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
343 MachineBasicBlock &TrueBB = getMBB(TrueTgt);
344 MIRBuilder.buildBrCond(Tst, TrueBB);
345 }
346
347 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
348 MachineBasicBlock &TgtBB = getMBB(BrTgt);
349 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
350
351 // If the unconditional target is the layout successor, fallthrough.
352 if (!CurBB.isLayoutSuccessor(&TgtBB))
353 MIRBuilder.buildBr(TgtBB);
354
355 // Link successors.
356 for (const BasicBlock *Succ : BrInst.successors())
357 CurBB.addSuccessor(&getMBB(*Succ));
358 return true;
359 }
360
translateSwitch(const User & U,MachineIRBuilder & MIRBuilder)361 bool IRTranslator::translateSwitch(const User &U,
362 MachineIRBuilder &MIRBuilder) {
363 // For now, just translate as a chain of conditional branches.
364 // FIXME: could we share most of the logic/code in
365 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
366 // At first sight, it seems most of the logic in there is independent of
367 // SelectionDAG-specifics and a lot of work went in to optimize switch
368 // lowering in there.
369
370 const SwitchInst &SwInst = cast<SwitchInst>(U);
371 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
372 const BasicBlock *OrigBB = SwInst.getParent();
373
374 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
375 for (auto &CaseIt : SwInst.cases()) {
376 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
377 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
378 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
379 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
380 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
381 MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
382
383 MIRBuilder.buildBrCond(Tst, TrueMBB);
384 CurMBB.addSuccessor(&TrueMBB);
385 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
386
387 MachineBasicBlock *FalseMBB =
388 MF->CreateMachineBasicBlock(SwInst.getParent());
389 // Insert the comparison blocks one after the other.
390 MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
391 MIRBuilder.buildBr(*FalseMBB);
392 CurMBB.addSuccessor(FalseMBB);
393
394 MIRBuilder.setMBB(*FalseMBB);
395 }
396 // handle default case
397 const BasicBlock *DefaultBB = SwInst.getDefaultDest();
398 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
399 MIRBuilder.buildBr(DefaultMBB);
400 MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
401 CurMBB.addSuccessor(&DefaultMBB);
402 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
403
404 return true;
405 }
406
translateIndirectBr(const User & U,MachineIRBuilder & MIRBuilder)407 bool IRTranslator::translateIndirectBr(const User &U,
408 MachineIRBuilder &MIRBuilder) {
409 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
410
411 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
412 MIRBuilder.buildBrIndirect(Tgt);
413
414 // Link successors.
415 MachineBasicBlock &CurBB = MIRBuilder.getMBB();
416 for (const BasicBlock *Succ : BrInst.successors())
417 CurBB.addSuccessor(&getMBB(*Succ));
418
419 return true;
420 }
421
translateLoad(const User & U,MachineIRBuilder & MIRBuilder)422 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
423 const LoadInst &LI = cast<LoadInst>(U);
424
425 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
426 : MachineMemOperand::MONone;
427 Flags |= MachineMemOperand::MOLoad;
428
429 if (DL->getTypeStoreSize(LI.getType()) == 0)
430 return true;
431
432 ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
433 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
434 unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
435
436 for (unsigned i = 0; i < Regs.size(); ++i) {
437 unsigned Addr = 0;
438 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
439
440 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
441 unsigned BaseAlign = getMemOpAlignment(LI);
442 auto MMO = MF->getMachineMemOperand(
443 Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
444 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
445 LI.getSyncScopeID(), LI.getOrdering());
446 MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
447 }
448
449 return true;
450 }
451
translateStore(const User & U,MachineIRBuilder & MIRBuilder)452 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
453 const StoreInst &SI = cast<StoreInst>(U);
454 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
455 : MachineMemOperand::MONone;
456 Flags |= MachineMemOperand::MOStore;
457
458 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
459 return true;
460
461 ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
462 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
463 unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
464
465 for (unsigned i = 0; i < Vals.size(); ++i) {
466 unsigned Addr = 0;
467 MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
468
469 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
470 unsigned BaseAlign = getMemOpAlignment(SI);
471 auto MMO = MF->getMachineMemOperand(
472 Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
473 MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
474 SI.getSyncScopeID(), SI.getOrdering());
475 MIRBuilder.buildStore(Vals[i], Addr, *MMO);
476 }
477 return true;
478 }
479
getOffsetFromIndices(const User & U,const DataLayout & DL)480 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
481 const Value *Src = U.getOperand(0);
482 Type *Int32Ty = Type::getInt32Ty(U.getContext());
483
484 // getIndexedOffsetInType is designed for GEPs, so the first index is the
485 // usual array element rather than looking into the actual aggregate.
486 SmallVector<Value *, 1> Indices;
487 Indices.push_back(ConstantInt::get(Int32Ty, 0));
488
489 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
490 for (auto Idx : EVI->indices())
491 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
492 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
493 for (auto Idx : IVI->indices())
494 Indices.push_back(ConstantInt::get(Int32Ty, Idx));
495 } else {
496 for (unsigned i = 1; i < U.getNumOperands(); ++i)
497 Indices.push_back(U.getOperand(i));
498 }
499
500 return 8 * static_cast<uint64_t>(
501 DL.getIndexedOffsetInType(Src->getType(), Indices));
502 }
503
translateExtractValue(const User & U,MachineIRBuilder & MIRBuilder)504 bool IRTranslator::translateExtractValue(const User &U,
505 MachineIRBuilder &MIRBuilder) {
506 const Value *Src = U.getOperand(0);
507 uint64_t Offset = getOffsetFromIndices(U, *DL);
508 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
509 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
510 unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
511 Offsets.begin();
512 auto &DstRegs = allocateVRegs(U);
513
514 for (unsigned i = 0; i < DstRegs.size(); ++i)
515 DstRegs[i] = SrcRegs[Idx++];
516
517 return true;
518 }
519
translateInsertValue(const User & U,MachineIRBuilder & MIRBuilder)520 bool IRTranslator::translateInsertValue(const User &U,
521 MachineIRBuilder &MIRBuilder) {
522 const Value *Src = U.getOperand(0);
523 uint64_t Offset = getOffsetFromIndices(U, *DL);
524 auto &DstRegs = allocateVRegs(U);
525 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
526 ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
527 ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
528 auto InsertedIt = InsertedRegs.begin();
529
530 for (unsigned i = 0; i < DstRegs.size(); ++i) {
531 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
532 DstRegs[i] = *InsertedIt++;
533 else
534 DstRegs[i] = SrcRegs[i];
535 }
536
537 return true;
538 }
539
translateSelect(const User & U,MachineIRBuilder & MIRBuilder)540 bool IRTranslator::translateSelect(const User &U,
541 MachineIRBuilder &MIRBuilder) {
542 unsigned Tst = getOrCreateVReg(*U.getOperand(0));
543 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
544 ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
545 ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
546
547 for (unsigned i = 0; i < ResRegs.size(); ++i)
548 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i]);
549
550 return true;
551 }
552
translateBitCast(const User & U,MachineIRBuilder & MIRBuilder)553 bool IRTranslator::translateBitCast(const User &U,
554 MachineIRBuilder &MIRBuilder) {
555 // If we're bitcasting to the source type, we can reuse the source vreg.
556 if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
557 getLLTForType(*U.getType(), *DL)) {
558 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
559 auto &Regs = *VMap.getVRegs(U);
560 // If we already assigned a vreg for this bitcast, we can't change that.
561 // Emit a copy to satisfy the users we already emitted.
562 if (!Regs.empty())
563 MIRBuilder.buildCopy(Regs[0], SrcReg);
564 else {
565 Regs.push_back(SrcReg);
566 VMap.getOffsets(U)->push_back(0);
567 }
568 return true;
569 }
570 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
571 }
572
translateCast(unsigned Opcode,const User & U,MachineIRBuilder & MIRBuilder)573 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
574 MachineIRBuilder &MIRBuilder) {
575 unsigned Op = getOrCreateVReg(*U.getOperand(0));
576 unsigned Res = getOrCreateVReg(U);
577 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
578 return true;
579 }
580
translateGetElementPtr(const User & U,MachineIRBuilder & MIRBuilder)581 bool IRTranslator::translateGetElementPtr(const User &U,
582 MachineIRBuilder &MIRBuilder) {
583 // FIXME: support vector GEPs.
584 if (U.getType()->isVectorTy())
585 return false;
586
587 Value &Op0 = *U.getOperand(0);
588 unsigned BaseReg = getOrCreateVReg(Op0);
589 Type *PtrIRTy = Op0.getType();
590 LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
591 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
592 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
593
594 int64_t Offset = 0;
595 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
596 GTI != E; ++GTI) {
597 const Value *Idx = GTI.getOperand();
598 if (StructType *StTy = GTI.getStructTypeOrNull()) {
599 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
600 Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
601 continue;
602 } else {
603 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
604
605 // If this is a scalar constant or a splat vector of constants,
606 // handle it quickly.
607 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
608 Offset += ElementSize * CI->getSExtValue();
609 continue;
610 }
611
612 if (Offset != 0) {
613 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
614 unsigned OffsetReg =
615 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
616 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
617
618 BaseReg = NewBaseReg;
619 Offset = 0;
620 }
621
622 unsigned IdxReg = getOrCreateVReg(*Idx);
623 if (MRI->getType(IdxReg) != OffsetTy) {
624 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
625 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
626 IdxReg = NewIdxReg;
627 }
628
629 // N = N + Idx * ElementSize;
630 // Avoid doing it for ElementSize of 1.
631 unsigned GepOffsetReg;
632 if (ElementSize != 1) {
633 unsigned ElementSizeReg =
634 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
635
636 GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
637 MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
638 } else
639 GepOffsetReg = IdxReg;
640
641 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
642 MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
643 BaseReg = NewBaseReg;
644 }
645 }
646
647 if (Offset != 0) {
648 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
649 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
650 return true;
651 }
652
653 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
654 return true;
655 }
656
translateMemfunc(const CallInst & CI,MachineIRBuilder & MIRBuilder,unsigned ID)657 bool IRTranslator::translateMemfunc(const CallInst &CI,
658 MachineIRBuilder &MIRBuilder,
659 unsigned ID) {
660 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
661 Type *DstTy = CI.getArgOperand(0)->getType();
662 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
663 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
664 return false;
665
666 SmallVector<CallLowering::ArgInfo, 8> Args;
667 for (int i = 0; i < 3; ++i) {
668 const auto &Arg = CI.getArgOperand(i);
669 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
670 }
671
672 const char *Callee;
673 switch (ID) {
674 case Intrinsic::memmove:
675 case Intrinsic::memcpy: {
676 Type *SrcTy = CI.getArgOperand(1)->getType();
677 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
678 return false;
679 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
680 break;
681 }
682 case Intrinsic::memset:
683 Callee = "memset";
684 break;
685 default:
686 return false;
687 }
688
689 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
690 MachineOperand::CreateES(Callee),
691 CallLowering::ArgInfo(0, CI.getType()), Args);
692 }
693
getStackGuard(unsigned DstReg,MachineIRBuilder & MIRBuilder)694 void IRTranslator::getStackGuard(unsigned DstReg,
695 MachineIRBuilder &MIRBuilder) {
696 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
697 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
698 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
699 MIB.addDef(DstReg);
700
701 auto &TLI = *MF->getSubtarget().getTargetLowering();
702 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
703 if (!Global)
704 return;
705
706 MachinePointerInfo MPInfo(Global);
707 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
708 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
709 MachineMemOperand::MODereferenceable;
710 *MemRefs =
711 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
712 DL->getPointerABIAlignment(0));
713 MIB.setMemRefs(MemRefs, MemRefs + 1);
714 }
715
translateOverflowIntrinsic(const CallInst & CI,unsigned Op,MachineIRBuilder & MIRBuilder)716 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
717 MachineIRBuilder &MIRBuilder) {
718 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
719 auto MIB = MIRBuilder.buildInstr(Op)
720 .addDef(ResRegs[0])
721 .addDef(ResRegs[1])
722 .addUse(getOrCreateVReg(*CI.getOperand(0)))
723 .addUse(getOrCreateVReg(*CI.getOperand(1)));
724
725 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
726 unsigned Zero = getOrCreateVReg(
727 *Constant::getNullValue(Type::getInt1Ty(CI.getContext())));
728 MIB.addUse(Zero);
729 }
730
731 return true;
732 }
733
translateKnownIntrinsic(const CallInst & CI,Intrinsic::ID ID,MachineIRBuilder & MIRBuilder)734 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
735 MachineIRBuilder &MIRBuilder) {
736 switch (ID) {
737 default:
738 break;
739 case Intrinsic::lifetime_start:
740 case Intrinsic::lifetime_end:
741 // Stack coloring is not enabled in O0 (which we care about now) so we can
742 // drop these. Make sure someone notices when we start compiling at higher
743 // opts though.
744 if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
745 return false;
746 return true;
747 case Intrinsic::dbg_declare: {
748 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
749 assert(DI.getVariable() && "Missing variable");
750
751 const Value *Address = DI.getAddress();
752 if (!Address || isa<UndefValue>(Address)) {
753 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
754 return true;
755 }
756
757 assert(DI.getVariable()->isValidLocationForIntrinsic(
758 MIRBuilder.getDebugLoc()) &&
759 "Expected inlined-at fields to agree");
760 auto AI = dyn_cast<AllocaInst>(Address);
761 if (AI && AI->isStaticAlloca()) {
762 // Static allocas are tracked at the MF level, no need for DBG_VALUE
763 // instructions (in fact, they get ignored if they *do* exist).
764 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
765 getOrCreateFrameIndex(*AI), DI.getDebugLoc());
766 } else
767 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
768 DI.getVariable(), DI.getExpression());
769 return true;
770 }
771 case Intrinsic::vaend:
772 // No target I know of cares about va_end. Certainly no in-tree target
773 // does. Simplest intrinsic ever!
774 return true;
775 case Intrinsic::vastart: {
776 auto &TLI = *MF->getSubtarget().getTargetLowering();
777 Value *Ptr = CI.getArgOperand(0);
778 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
779
780 MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
781 .addUse(getOrCreateVReg(*Ptr))
782 .addMemOperand(MF->getMachineMemOperand(
783 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
784 return true;
785 }
786 case Intrinsic::dbg_value: {
787 // This form of DBG_VALUE is target-independent.
788 const DbgValueInst &DI = cast<DbgValueInst>(CI);
789 const Value *V = DI.getValue();
790 assert(DI.getVariable()->isValidLocationForIntrinsic(
791 MIRBuilder.getDebugLoc()) &&
792 "Expected inlined-at fields to agree");
793 if (!V) {
794 // Currently the optimizer can produce this; insert an undef to
795 // help debugging. Probably the optimizer should not do this.
796 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
797 } else if (const auto *CI = dyn_cast<Constant>(V)) {
798 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
799 } else {
800 unsigned Reg = getOrCreateVReg(*V);
801 // FIXME: This does not handle register-indirect values at offset 0. The
802 // direct/indirect thing shouldn't really be handled by something as
803 // implicit as reg+noreg vs reg+imm in the first palce, but it seems
804 // pretty baked in right now.
805 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
806 }
807 return true;
808 }
809 case Intrinsic::uadd_with_overflow:
810 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
811 case Intrinsic::sadd_with_overflow:
812 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
813 case Intrinsic::usub_with_overflow:
814 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
815 case Intrinsic::ssub_with_overflow:
816 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
817 case Intrinsic::umul_with_overflow:
818 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
819 case Intrinsic::smul_with_overflow:
820 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
821 case Intrinsic::pow:
822 MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
823 .addDef(getOrCreateVReg(CI))
824 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
825 .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
826 return true;
827 case Intrinsic::exp:
828 MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
829 .addDef(getOrCreateVReg(CI))
830 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
831 return true;
832 case Intrinsic::exp2:
833 MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
834 .addDef(getOrCreateVReg(CI))
835 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
836 return true;
837 case Intrinsic::log:
838 MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
839 .addDef(getOrCreateVReg(CI))
840 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
841 return true;
842 case Intrinsic::log2:
843 MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
844 .addDef(getOrCreateVReg(CI))
845 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
846 return true;
847 case Intrinsic::fabs:
848 MIRBuilder.buildInstr(TargetOpcode::G_FABS)
849 .addDef(getOrCreateVReg(CI))
850 .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
851 return true;
852 case Intrinsic::fma:
853 MIRBuilder.buildInstr(TargetOpcode::G_FMA)
854 .addDef(getOrCreateVReg(CI))
855 .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
856 .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
857 .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
858 return true;
859 case Intrinsic::fmuladd: {
860 const TargetMachine &TM = MF->getTarget();
861 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
862 unsigned Dst = getOrCreateVReg(CI);
863 unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
864 unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
865 unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
866 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
867 TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
868 // TODO: Revisit this to see if we should move this part of the
869 // lowering to the combiner.
870 MIRBuilder.buildInstr(TargetOpcode::G_FMA, Dst, Op0, Op1, Op2);
871 } else {
872 LLT Ty = getLLTForType(*CI.getType(), *DL);
873 auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, Ty, Op0, Op1);
874 MIRBuilder.buildInstr(TargetOpcode::G_FADD, Dst, FMul, Op2);
875 }
876 return true;
877 }
878 case Intrinsic::memcpy:
879 case Intrinsic::memmove:
880 case Intrinsic::memset:
881 return translateMemfunc(CI, MIRBuilder, ID);
882 case Intrinsic::eh_typeid_for: {
883 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
884 unsigned Reg = getOrCreateVReg(CI);
885 unsigned TypeID = MF->getTypeIDFor(GV);
886 MIRBuilder.buildConstant(Reg, TypeID);
887 return true;
888 }
889 case Intrinsic::objectsize: {
890 // If we don't know by now, we're never going to know.
891 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
892
893 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
894 return true;
895 }
896 case Intrinsic::stackguard:
897 getStackGuard(getOrCreateVReg(CI), MIRBuilder);
898 return true;
899 case Intrinsic::stackprotector: {
900 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
901 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
902 getStackGuard(GuardVal, MIRBuilder);
903
904 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
905 MIRBuilder.buildStore(
906 GuardVal, getOrCreateVReg(*Slot),
907 *MF->getMachineMemOperand(
908 MachinePointerInfo::getFixedStack(*MF,
909 getOrCreateFrameIndex(*Slot)),
910 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
911 PtrTy.getSizeInBits() / 8, 8));
912 return true;
913 }
914 }
915 return false;
916 }
917
translateInlineAsm(const CallInst & CI,MachineIRBuilder & MIRBuilder)918 bool IRTranslator::translateInlineAsm(const CallInst &CI,
919 MachineIRBuilder &MIRBuilder) {
920 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
921 if (!IA.getConstraintString().empty())
922 return false;
923
924 unsigned ExtraInfo = 0;
925 if (IA.hasSideEffects())
926 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
927 if (IA.getDialect() == InlineAsm::AD_Intel)
928 ExtraInfo |= InlineAsm::Extra_AsmDialect;
929
930 MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
931 .addExternalSymbol(IA.getAsmString().c_str())
932 .addImm(ExtraInfo);
933
934 return true;
935 }
936
packRegs(const Value & V,MachineIRBuilder & MIRBuilder)937 unsigned IRTranslator::packRegs(const Value &V,
938 MachineIRBuilder &MIRBuilder) {
939 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
940 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
941 LLT BigTy = getLLTForType(*V.getType(), *DL);
942
943 if (Regs.size() == 1)
944 return Regs[0];
945
946 unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
947 MIRBuilder.buildUndef(Dst);
948 for (unsigned i = 0; i < Regs.size(); ++i) {
949 unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
950 MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
951 Dst = NewDst;
952 }
953 return Dst;
954 }
955
unpackRegs(const Value & V,unsigned Src,MachineIRBuilder & MIRBuilder)956 void IRTranslator::unpackRegs(const Value &V, unsigned Src,
957 MachineIRBuilder &MIRBuilder) {
958 ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
959 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
960
961 for (unsigned i = 0; i < Regs.size(); ++i)
962 MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
963 }
964
translateCall(const User & U,MachineIRBuilder & MIRBuilder)965 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
966 const CallInst &CI = cast<CallInst>(U);
967 auto TII = MF->getTarget().getIntrinsicInfo();
968 const Function *F = CI.getCalledFunction();
969
970 // FIXME: support Windows dllimport function calls.
971 if (F && F->hasDLLImportStorageClass())
972 return false;
973
974 if (CI.isInlineAsm())
975 return translateInlineAsm(CI, MIRBuilder);
976
977 Intrinsic::ID ID = Intrinsic::not_intrinsic;
978 if (F && F->isIntrinsic()) {
979 ID = F->getIntrinsicID();
980 if (TII && ID == Intrinsic::not_intrinsic)
981 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
982 }
983
984 bool IsSplitType = valueIsSplit(CI);
985 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
986 unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
987 getLLTForType(*CI.getType(), *DL))
988 : getOrCreateVReg(CI);
989
990 SmallVector<unsigned, 8> Args;
991 for (auto &Arg: CI.arg_operands())
992 Args.push_back(packRegs(*Arg, MIRBuilder));
993
994 MF->getFrameInfo().setHasCalls(true);
995 bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
996 return getOrCreateVReg(*CI.getCalledValue());
997 });
998
999 if (IsSplitType)
1000 unpackRegs(CI, Res, MIRBuilder);
1001 return Success;
1002 }
1003
1004 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1005
1006 if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1007 return true;
1008
1009 unsigned Res = 0;
1010 if (!CI.getType()->isVoidTy()) {
1011 if (IsSplitType)
1012 Res =
1013 MRI->createGenericVirtualRegister(getLLTForType(*CI.getType(), *DL));
1014 else
1015 Res = getOrCreateVReg(CI);
1016 }
1017 MachineInstrBuilder MIB =
1018 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
1019
1020 for (auto &Arg : CI.arg_operands()) {
1021 // Some intrinsics take metadata parameters. Reject them.
1022 if (isa<MetadataAsValue>(Arg))
1023 return false;
1024 MIB.addUse(packRegs(*Arg, MIRBuilder));
1025 }
1026
1027 if (IsSplitType)
1028 unpackRegs(CI, Res, MIRBuilder);
1029
1030 // Add a MachineMemOperand if it is a target mem intrinsic.
1031 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1032 TargetLowering::IntrinsicInfo Info;
1033 // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
1034 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
1035 uint64_t Size = Info.memVT.getStoreSize();
1036 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal),
1037 Info.flags, Size, Info.align));
1038 }
1039
1040 return true;
1041 }
1042
translateInvoke(const User & U,MachineIRBuilder & MIRBuilder)1043 bool IRTranslator::translateInvoke(const User &U,
1044 MachineIRBuilder &MIRBuilder) {
1045 const InvokeInst &I = cast<InvokeInst>(U);
1046 MCContext &Context = MF->getContext();
1047
1048 const BasicBlock *ReturnBB = I.getSuccessor(0);
1049 const BasicBlock *EHPadBB = I.getSuccessor(1);
1050
1051 const Value *Callee = I.getCalledValue();
1052 const Function *Fn = dyn_cast<Function>(Callee);
1053 if (isa<InlineAsm>(Callee))
1054 return false;
1055
1056 // FIXME: support invoking patchpoint and statepoint intrinsics.
1057 if (Fn && Fn->isIntrinsic())
1058 return false;
1059
1060 // FIXME: support whatever these are.
1061 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1062 return false;
1063
1064 // FIXME: support Windows exception handling.
1065 if (!isa<LandingPadInst>(EHPadBB->front()))
1066 return false;
1067
1068 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
1069 // the region covered by the try.
1070 MCSymbol *BeginSymbol = Context.createTempSymbol();
1071 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1072
1073 unsigned Res =
1074 MRI->createGenericVirtualRegister(getLLTForType(*I.getType(), *DL));
1075 SmallVector<unsigned, 8> Args;
1076 for (auto &Arg: I.arg_operands())
1077 Args.push_back(packRegs(*Arg, MIRBuilder));
1078
1079 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
1080 [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1081 return false;
1082
1083 unpackRegs(I, Res, MIRBuilder);
1084
1085 MCSymbol *EndSymbol = Context.createTempSymbol();
1086 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1087
1088 // FIXME: track probabilities.
1089 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1090 &ReturnMBB = getMBB(*ReturnBB);
1091 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1092 MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1093 MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
1094 MIRBuilder.buildBr(ReturnMBB);
1095
1096 return true;
1097 }
1098
translateLandingPad(const User & U,MachineIRBuilder & MIRBuilder)1099 bool IRTranslator::translateLandingPad(const User &U,
1100 MachineIRBuilder &MIRBuilder) {
1101 const LandingPadInst &LP = cast<LandingPadInst>(U);
1102
1103 MachineBasicBlock &MBB = MIRBuilder.getMBB();
1104 addLandingPadInfo(LP, MBB);
1105
1106 MBB.setIsEHPad();
1107
1108 // If there aren't registers to copy the values into (e.g., during SjLj
1109 // exceptions), then don't bother.
1110 auto &TLI = *MF->getSubtarget().getTargetLowering();
1111 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1112 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1113 TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1114 return true;
1115
1116 // If landingpad's return type is token type, we don't create DAG nodes
1117 // for its exception pointer and selector value. The extraction of exception
1118 // pointer or selector value from token type landingpads is not currently
1119 // supported.
1120 if (LP.getType()->isTokenTy())
1121 return true;
1122
1123 // Add a label to mark the beginning of the landing pad. Deletion of the
1124 // landing pad can thus be detected via the MachineModuleInfo.
1125 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
1126 .addSym(MF->addLandingPad(&MBB));
1127
1128 LLT Ty = getLLTForType(*LP.getType(), *DL);
1129 unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1130 MIRBuilder.buildUndef(Undef);
1131
1132 SmallVector<LLT, 2> Tys;
1133 for (Type *Ty : cast<StructType>(LP.getType())->elements())
1134 Tys.push_back(getLLTForType(*Ty, *DL));
1135 assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1136
1137 // Mark exception register as live in.
1138 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1139 if (!ExceptionReg)
1140 return false;
1141
1142 MBB.addLiveIn(ExceptionReg);
1143 ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1144 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
1145
1146 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1147 if (!SelectorReg)
1148 return false;
1149
1150 MBB.addLiveIn(SelectorReg);
1151 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1152 MIRBuilder.buildCopy(PtrVReg, SelectorReg);
1153 MIRBuilder.buildCast(ResRegs[1], PtrVReg);
1154
1155 return true;
1156 }
1157
translateAlloca(const User & U,MachineIRBuilder & MIRBuilder)1158 bool IRTranslator::translateAlloca(const User &U,
1159 MachineIRBuilder &MIRBuilder) {
1160 auto &AI = cast<AllocaInst>(U);
1161
1162 if (AI.isSwiftError())
1163 return false;
1164
1165 if (AI.isStaticAlloca()) {
1166 unsigned Res = getOrCreateVReg(AI);
1167 int FI = getOrCreateFrameIndex(AI);
1168 MIRBuilder.buildFrameIndex(Res, FI);
1169 return true;
1170 }
1171
1172 // FIXME: support stack probing for Windows.
1173 if (MF->getTarget().getTargetTriple().isOSWindows())
1174 return false;
1175
1176 // Now we're in the harder dynamic case.
1177 Type *Ty = AI.getAllocatedType();
1178 unsigned Align =
1179 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1180
1181 unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1182
1183 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1184 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
1185 if (MRI->getType(NumElts) != IntPtrTy) {
1186 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1187 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1188 NumElts = ExtElts;
1189 }
1190
1191 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
1192 unsigned TySize =
1193 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
1194 MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1195
1196 LLT PtrTy = getLLTForType(*AI.getType(), *DL);
1197 auto &TLI = *MF->getSubtarget().getTargetLowering();
1198 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1199
1200 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1201 MIRBuilder.buildCopy(SPTmp, SPReg);
1202
1203 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1204 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
1205
1206 // Handle alignment. We have to realign if the allocation granule was smaller
1207 // than stack alignment, or the specific alloca requires more than stack
1208 // alignment.
1209 unsigned StackAlign =
1210 MF->getSubtarget().getFrameLowering()->getStackAlignment();
1211 Align = std::max(Align, StackAlign);
1212 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1213 // Round the size of the allocation up to the stack alignment size
1214 // by add SA-1 to the size. This doesn't overflow because we're computing
1215 // an address inside an alloca.
1216 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1217 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1218 AllocTmp = AlignedAlloc;
1219 }
1220
1221 MIRBuilder.buildCopy(SPReg, AllocTmp);
1222 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
1223
1224 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1225 assert(MF->getFrameInfo().hasVarSizedObjects());
1226 return true;
1227 }
1228
translateVAArg(const User & U,MachineIRBuilder & MIRBuilder)1229 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1230 // FIXME: We may need more info about the type. Because of how LLT works,
1231 // we're completely discarding the i64/double distinction here (amongst
1232 // others). Fortunately the ABIs I know of where that matters don't use va_arg
1233 // anyway but that's not guaranteed.
1234 MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1235 .addDef(getOrCreateVReg(U))
1236 .addUse(getOrCreateVReg(*U.getOperand(0)))
1237 .addImm(DL->getABITypeAlignment(U.getType()));
1238 return true;
1239 }
1240
translateInsertElement(const User & U,MachineIRBuilder & MIRBuilder)1241 bool IRTranslator::translateInsertElement(const User &U,
1242 MachineIRBuilder &MIRBuilder) {
1243 // If it is a <1 x Ty> vector, use the scalar as it is
1244 // not a legal vector type in LLT.
1245 if (U.getType()->getVectorNumElements() == 1) {
1246 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1247 auto &Regs = *VMap.getVRegs(U);
1248 if (Regs.empty()) {
1249 Regs.push_back(Elt);
1250 VMap.getOffsets(U)->push_back(0);
1251 } else {
1252 MIRBuilder.buildCopy(Regs[0], Elt);
1253 }
1254 return true;
1255 }
1256
1257 unsigned Res = getOrCreateVReg(U);
1258 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1259 unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1260 unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1261 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
1262 return true;
1263 }
1264
translateExtractElement(const User & U,MachineIRBuilder & MIRBuilder)1265 bool IRTranslator::translateExtractElement(const User &U,
1266 MachineIRBuilder &MIRBuilder) {
1267 // If it is a <1 x Ty> vector, use the scalar as it is
1268 // not a legal vector type in LLT.
1269 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1270 unsigned Elt = getOrCreateVReg(*U.getOperand(0));
1271 auto &Regs = *VMap.getVRegs(U);
1272 if (Regs.empty()) {
1273 Regs.push_back(Elt);
1274 VMap.getOffsets(U)->push_back(0);
1275 } else {
1276 MIRBuilder.buildCopy(Regs[0], Elt);
1277 }
1278 return true;
1279 }
1280 unsigned Res = getOrCreateVReg(U);
1281 unsigned Val = getOrCreateVReg(*U.getOperand(0));
1282 unsigned Idx = getOrCreateVReg(*U.getOperand(1));
1283 MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
1284 return true;
1285 }
1286
translateShuffleVector(const User & U,MachineIRBuilder & MIRBuilder)1287 bool IRTranslator::translateShuffleVector(const User &U,
1288 MachineIRBuilder &MIRBuilder) {
1289 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1290 .addDef(getOrCreateVReg(U))
1291 .addUse(getOrCreateVReg(*U.getOperand(0)))
1292 .addUse(getOrCreateVReg(*U.getOperand(1)))
1293 .addUse(getOrCreateVReg(*U.getOperand(2)));
1294 return true;
1295 }
1296
translatePHI(const User & U,MachineIRBuilder & MIRBuilder)1297 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1298 const PHINode &PI = cast<PHINode>(U);
1299
1300 SmallVector<MachineInstr *, 4> Insts;
1301 for (auto Reg : getOrCreateVRegs(PI)) {
1302 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, Reg);
1303 Insts.push_back(MIB.getInstr());
1304 }
1305
1306 PendingPHIs.emplace_back(&PI, std::move(Insts));
1307 return true;
1308 }
1309
translateAtomicCmpXchg(const User & U,MachineIRBuilder & MIRBuilder)1310 bool IRTranslator::translateAtomicCmpXchg(const User &U,
1311 MachineIRBuilder &MIRBuilder) {
1312 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1313
1314 if (I.isWeak())
1315 return false;
1316
1317 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1318 : MachineMemOperand::MONone;
1319 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1320
1321 Type *ResType = I.getType();
1322 Type *ValType = ResType->Type::getStructElementType(0);
1323
1324 auto Res = getOrCreateVRegs(I);
1325 unsigned OldValRes = Res[0];
1326 unsigned SuccessRes = Res[1];
1327 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1328 unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1329 unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1330
1331 MIRBuilder.buildAtomicCmpXchgWithSuccess(
1332 OldValRes, SuccessRes, Addr, Cmp, NewVal,
1333 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1334 Flags, DL->getTypeStoreSize(ValType),
1335 getMemOpAlignment(I), AAMDNodes(), nullptr,
1336 I.getSyncScopeID(), I.getSuccessOrdering(),
1337 I.getFailureOrdering()));
1338 return true;
1339 }
1340
translateAtomicRMW(const User & U,MachineIRBuilder & MIRBuilder)1341 bool IRTranslator::translateAtomicRMW(const User &U,
1342 MachineIRBuilder &MIRBuilder) {
1343 const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1344
1345 auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1346 : MachineMemOperand::MONone;
1347 Flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1348
1349 Type *ResType = I.getType();
1350
1351 unsigned Res = getOrCreateVReg(I);
1352 unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1353 unsigned Val = getOrCreateVReg(*I.getValOperand());
1354
1355 unsigned Opcode = 0;
1356 switch (I.getOperation()) {
1357 default:
1358 llvm_unreachable("Unknown atomicrmw op");
1359 return false;
1360 case AtomicRMWInst::Xchg:
1361 Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1362 break;
1363 case AtomicRMWInst::Add:
1364 Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1365 break;
1366 case AtomicRMWInst::Sub:
1367 Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1368 break;
1369 case AtomicRMWInst::And:
1370 Opcode = TargetOpcode::G_ATOMICRMW_AND;
1371 break;
1372 case AtomicRMWInst::Nand:
1373 Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1374 break;
1375 case AtomicRMWInst::Or:
1376 Opcode = TargetOpcode::G_ATOMICRMW_OR;
1377 break;
1378 case AtomicRMWInst::Xor:
1379 Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1380 break;
1381 case AtomicRMWInst::Max:
1382 Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1383 break;
1384 case AtomicRMWInst::Min:
1385 Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1386 break;
1387 case AtomicRMWInst::UMax:
1388 Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1389 break;
1390 case AtomicRMWInst::UMin:
1391 Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1392 break;
1393 }
1394
1395 MIRBuilder.buildAtomicRMW(
1396 Opcode, Res, Addr, Val,
1397 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1398 Flags, DL->getTypeStoreSize(ResType),
1399 getMemOpAlignment(I), AAMDNodes(), nullptr,
1400 I.getSyncScopeID(), I.getOrdering()));
1401 return true;
1402 }
1403
finishPendingPhis()1404 void IRTranslator::finishPendingPhis() {
1405 for (auto &Phi : PendingPHIs) {
1406 const PHINode *PI = Phi.first;
1407 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
1408
1409 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1410 // won't create extra control flow here, otherwise we need to find the
1411 // dominating predecessor here (or perhaps force the weirder IRTranslators
1412 // to provide a simple boundary).
1413 SmallSet<const BasicBlock *, 4> HandledPreds;
1414
1415 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
1416 auto IRPred = PI->getIncomingBlock(i);
1417 if (HandledPreds.count(IRPred))
1418 continue;
1419
1420 HandledPreds.insert(IRPred);
1421 ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
1422 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1423 assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
1424 "incorrect CFG at MachineBasicBlock level");
1425 for (unsigned j = 0; j < ValRegs.size(); ++j) {
1426 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1427 MIB.addUse(ValRegs[j]);
1428 MIB.addMBB(Pred);
1429 }
1430 }
1431 }
1432 }
1433 }
1434
valueIsSplit(const Value & V,SmallVectorImpl<uint64_t> * Offsets)1435 bool IRTranslator::valueIsSplit(const Value &V,
1436 SmallVectorImpl<uint64_t> *Offsets) {
1437 SmallVector<LLT, 4> SplitTys;
1438 if (Offsets && !Offsets->empty())
1439 Offsets->clear();
1440 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1441 return SplitTys.size() > 1;
1442 }
1443
translate(const Instruction & Inst)1444 bool IRTranslator::translate(const Instruction &Inst) {
1445 CurBuilder.setDebugLoc(Inst.getDebugLoc());
1446 switch(Inst.getOpcode()) {
1447 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1448 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
1449 #include "llvm/IR/Instruction.def"
1450 default:
1451 return false;
1452 }
1453 }
1454
translate(const Constant & C,unsigned Reg)1455 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
1456 if (auto CI = dyn_cast<ConstantInt>(&C))
1457 EntryBuilder.buildConstant(Reg, *CI);
1458 else if (auto CF = dyn_cast<ConstantFP>(&C))
1459 EntryBuilder.buildFConstant(Reg, *CF);
1460 else if (isa<UndefValue>(C))
1461 EntryBuilder.buildUndef(Reg);
1462 else if (isa<ConstantPointerNull>(C)) {
1463 // As we are trying to build a constant val of 0 into a pointer,
1464 // insert a cast to make them correct with respect to types.
1465 unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1466 auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1467 auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1468 unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1469 EntryBuilder.buildCast(Reg, ZeroReg);
1470 } else if (auto GV = dyn_cast<GlobalValue>(&C))
1471 EntryBuilder.buildGlobalValue(Reg, GV);
1472 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1473 if (!CAZ->getType()->isVectorTy())
1474 return false;
1475 // Return the scalar if it is a <1 x Ty> vector.
1476 if (CAZ->getNumElements() == 1)
1477 return translate(*CAZ->getElementValue(0u), Reg);
1478 std::vector<unsigned> Ops;
1479 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1480 Constant &Elt = *CAZ->getElementValue(i);
1481 Ops.push_back(getOrCreateVReg(Elt));
1482 }
1483 EntryBuilder.buildMerge(Reg, Ops);
1484 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
1485 // Return the scalar if it is a <1 x Ty> vector.
1486 if (CV->getNumElements() == 1)
1487 return translate(*CV->getElementAsConstant(0), Reg);
1488 std::vector<unsigned> Ops;
1489 for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1490 Constant &Elt = *CV->getElementAsConstant(i);
1491 Ops.push_back(getOrCreateVReg(Elt));
1492 }
1493 EntryBuilder.buildMerge(Reg, Ops);
1494 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1495 switch(CE->getOpcode()) {
1496 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1497 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
1498 #include "llvm/IR/Instruction.def"
1499 default:
1500 return false;
1501 }
1502 } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1503 if (CV->getNumOperands() == 1)
1504 return translate(*CV->getOperand(0), Reg);
1505 SmallVector<unsigned, 4> Ops;
1506 for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1507 Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1508 }
1509 EntryBuilder.buildMerge(Reg, Ops);
1510 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
1511 EntryBuilder.buildBlockAddress(Reg, BA);
1512 } else
1513 return false;
1514
1515 return true;
1516 }
1517
finalizeFunction()1518 void IRTranslator::finalizeFunction() {
1519 // Release the memory used by the different maps we
1520 // needed during the translation.
1521 PendingPHIs.clear();
1522 VMap.reset();
1523 FrameIndices.clear();
1524 MachinePreds.clear();
1525 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1526 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1527 // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1528 EntryBuilder = MachineIRBuilder();
1529 CurBuilder = MachineIRBuilder();
1530 }
1531
runOnMachineFunction(MachineFunction & CurMF)1532 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1533 MF = &CurMF;
1534 const Function &F = MF->getFunction();
1535 if (F.empty())
1536 return false;
1537 CLI = MF->getSubtarget().getCallLowering();
1538 CurBuilder.setMF(*MF);
1539 EntryBuilder.setMF(*MF);
1540 MRI = &MF->getRegInfo();
1541 DL = &F.getParent()->getDataLayout();
1542 TPC = &getAnalysis<TargetPassConfig>();
1543 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
1544
1545 assert(PendingPHIs.empty() && "stale PHIs");
1546
1547 if (!DL->isLittleEndian()) {
1548 // Currently we don't properly handle big endian code.
1549 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1550 F.getSubprogram(), &F.getEntryBlock());
1551 R << "unable to translate in big endian mode";
1552 reportTranslationError(*MF, *TPC, *ORE, R);
1553 }
1554
1555 // Release the per-function state when we return, whether we succeeded or not.
1556 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1557
1558 // Setup a separate basic-block for the arguments and constants
1559 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1560 MF->push_back(EntryBB);
1561 EntryBuilder.setMBB(*EntryBB);
1562
1563 // Create all blocks, in IR order, to preserve the layout.
1564 for (const BasicBlock &BB: F) {
1565 auto *&MBB = BBToMBB[&BB];
1566
1567 MBB = MF->CreateMachineBasicBlock(&BB);
1568 MF->push_back(MBB);
1569
1570 if (BB.hasAddressTaken())
1571 MBB->setHasAddressTaken();
1572 }
1573
1574 // Make our arguments/constants entry block fallthrough to the IR entry block.
1575 EntryBB->addSuccessor(&getMBB(F.front()));
1576
1577 // Lower the actual args into this basic block.
1578 SmallVector<unsigned, 8> VRegArgs;
1579 for (const Argument &Arg: F.args()) {
1580 if (DL->getTypeStoreSize(Arg.getType()) == 0)
1581 continue; // Don't handle zero sized types.
1582 VRegArgs.push_back(
1583 MRI->createGenericVirtualRegister(getLLTForType(*Arg.getType(), *DL)));
1584 }
1585
1586 // We don't currently support translating swifterror or swiftself functions.
1587 for (auto &Arg : F.args()) {
1588 if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1589 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1590 F.getSubprogram(), &F.getEntryBlock());
1591 R << "unable to lower arguments due to swifterror/swiftself: "
1592 << ore::NV("Prototype", F.getType());
1593 reportTranslationError(*MF, *TPC, *ORE, R);
1594 return false;
1595 }
1596 }
1597
1598 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
1599 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1600 F.getSubprogram(), &F.getEntryBlock());
1601 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1602 reportTranslationError(*MF, *TPC, *ORE, R);
1603 return false;
1604 }
1605
1606 auto ArgIt = F.arg_begin();
1607 for (auto &VArg : VRegArgs) {
1608 // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1609 // creating redundant copies.
1610 if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1611 auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1612 assert(VRegs.empty() && "VRegs already populated?");
1613 VRegs.push_back(VArg);
1614 } else {
1615 unpackRegs(*ArgIt, VArg, EntryBuilder);
1616 }
1617 ArgIt++;
1618 }
1619
1620 // Need to visit defs before uses when translating instructions.
1621 ReversePostOrderTraversal<const Function *> RPOT(&F);
1622 for (const BasicBlock *BB : RPOT) {
1623 MachineBasicBlock &MBB = getMBB(*BB);
1624 // Set the insertion point of all the following translations to
1625 // the end of this basic block.
1626 CurBuilder.setMBB(MBB);
1627
1628 for (const Instruction &Inst : *BB) {
1629 if (translate(Inst))
1630 continue;
1631
1632 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1633 Inst.getDebugLoc(), BB);
1634 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1635
1636 if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1637 std::string InstStrStorage;
1638 raw_string_ostream InstStr(InstStrStorage);
1639 InstStr << Inst;
1640
1641 R << ": '" << InstStr.str() << "'";
1642 }
1643
1644 reportTranslationError(*MF, *TPC, *ORE, R);
1645 return false;
1646 }
1647 }
1648
1649 finishPendingPhis();
1650
1651 // Merge the argument lowering and constants block with its single
1652 // successor, the LLVM-IR entry block. We want the basic block to
1653 // be maximal.
1654 assert(EntryBB->succ_size() == 1 &&
1655 "Custom BB used for lowering should have only one successor");
1656 // Get the successor of the current entry block.
1657 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1658 assert(NewEntryBB.pred_size() == 1 &&
1659 "LLVM-IR entry block has a predecessor!?");
1660 // Move all the instruction from the current entry block to the
1661 // new entry block.
1662 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1663 EntryBB->end());
1664
1665 // Update the live-in information for the new entry block.
1666 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1667 NewEntryBB.addLiveIn(LiveIn);
1668 NewEntryBB.sortUniqueLiveIns();
1669
1670 // Get rid of the now empty basic block.
1671 EntryBB->removeSuccessor(&NewEntryBB);
1672 MF->remove(EntryBB);
1673 MF->DeleteMachineBasicBlock(EntryBB);
1674
1675 assert(&MF->front() == &NewEntryBB &&
1676 "New entry wasn't next in the list of basic block!");
1677
1678 // Initialize stack protector information.
1679 StackProtector &SP = getAnalysis<StackProtector>();
1680 SP.copyToMachineFrameInfo(MF->getFrameInfo());
1681
1682 return false;
1683 }
1684