OSDN Git Service

GlobalISel: support translating va_arg
[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
15 #include "llvm/ADT/SmallSet.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/TargetPassConfig.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GetElementPtrTypeIterator.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetIntrinsicInfo.h"
33 #include "llvm/Target/TargetLowering.h"
34
35 #define DEBUG_TYPE "irtranslator"
36
37 using namespace llvm;
38
39 char IRTranslator::ID = 0;
40 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
41                 false, false)
42 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
43 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
44                 false, false)
45
46 static void reportTranslationError(const Value &V, const Twine &Message) {
47   std::string ErrStorage;
48   raw_string_ostream Err(ErrStorage);
49   Err << Message << ": " << V << '\n';
50   report_fatal_error(Err.str());
51 }
52
53 IRTranslator::IRTranslator() : MachineFunctionPass(ID), MRI(nullptr) {
54   initializeIRTranslatorPass(*PassRegistry::getPassRegistry());
55 }
56
57 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
58   AU.addRequired<TargetPassConfig>();
59   MachineFunctionPass::getAnalysisUsage(AU);
60 }
61
62
63 unsigned IRTranslator::getOrCreateVReg(const Value &Val) {
64   unsigned &ValReg = ValToVReg[&Val];
65
66   if (ValReg)
67     return ValReg;
68
69   // Fill ValRegsSequence with the sequence of registers
70   // we need to concat together to produce the value.
71   assert(Val.getType()->isSized() &&
72          "Don't know how to create an empty vreg");
73   unsigned VReg = MRI->createGenericVirtualRegister(LLT{*Val.getType(), *DL});
74   ValReg = VReg;
75
76   if (auto CV = dyn_cast<Constant>(&Val)) {
77     bool Success = translate(*CV, VReg);
78     if (!Success) {
79       if (!TPC->isGlobalISelAbortEnabled()) {
80         MF->getProperties().set(
81             MachineFunctionProperties::Property::FailedISel);
82         return VReg;
83       }
84       reportTranslationError(Val, "unable to translate constant");
85     }
86   }
87
88   return VReg;
89 }
90
91 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
92   if (FrameIndices.find(&AI) != FrameIndices.end())
93     return FrameIndices[&AI];
94
95   unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
96   unsigned Size =
97       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
98
99   // Always allocate at least one byte.
100   Size = std::max(Size, 1u);
101
102   unsigned Alignment = AI.getAlignment();
103   if (!Alignment)
104     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
105
106   int &FI = FrameIndices[&AI];
107   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
108   return FI;
109 }
110
111 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
112   unsigned Alignment = 0;
113   Type *ValTy = nullptr;
114   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
115     Alignment = SI->getAlignment();
116     ValTy = SI->getValueOperand()->getType();
117   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
118     Alignment = LI->getAlignment();
119     ValTy = LI->getType();
120   } else if (!TPC->isGlobalISelAbortEnabled()) {
121     MF->getProperties().set(
122         MachineFunctionProperties::Property::FailedISel);
123     return 1;
124   } else
125     llvm_unreachable("unhandled memory instruction");
126
127   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
128 }
129
130 MachineBasicBlock &IRTranslator::getOrCreateBB(const BasicBlock &BB) {
131   MachineBasicBlock *&MBB = BBToMBB[&BB];
132   if (!MBB) {
133     MBB = MF->CreateMachineBasicBlock(&BB);
134     MF->push_back(MBB);
135
136     if (BB.hasAddressTaken())
137       MBB->setHasAddressTaken();
138   }
139   return *MBB;
140 }
141
142 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
143   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
144   MachinePreds[Edge].push_back(NewPred);
145 }
146
147 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
148                                      MachineIRBuilder &MIRBuilder) {
149   // FIXME: handle signed/unsigned wrapping flags.
150
151   // Get or create a virtual register for each value.
152   // Unless the value is a Constant => loadimm cst?
153   // or inline constant each time?
154   // Creation of a virtual register needs to have a size.
155   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
156   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
157   unsigned Res = getOrCreateVReg(U);
158   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
159   return true;
160 }
161
162 bool IRTranslator::translateCompare(const User &U,
163                                     MachineIRBuilder &MIRBuilder) {
164   const CmpInst *CI = dyn_cast<CmpInst>(&U);
165   unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
166   unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
167   unsigned Res = getOrCreateVReg(U);
168   CmpInst::Predicate Pred =
169       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
170                                     cast<ConstantExpr>(U).getPredicate());
171
172   if (CmpInst::isIntPredicate(Pred))
173     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
174   else
175     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
176
177   return true;
178 }
179
180 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
181   const ReturnInst &RI = cast<ReturnInst>(U);
182   const Value *Ret = RI.getReturnValue();
183   // The target may mess up with the insertion point, but
184   // this is not important as a return is the last instruction
185   // of the block anyway.
186   return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret));
187 }
188
189 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
190   const BranchInst &BrInst = cast<BranchInst>(U);
191   unsigned Succ = 0;
192   if (!BrInst.isUnconditional()) {
193     // We want a G_BRCOND to the true BB followed by an unconditional branch.
194     unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
195     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
196     MachineBasicBlock &TrueBB = getOrCreateBB(TrueTgt);
197     MIRBuilder.buildBrCond(Tst, TrueBB);
198   }
199
200   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
201   MachineBasicBlock &TgtBB = getOrCreateBB(BrTgt);
202   MIRBuilder.buildBr(TgtBB);
203
204   // Link successors.
205   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
206   for (const BasicBlock *Succ : BrInst.successors())
207     CurBB.addSuccessor(&getOrCreateBB(*Succ));
208   return true;
209 }
210
211 bool IRTranslator::translateSwitch(const User &U,
212                                    MachineIRBuilder &MIRBuilder) {
213   // For now, just translate as a chain of conditional branches.
214   // FIXME: could we share most of the logic/code in
215   // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
216   // At first sight, it seems most of the logic in there is independent of
217   // SelectionDAG-specifics and a lot of work went in to optimize switch
218   // lowering in there.
219
220   const SwitchInst &SwInst = cast<SwitchInst>(U);
221   const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
222   const BasicBlock *OrigBB = SwInst.getParent();
223
224   LLT LLTi1 = LLT(*Type::getInt1Ty(U.getContext()), *DL);
225   for (auto &CaseIt : SwInst.cases()) {
226     const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
227     const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
228     MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
229     MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
230     const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
231     MachineBasicBlock &TrueMBB = getOrCreateBB(*TrueBB);
232
233     MIRBuilder.buildBrCond(Tst, TrueMBB);
234     CurMBB.addSuccessor(&TrueMBB);
235     addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
236
237     MachineBasicBlock *FalseMBB =
238         MF->CreateMachineBasicBlock(SwInst.getParent());
239     MF->push_back(FalseMBB);
240     MIRBuilder.buildBr(*FalseMBB);
241     CurMBB.addSuccessor(FalseMBB);
242
243     MIRBuilder.setMBB(*FalseMBB);
244   }
245   // handle default case
246   const BasicBlock *DefaultBB = SwInst.getDefaultDest();
247   MachineBasicBlock &DefaultMBB = getOrCreateBB(*DefaultBB);
248   MIRBuilder.buildBr(DefaultMBB);
249   MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
250   CurMBB.addSuccessor(&DefaultMBB);
251   addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
252
253   return true;
254 }
255
256 bool IRTranslator::translateIndirectBr(const User &U,
257                                        MachineIRBuilder &MIRBuilder) {
258   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
259
260   const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
261   MIRBuilder.buildBrIndirect(Tgt);
262
263   // Link successors.
264   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
265   for (const BasicBlock *Succ : BrInst.successors())
266     CurBB.addSuccessor(&getOrCreateBB(*Succ));
267
268   return true;
269 }
270
271 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
272   const LoadInst &LI = cast<LoadInst>(U);
273
274   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
275                                : MachineMemOperand::MONone;
276   Flags |= MachineMemOperand::MOLoad;
277
278   unsigned Res = getOrCreateVReg(LI);
279   unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
280   LLT VTy{*LI.getType(), *DL}, PTy{*LI.getPointerOperand()->getType(), *DL};
281   MIRBuilder.buildLoad(
282       Res, Addr,
283       *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
284                                 Flags, DL->getTypeStoreSize(LI.getType()),
285                                 getMemOpAlignment(LI), AAMDNodes(), nullptr,
286                                 LI.getSynchScope(), LI.getOrdering()));
287   return true;
288 }
289
290 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
291   const StoreInst &SI = cast<StoreInst>(U);
292   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
293                                : MachineMemOperand::MONone;
294   Flags |= MachineMemOperand::MOStore;
295
296   unsigned Val = getOrCreateVReg(*SI.getValueOperand());
297   unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
298   LLT VTy{*SI.getValueOperand()->getType(), *DL},
299       PTy{*SI.getPointerOperand()->getType(), *DL};
300
301   MIRBuilder.buildStore(
302       Val, Addr,
303       *MF->getMachineMemOperand(
304           MachinePointerInfo(SI.getPointerOperand()), Flags,
305           DL->getTypeStoreSize(SI.getValueOperand()->getType()),
306           getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSynchScope(),
307           SI.getOrdering()));
308   return true;
309 }
310
311 bool IRTranslator::translateExtractValue(const User &U,
312                                          MachineIRBuilder &MIRBuilder) {
313   const Value *Src = U.getOperand(0);
314   Type *Int32Ty = Type::getInt32Ty(U.getContext());
315   SmallVector<Value *, 1> Indices;
316
317   // getIndexedOffsetInType is designed for GEPs, so the first index is the
318   // usual array element rather than looking into the actual aggregate.
319   Indices.push_back(ConstantInt::get(Int32Ty, 0));
320
321   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
322     for (auto Idx : EVI->indices())
323       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
324   } else {
325     for (unsigned i = 1; i < U.getNumOperands(); ++i)
326       Indices.push_back(U.getOperand(i));
327   }
328
329   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
330
331   unsigned Res = getOrCreateVReg(U);
332   MIRBuilder.buildExtract(Res, Offset, getOrCreateVReg(*Src));
333
334   return true;
335 }
336
337 bool IRTranslator::translateInsertValue(const User &U,
338                                         MachineIRBuilder &MIRBuilder) {
339   const Value *Src = U.getOperand(0);
340   Type *Int32Ty = Type::getInt32Ty(U.getContext());
341   SmallVector<Value *, 1> Indices;
342
343   // getIndexedOffsetInType is designed for GEPs, so the first index is the
344   // usual array element rather than looking into the actual aggregate.
345   Indices.push_back(ConstantInt::get(Int32Ty, 0));
346
347   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
348     for (auto Idx : IVI->indices())
349       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
350   } else {
351     for (unsigned i = 2; i < U.getNumOperands(); ++i)
352       Indices.push_back(U.getOperand(i));
353   }
354
355   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
356
357   unsigned Res = getOrCreateVReg(U);
358   const Value &Inserted = *U.getOperand(1);
359   MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
360                          Offset);
361
362   return true;
363 }
364
365 bool IRTranslator::translateSelect(const User &U,
366                                    MachineIRBuilder &MIRBuilder) {
367   MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
368                          getOrCreateVReg(*U.getOperand(1)),
369                          getOrCreateVReg(*U.getOperand(2)));
370   return true;
371 }
372
373 bool IRTranslator::translateBitCast(const User &U,
374                                     MachineIRBuilder &MIRBuilder) {
375   if (LLT{*U.getOperand(0)->getType(), *DL} == LLT{*U.getType(), *DL}) {
376     unsigned &Reg = ValToVReg[&U];
377     if (Reg)
378       MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0)));
379     else
380       Reg = getOrCreateVReg(*U.getOperand(0));
381     return true;
382   }
383   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
384 }
385
386 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
387                                  MachineIRBuilder &MIRBuilder) {
388   unsigned Op = getOrCreateVReg(*U.getOperand(0));
389   unsigned Res = getOrCreateVReg(U);
390   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
391   return true;
392 }
393
394 bool IRTranslator::translateGetElementPtr(const User &U,
395                                           MachineIRBuilder &MIRBuilder) {
396   // FIXME: support vector GEPs.
397   if (U.getType()->isVectorTy())
398     return false;
399
400   Value &Op0 = *U.getOperand(0);
401   unsigned BaseReg = getOrCreateVReg(Op0);
402   LLT PtrTy{*Op0.getType(), *DL};
403   unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
404   LLT OffsetTy = LLT::scalar(PtrSize);
405
406   int64_t Offset = 0;
407   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
408        GTI != E; ++GTI) {
409     const Value *Idx = GTI.getOperand();
410     if (StructType *StTy = GTI.getStructTypeOrNull()) {
411       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
412       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
413       continue;
414     } else {
415       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
416
417       // If this is a scalar constant or a splat vector of constants,
418       // handle it quickly.
419       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
420         Offset += ElementSize * CI->getSExtValue();
421         continue;
422       }
423
424       if (Offset != 0) {
425         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
426         unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
427         MIRBuilder.buildConstant(OffsetReg, Offset);
428         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
429
430         BaseReg = NewBaseReg;
431         Offset = 0;
432       }
433
434       // N = N + Idx * ElementSize;
435       unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
436       MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
437
438       unsigned IdxReg = getOrCreateVReg(*Idx);
439       if (MRI->getType(IdxReg) != OffsetTy) {
440         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
441         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
442         IdxReg = NewIdxReg;
443       }
444
445       unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
446       MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
447
448       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
449       MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
450       BaseReg = NewBaseReg;
451     }
452   }
453
454   if (Offset != 0) {
455     unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
456     MIRBuilder.buildConstant(OffsetReg, Offset);
457     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
458     return true;
459   }
460
461   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
462   return true;
463 }
464
465 bool IRTranslator::translateMemfunc(const CallInst &CI,
466                                     MachineIRBuilder &MIRBuilder,
467                                     unsigned ID) {
468   LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL};
469   Type *DstTy = CI.getArgOperand(0)->getType();
470   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
471       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
472     return false;
473
474   SmallVector<CallLowering::ArgInfo, 8> Args;
475   for (int i = 0; i < 3; ++i) {
476     const auto &Arg = CI.getArgOperand(i);
477     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
478   }
479
480   const char *Callee;
481   switch (ID) {
482   case Intrinsic::memmove:
483   case Intrinsic::memcpy: {
484     Type *SrcTy = CI.getArgOperand(1)->getType();
485     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
486       return false;
487     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
488     break;
489   }
490   case Intrinsic::memset:
491     Callee = "memset";
492     break;
493   default:
494     return false;
495   }
496
497   return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
498                         CallLowering::ArgInfo(0, CI.getType()), Args);
499 }
500
501 void IRTranslator::getStackGuard(unsigned DstReg,
502                                  MachineIRBuilder &MIRBuilder) {
503   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
504   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
505   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
506   MIB.addDef(DstReg);
507
508   auto &TLI = *MF->getSubtarget().getTargetLowering();
509   Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
510   if (!Global)
511     return;
512
513   MachinePointerInfo MPInfo(Global);
514   MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
515   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
516                MachineMemOperand::MODereferenceable;
517   *MemRefs =
518       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
519                                DL->getPointerABIAlignment());
520   MIB.setMemRefs(MemRefs, MemRefs + 1);
521 }
522
523 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
524                                               MachineIRBuilder &MIRBuilder) {
525   LLT Ty{*CI.getOperand(0)->getType(), *DL};
526   LLT s1 = LLT::scalar(1);
527   unsigned Width = Ty.getSizeInBits();
528   unsigned Res = MRI->createGenericVirtualRegister(Ty);
529   unsigned Overflow = MRI->createGenericVirtualRegister(s1);
530   auto MIB = MIRBuilder.buildInstr(Op)
531                  .addDef(Res)
532                  .addDef(Overflow)
533                  .addUse(getOrCreateVReg(*CI.getOperand(0)))
534                  .addUse(getOrCreateVReg(*CI.getOperand(1)));
535
536   if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
537     unsigned Zero = MRI->createGenericVirtualRegister(s1);
538     EntryBuilder.buildConstant(Zero, 0);
539     MIB.addUse(Zero);
540   }
541
542   MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
543   return true;
544 }
545
546 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
547                                            MachineIRBuilder &MIRBuilder) {
548   switch (ID) {
549   default:
550     break;
551   case Intrinsic::lifetime_start:
552   case Intrinsic::lifetime_end:
553     // Stack coloring is not enabled in O0 (which we care about now) so we can
554     // drop these. Make sure someone notices when we start compiling at higher
555     // opts though.
556     if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
557       return false;
558     return true;
559   case Intrinsic::dbg_declare: {
560     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
561     assert(DI.getVariable() && "Missing variable");
562
563     const Value *Address = DI.getAddress();
564     if (!Address || isa<UndefValue>(Address)) {
565       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
566       return true;
567     }
568
569     unsigned Reg = getOrCreateVReg(*Address);
570     auto RegDef = MRI->def_instr_begin(Reg);
571     assert(DI.getVariable()->isValidLocationForIntrinsic(
572                MIRBuilder.getDebugLoc()) &&
573            "Expected inlined-at fields to agree");
574
575     if (RegDef != MRI->def_instr_end() &&
576         RegDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
577       MIRBuilder.buildFIDbgValue(RegDef->getOperand(1).getIndex(),
578                                  DI.getVariable(), DI.getExpression());
579     } else
580       MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
581     return true;
582   }
583   case Intrinsic::vaend:
584     // No target I know of cares about va_end. Certainly no in-tree target
585     // does. Simplest intrinsic ever!
586     return true;
587   case Intrinsic::vastart: {
588     auto &TLI = *MF->getSubtarget().getTargetLowering();
589     Value *Ptr = CI.getArgOperand(0);
590     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
591
592     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
593         .addUse(getOrCreateVReg(*Ptr))
594         .addMemOperand(MF->getMachineMemOperand(
595             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
596     return true;
597   }
598   case Intrinsic::dbg_value: {
599     // This form of DBG_VALUE is target-independent.
600     const DbgValueInst &DI = cast<DbgValueInst>(CI);
601     const Value *V = DI.getValue();
602     assert(DI.getVariable()->isValidLocationForIntrinsic(
603                MIRBuilder.getDebugLoc()) &&
604            "Expected inlined-at fields to agree");
605     if (!V) {
606       // Currently the optimizer can produce this; insert an undef to
607       // help debugging.  Probably the optimizer should not do this.
608       MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
609                                        DI.getExpression());
610     } else if (const auto *CI = dyn_cast<Constant>(V)) {
611       MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
612                                     DI.getExpression());
613     } else {
614       unsigned Reg = getOrCreateVReg(*V);
615       // FIXME: This does not handle register-indirect values at offset 0. The
616       // direct/indirect thing shouldn't really be handled by something as
617       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
618       // pretty baked in right now.
619       if (DI.getOffset() != 0)
620         MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
621                                          DI.getExpression());
622       else
623         MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
624                                        DI.getExpression());
625     }
626     return true;
627   }
628   case Intrinsic::uadd_with_overflow:
629     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
630   case Intrinsic::sadd_with_overflow:
631     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
632   case Intrinsic::usub_with_overflow:
633     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
634   case Intrinsic::ssub_with_overflow:
635     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
636   case Intrinsic::umul_with_overflow:
637     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
638   case Intrinsic::smul_with_overflow:
639     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
640   case Intrinsic::pow:
641     MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
642         .addDef(getOrCreateVReg(CI))
643         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
644         .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
645     return true;
646   case Intrinsic::memcpy:
647   case Intrinsic::memmove:
648   case Intrinsic::memset:
649     return translateMemfunc(CI, MIRBuilder, ID);
650   case Intrinsic::eh_typeid_for: {
651     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
652     unsigned Reg = getOrCreateVReg(CI);
653     unsigned TypeID = MF->getTypeIDFor(GV);
654     MIRBuilder.buildConstant(Reg, TypeID);
655     return true;
656   }
657   case Intrinsic::objectsize: {
658     // If we don't know by now, we're never going to know.
659     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
660
661     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
662     return true;
663   }
664   case Intrinsic::stackguard:
665     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
666     return true;
667   case Intrinsic::stackprotector: {
668     LLT PtrTy{*CI.getArgOperand(0)->getType(), *DL};
669     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
670     getStackGuard(GuardVal, MIRBuilder);
671
672     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
673     MIRBuilder.buildStore(
674         GuardVal, getOrCreateVReg(*Slot),
675         *MF->getMachineMemOperand(
676             MachinePointerInfo::getFixedStack(*MF,
677                                               getOrCreateFrameIndex(*Slot)),
678             MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
679             PtrTy.getSizeInBits() / 8, 8));
680     return true;
681   }
682   }
683   return false;
684 }
685
686 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
687   const CallInst &CI = cast<CallInst>(U);
688   auto TII = MF->getTarget().getIntrinsicInfo();
689   const Function *F = CI.getCalledFunction();
690
691   if (CI.isInlineAsm())
692     return false;
693
694   if (!F || !F->isIntrinsic()) {
695     unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
696     SmallVector<unsigned, 8> Args;
697     for (auto &Arg: CI.arg_operands())
698       Args.push_back(getOrCreateVReg(*Arg));
699
700     return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
701       return getOrCreateVReg(*CI.getCalledValue());
702     });
703   }
704
705   Intrinsic::ID ID = F->getIntrinsicID();
706   if (TII && ID == Intrinsic::not_intrinsic)
707     ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
708
709   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
710
711   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
712     return true;
713
714   unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
715   MachineInstrBuilder MIB =
716       MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
717
718   for (auto &Arg : CI.arg_operands()) {
719     if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
720       MIB.addImm(CI->getSExtValue());
721     else
722       MIB.addUse(getOrCreateVReg(*Arg));
723   }
724   return true;
725 }
726
727 bool IRTranslator::translateInvoke(const User &U,
728                                    MachineIRBuilder &MIRBuilder) {
729   const InvokeInst &I = cast<InvokeInst>(U);
730   MCContext &Context = MF->getContext();
731
732   const BasicBlock *ReturnBB = I.getSuccessor(0);
733   const BasicBlock *EHPadBB = I.getSuccessor(1);
734
735   const Value *Callee(I.getCalledValue());
736   const Function *Fn = dyn_cast<Function>(Callee);
737   if (isa<InlineAsm>(Callee))
738     return false;
739
740   // FIXME: support invoking patchpoint and statepoint intrinsics.
741   if (Fn && Fn->isIntrinsic())
742     return false;
743
744   // FIXME: support whatever these are.
745   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
746     return false;
747
748   // FIXME: support Windows exception handling.
749   if (!isa<LandingPadInst>(EHPadBB->front()))
750     return false;
751
752
753   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
754   // the region covered by the try.
755   MCSymbol *BeginSymbol = Context.createTempSymbol();
756   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
757
758   unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
759   SmallVector<unsigned, 8> Args;
760   for (auto &Arg: I.arg_operands())
761     Args.push_back(getOrCreateVReg(*Arg));
762
763  CLI->lowerCall(MIRBuilder, I, Res, Args,
764                  [&]() { return getOrCreateVReg(*I.getCalledValue()); });
765
766   MCSymbol *EndSymbol = Context.createTempSymbol();
767   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
768
769   // FIXME: track probabilities.
770   MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
771                     &ReturnMBB = getOrCreateBB(*ReturnBB);
772   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
773   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
774   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
775   MIRBuilder.buildBr(ReturnMBB);
776
777   return true;
778 }
779
780 bool IRTranslator::translateLandingPad(const User &U,
781                                        MachineIRBuilder &MIRBuilder) {
782   const LandingPadInst &LP = cast<LandingPadInst>(U);
783
784   MachineBasicBlock &MBB = MIRBuilder.getMBB();
785   addLandingPadInfo(LP, MBB);
786
787   MBB.setIsEHPad();
788
789   // If there aren't registers to copy the values into (e.g., during SjLj
790   // exceptions), then don't bother.
791   auto &TLI = *MF->getSubtarget().getTargetLowering();
792   const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
793   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
794       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
795     return true;
796
797   // If landingpad's return type is token type, we don't create DAG nodes
798   // for its exception pointer and selector value. The extraction of exception
799   // pointer or selector value from token type landingpads is not currently
800   // supported.
801   if (LP.getType()->isTokenTy())
802     return true;
803
804   // Add a label to mark the beginning of the landing pad.  Deletion of the
805   // landing pad can thus be detected via the MachineModuleInfo.
806   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
807     .addSym(MF->addLandingPad(&MBB));
808
809   SmallVector<LLT, 2> Tys;
810   for (Type *Ty : cast<StructType>(LP.getType())->elements())
811     Tys.push_back(LLT{*Ty, *DL});
812   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
813
814   // Mark exception register as live in.
815   SmallVector<unsigned, 2> Regs;
816   SmallVector<uint64_t, 2> Offsets;
817   if (unsigned Reg = TLI.getExceptionPointerRegister(PersonalityFn)) {
818     MBB.addLiveIn(Reg);
819     unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]);
820     MIRBuilder.buildCopy(VReg, Reg);
821     Regs.push_back(VReg);
822     Offsets.push_back(0);
823   }
824
825   if (unsigned Reg = TLI.getExceptionSelectorRegister(PersonalityFn)) {
826     MBB.addLiveIn(Reg);
827
828     // N.b. the exception selector register always has pointer type and may not
829     // match the actual IR-level type in the landingpad so an extra cast is
830     // needed.
831     unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
832     MIRBuilder.buildCopy(PtrVReg, Reg);
833
834     unsigned VReg = MRI->createGenericVirtualRegister(Tys[1]);
835     MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT)
836         .addDef(VReg)
837         .addUse(PtrVReg);
838     Regs.push_back(VReg);
839     Offsets.push_back(Tys[0].getSizeInBits());
840   }
841
842   MIRBuilder.buildSequence(getOrCreateVReg(LP), Regs, Offsets);
843   return true;
844 }
845
846 bool IRTranslator::translateAlloca(const User &U,
847                                    MachineIRBuilder &MIRBuilder) {
848   auto &AI = cast<AllocaInst>(U);
849
850   if (AI.isStaticAlloca()) {
851     unsigned Res = getOrCreateVReg(AI);
852     int FI = getOrCreateFrameIndex(AI);
853     MIRBuilder.buildFrameIndex(Res, FI);
854     return true;
855   }
856
857   // Now we're in the harder dynamic case.
858   Type *Ty = AI.getAllocatedType();
859   unsigned Align =
860       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
861
862   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
863
864   LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
865   if (MRI->getType(NumElts) != IntPtrTy) {
866     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
867     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
868     NumElts = ExtElts;
869   }
870
871   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
872   unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
873   MIRBuilder.buildConstant(TySize, -DL->getTypeAllocSize(Ty));
874   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
875
876   LLT PtrTy = LLT{*AI.getType(), *DL};
877   auto &TLI = *MF->getSubtarget().getTargetLowering();
878   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
879
880   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
881   MIRBuilder.buildCopy(SPTmp, SPReg);
882
883   unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
884   MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
885
886   // Handle alignment. We have to realign if the allocation granule was smaller
887   // than stack alignment, or the specific alloca requires more than stack
888   // alignment.
889   unsigned StackAlign =
890       MF->getSubtarget().getFrameLowering()->getStackAlignment();
891   Align = std::max(Align, StackAlign);
892   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
893     // Round the size of the allocation up to the stack alignment size
894     // by add SA-1 to the size. This doesn't overflow because we're computing
895     // an address inside an alloca.
896     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
897     MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
898     AllocTmp = AlignedAlloc;
899   }
900
901   MIRBuilder.buildCopy(SPReg, AllocTmp);
902   MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
903
904   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
905   assert(MF->getFrameInfo().hasVarSizedObjects());
906   return true;
907 }
908
909 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
910   // FIXME: We may need more info about the type. Because of how LLT works,
911   // we're completely discarding the i64/double distinction here (amongst
912   // others). Fortunately the ABIs I know of where that matters don't use va_arg
913   // anyway but that's not guaranteed.
914   MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
915     .addDef(getOrCreateVReg(U))
916     .addUse(getOrCreateVReg(*U.getOperand(0)))
917     .addImm(DL->getABITypeAlignment(U.getType()));
918   return true;
919 }
920
921 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
922   const PHINode &PI = cast<PHINode>(U);
923   auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
924   MIB.addDef(getOrCreateVReg(PI));
925
926   PendingPHIs.emplace_back(&PI, MIB.getInstr());
927   return true;
928 }
929
930 void IRTranslator::finishPendingPhis() {
931   for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
932     const PHINode *PI = Phi.first;
933     MachineInstrBuilder MIB(*MF, Phi.second);
934
935     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
936     // won't create extra control flow here, otherwise we need to find the
937     // dominating predecessor here (or perhaps force the weirder IRTranslators
938     // to provide a simple boundary).
939     SmallSet<const BasicBlock *, 4> HandledPreds;
940
941     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
942       auto IRPred = PI->getIncomingBlock(i);
943       if (HandledPreds.count(IRPred))
944         continue;
945
946       HandledPreds.insert(IRPred);
947       unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
948       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
949         assert(Pred->isSuccessor(MIB->getParent()) &&
950                "incorrect CFG at MachineBasicBlock level");
951         MIB.addUse(ValReg);
952         MIB.addMBB(Pred);
953       }
954     }
955   }
956 }
957
958 bool IRTranslator::translate(const Instruction &Inst) {
959   CurBuilder.setDebugLoc(Inst.getDebugLoc());
960   switch(Inst.getOpcode()) {
961 #define HANDLE_INST(NUM, OPCODE, CLASS) \
962     case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
963 #include "llvm/IR/Instruction.def"
964   default:
965     if (!TPC->isGlobalISelAbortEnabled())
966       return false;
967     llvm_unreachable("unknown opcode");
968   }
969 }
970
971 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
972   if (auto CI = dyn_cast<ConstantInt>(&C))
973     EntryBuilder.buildConstant(Reg, *CI);
974   else if (auto CF = dyn_cast<ConstantFP>(&C))
975     EntryBuilder.buildFConstant(Reg, *CF);
976   else if (isa<UndefValue>(C))
977     EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg);
978   else if (isa<ConstantPointerNull>(C))
979     EntryBuilder.buildConstant(Reg, 0);
980   else if (auto GV = dyn_cast<GlobalValue>(&C))
981     EntryBuilder.buildGlobalValue(Reg, GV);
982   else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
983     switch(CE->getOpcode()) {
984 #define HANDLE_INST(NUM, OPCODE, CLASS)                         \
985       case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
986 #include "llvm/IR/Instruction.def"
987     default:
988       if (!TPC->isGlobalISelAbortEnabled())
989         return false;
990       llvm_unreachable("unknown opcode");
991     }
992   } else if (!TPC->isGlobalISelAbortEnabled())
993     return false;
994   else
995     llvm_unreachable("unhandled constant kind");
996
997   return true;
998 }
999
1000 void IRTranslator::finalizeFunction() {
1001   // Release the memory used by the different maps we
1002   // needed during the translation.
1003   PendingPHIs.clear();
1004   ValToVReg.clear();
1005   FrameIndices.clear();
1006   Constants.clear();
1007   MachinePreds.clear();
1008 }
1009
1010 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1011   MF = &CurMF;
1012   const Function &F = *MF->getFunction();
1013   if (F.empty())
1014     return false;
1015   CLI = MF->getSubtarget().getCallLowering();
1016   CurBuilder.setMF(*MF);
1017   EntryBuilder.setMF(*MF);
1018   MRI = &MF->getRegInfo();
1019   DL = &F.getParent()->getDataLayout();
1020   TPC = &getAnalysis<TargetPassConfig>();
1021
1022   assert(PendingPHIs.empty() && "stale PHIs");
1023
1024   // Setup a separate basic-block for the arguments and constants, falling
1025   // through to the IR-level Function's entry block.
1026   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1027   MF->push_back(EntryBB);
1028   EntryBB->addSuccessor(&getOrCreateBB(F.front()));
1029   EntryBuilder.setMBB(*EntryBB);
1030
1031   // Lower the actual args into this basic block.
1032   SmallVector<unsigned, 8> VRegArgs;
1033   for (const Argument &Arg: F.args())
1034     VRegArgs.push_back(getOrCreateVReg(Arg));
1035   bool Succeeded = CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs);
1036   if (!Succeeded) {
1037     if (!TPC->isGlobalISelAbortEnabled()) {
1038       MF->getProperties().set(
1039           MachineFunctionProperties::Property::FailedISel);
1040       finalizeFunction();
1041       return false;
1042     }
1043     report_fatal_error("Unable to lower arguments");
1044   }
1045
1046   // And translate the function!
1047   for (const BasicBlock &BB: F) {
1048     MachineBasicBlock &MBB = getOrCreateBB(BB);
1049     // Set the insertion point of all the following translations to
1050     // the end of this basic block.
1051     CurBuilder.setMBB(MBB);
1052
1053     for (const Instruction &Inst: BB) {
1054       Succeeded &= translate(Inst);
1055       if (!Succeeded) {
1056         if (TPC->isGlobalISelAbortEnabled())
1057           reportTranslationError(Inst, "unable to translate instruction");
1058         MF->getProperties().set(
1059             MachineFunctionProperties::Property::FailedISel);
1060         break;
1061       }
1062     }
1063   }
1064
1065   if (Succeeded) {
1066     finishPendingPhis();
1067
1068     // Now that the MachineFrameInfo has been configured, no further changes to
1069     // the reserved registers are possible.
1070     MRI->freezeReservedRegs(*MF);
1071
1072     // Merge the argument lowering and constants block with its single
1073     // successor, the LLVM-IR entry block.  We want the basic block to
1074     // be maximal.
1075     assert(EntryBB->succ_size() == 1 &&
1076            "Custom BB used for lowering should have only one successor");
1077     // Get the successor of the current entry block.
1078     MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1079     assert(NewEntryBB.pred_size() == 1 &&
1080            "LLVM-IR entry block has a predecessor!?");
1081     // Move all the instruction from the current entry block to the
1082     // new entry block.
1083     NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1084                       EntryBB->end());
1085
1086     // Update the live-in information for the new entry block.
1087     for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1088       NewEntryBB.addLiveIn(LiveIn);
1089     NewEntryBB.sortUniqueLiveIns();
1090
1091     // Get rid of the now empty basic block.
1092     EntryBB->removeSuccessor(&NewEntryBB);
1093     MF->remove(EntryBB);
1094     MF->DeleteMachineBasicBlock(EntryBB);
1095
1096     assert(&MF->front() == &NewEntryBB &&
1097            "New entry wasn't next in the list of basic block!");
1098   }
1099
1100   finalizeFunction();
1101
1102   return false;
1103 }