OSDN Git Service

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