OSDN Git Service

GlobalISel: drop lifetime intrinsics during translation.
[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   if (!TPC->isGlobalISelAbortEnabled() && LI.isAtomic())
275     return false;
276
277   assert(!LI.isAtomic() && "only non-atomic loads are supported at the moment");
278   auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
279                                : MachineMemOperand::MONone;
280   Flags |= MachineMemOperand::MOLoad;
281
282   unsigned Res = getOrCreateVReg(LI);
283   unsigned Addr = getOrCreateVReg(*LI.getPointerOperand());
284   LLT VTy{*LI.getType(), *DL}, PTy{*LI.getPointerOperand()->getType(), *DL};
285   MIRBuilder.buildLoad(
286       Res, Addr,
287       *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()),
288                                 Flags, DL->getTypeStoreSize(LI.getType()),
289                                 getMemOpAlignment(LI)));
290   return true;
291 }
292
293 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
294   const StoreInst &SI = cast<StoreInst>(U);
295
296   if (!TPC->isGlobalISelAbortEnabled() && SI.isAtomic())
297     return false;
298
299   assert(!SI.isAtomic() && "only non-atomic stores supported at the moment");
300   auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
301                                : MachineMemOperand::MONone;
302   Flags |= MachineMemOperand::MOStore;
303
304   unsigned Val = getOrCreateVReg(*SI.getValueOperand());
305   unsigned Addr = getOrCreateVReg(*SI.getPointerOperand());
306   LLT VTy{*SI.getValueOperand()->getType(), *DL},
307       PTy{*SI.getPointerOperand()->getType(), *DL};
308
309   MIRBuilder.buildStore(
310       Val, Addr,
311       *MF->getMachineMemOperand(
312           MachinePointerInfo(SI.getPointerOperand()), Flags,
313           DL->getTypeStoreSize(SI.getValueOperand()->getType()),
314           getMemOpAlignment(SI)));
315   return true;
316 }
317
318 bool IRTranslator::translateExtractValue(const User &U,
319                                          MachineIRBuilder &MIRBuilder) {
320   const Value *Src = U.getOperand(0);
321   Type *Int32Ty = Type::getInt32Ty(U.getContext());
322   SmallVector<Value *, 1> Indices;
323
324   // getIndexedOffsetInType is designed for GEPs, so the first index is the
325   // usual array element rather than looking into the actual aggregate.
326   Indices.push_back(ConstantInt::get(Int32Ty, 0));
327
328   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
329     for (auto Idx : EVI->indices())
330       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
331   } else {
332     for (unsigned i = 1; i < U.getNumOperands(); ++i)
333       Indices.push_back(U.getOperand(i));
334   }
335
336   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
337
338   unsigned Res = getOrCreateVReg(U);
339   MIRBuilder.buildExtract(Res, Offset, getOrCreateVReg(*Src));
340
341   return true;
342 }
343
344 bool IRTranslator::translateInsertValue(const User &U,
345                                         MachineIRBuilder &MIRBuilder) {
346   const Value *Src = U.getOperand(0);
347   Type *Int32Ty = Type::getInt32Ty(U.getContext());
348   SmallVector<Value *, 1> Indices;
349
350   // getIndexedOffsetInType is designed for GEPs, so the first index is the
351   // usual array element rather than looking into the actual aggregate.
352   Indices.push_back(ConstantInt::get(Int32Ty, 0));
353
354   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
355     for (auto Idx : IVI->indices())
356       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
357   } else {
358     for (unsigned i = 2; i < U.getNumOperands(); ++i)
359       Indices.push_back(U.getOperand(i));
360   }
361
362   uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices);
363
364   unsigned Res = getOrCreateVReg(U);
365   const Value &Inserted = *U.getOperand(1);
366   MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), getOrCreateVReg(Inserted),
367                          Offset);
368
369   return true;
370 }
371
372 bool IRTranslator::translateSelect(const User &U,
373                                    MachineIRBuilder &MIRBuilder) {
374   MIRBuilder.buildSelect(getOrCreateVReg(U), getOrCreateVReg(*U.getOperand(0)),
375                          getOrCreateVReg(*U.getOperand(1)),
376                          getOrCreateVReg(*U.getOperand(2)));
377   return true;
378 }
379
380 bool IRTranslator::translateBitCast(const User &U,
381                                     MachineIRBuilder &MIRBuilder) {
382   if (LLT{*U.getOperand(0)->getType(), *DL} == LLT{*U.getType(), *DL}) {
383     unsigned &Reg = ValToVReg[&U];
384     if (Reg)
385       MIRBuilder.buildCopy(Reg, getOrCreateVReg(*U.getOperand(0)));
386     else
387       Reg = getOrCreateVReg(*U.getOperand(0));
388     return true;
389   }
390   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
391 }
392
393 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
394                                  MachineIRBuilder &MIRBuilder) {
395   unsigned Op = getOrCreateVReg(*U.getOperand(0));
396   unsigned Res = getOrCreateVReg(U);
397   MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
398   return true;
399 }
400
401 bool IRTranslator::translateGetElementPtr(const User &U,
402                                           MachineIRBuilder &MIRBuilder) {
403   // FIXME: support vector GEPs.
404   if (U.getType()->isVectorTy())
405     return false;
406
407   Value &Op0 = *U.getOperand(0);
408   unsigned BaseReg = getOrCreateVReg(Op0);
409   LLT PtrTy{*Op0.getType(), *DL};
410   unsigned PtrSize = DL->getPointerSizeInBits(PtrTy.getAddressSpace());
411   LLT OffsetTy = LLT::scalar(PtrSize);
412
413   int64_t Offset = 0;
414   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
415        GTI != E; ++GTI) {
416     const Value *Idx = GTI.getOperand();
417     if (StructType *StTy = GTI.getStructTypeOrNull()) {
418       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
419       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
420       continue;
421     } else {
422       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
423
424       // If this is a scalar constant or a splat vector of constants,
425       // handle it quickly.
426       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
427         Offset += ElementSize * CI->getSExtValue();
428         continue;
429       }
430
431       if (Offset != 0) {
432         unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
433         unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
434         MIRBuilder.buildConstant(OffsetReg, Offset);
435         MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
436
437         BaseReg = NewBaseReg;
438         Offset = 0;
439       }
440
441       // N = N + Idx * ElementSize;
442       unsigned ElementSizeReg = MRI->createGenericVirtualRegister(OffsetTy);
443       MIRBuilder.buildConstant(ElementSizeReg, ElementSize);
444
445       unsigned IdxReg = getOrCreateVReg(*Idx);
446       if (MRI->getType(IdxReg) != OffsetTy) {
447         unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
448         MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
449         IdxReg = NewIdxReg;
450       }
451
452       unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
453       MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg);
454
455       unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
456       MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
457       BaseReg = NewBaseReg;
458     }
459   }
460
461   if (Offset != 0) {
462     unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
463     MIRBuilder.buildConstant(OffsetReg, Offset);
464     MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
465     return true;
466   }
467
468   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
469   return true;
470 }
471
472 bool IRTranslator::translateMemfunc(const CallInst &CI,
473                                     MachineIRBuilder &MIRBuilder,
474                                     unsigned ID) {
475   LLT SizeTy{*CI.getArgOperand(2)->getType(), *DL};
476   Type *DstTy = CI.getArgOperand(0)->getType();
477   if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
478       SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
479     return false;
480
481   SmallVector<CallLowering::ArgInfo, 8> Args;
482   for (int i = 0; i < 3; ++i) {
483     const auto &Arg = CI.getArgOperand(i);
484     Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
485   }
486
487   const char *Callee;
488   switch (ID) {
489   case Intrinsic::memmove:
490   case Intrinsic::memcpy: {
491     Type *SrcTy = CI.getArgOperand(1)->getType();
492     if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
493       return false;
494     Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
495     break;
496   }
497   case Intrinsic::memset:
498     Callee = "memset";
499     break;
500   default:
501     return false;
502   }
503
504   return CLI->lowerCall(MIRBuilder, MachineOperand::CreateES(Callee),
505                         CallLowering::ArgInfo(0, CI.getType()), Args);
506 }
507
508 void IRTranslator::getStackGuard(unsigned DstReg,
509                                  MachineIRBuilder &MIRBuilder) {
510   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
511   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
512   auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
513   MIB.addDef(DstReg);
514
515   auto &TLI = *MF->getSubtarget().getTargetLowering();
516   Value *Global = TLI.getSDagStackGuard(*MF->getFunction()->getParent());
517   if (!Global)
518     return;
519
520   MachinePointerInfo MPInfo(Global);
521   MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1);
522   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
523                MachineMemOperand::MODereferenceable;
524   *MemRefs =
525       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
526                                DL->getPointerABIAlignment());
527   MIB.setMemRefs(MemRefs, MemRefs + 1);
528 }
529
530 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
531                                               MachineIRBuilder &MIRBuilder) {
532   LLT Ty{*CI.getOperand(0)->getType(), *DL};
533   LLT s1 = LLT::scalar(1);
534   unsigned Width = Ty.getSizeInBits();
535   unsigned Res = MRI->createGenericVirtualRegister(Ty);
536   unsigned Overflow = MRI->createGenericVirtualRegister(s1);
537   auto MIB = MIRBuilder.buildInstr(Op)
538                  .addDef(Res)
539                  .addDef(Overflow)
540                  .addUse(getOrCreateVReg(*CI.getOperand(0)))
541                  .addUse(getOrCreateVReg(*CI.getOperand(1)));
542
543   if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
544     unsigned Zero = MRI->createGenericVirtualRegister(s1);
545     EntryBuilder.buildConstant(Zero, 0);
546     MIB.addUse(Zero);
547   }
548
549   MIRBuilder.buildSequence(getOrCreateVReg(CI), Res, 0, Overflow, Width);
550   return true;
551 }
552
553 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
554                                            MachineIRBuilder &MIRBuilder) {
555   switch (ID) {
556   default:
557     break;
558   case Intrinsic::lifetime_start:
559   case Intrinsic::lifetime_end:
560     // Stack coloring is not enabled in O0 (which we care about now) so we can
561     // drop these. Make sure someone notices when we start compiling at higher
562     // opts though.
563     if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
564       return false;
565     return true;
566   case Intrinsic::dbg_declare: {
567     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
568     assert(DI.getVariable() && "Missing variable");
569
570     const Value *Address = DI.getAddress();
571     if (!Address || isa<UndefValue>(Address)) {
572       DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
573       return true;
574     }
575
576     unsigned Reg = getOrCreateVReg(*Address);
577     auto RegDef = MRI->def_instr_begin(Reg);
578     assert(DI.getVariable()->isValidLocationForIntrinsic(
579                MIRBuilder.getDebugLoc()) &&
580            "Expected inlined-at fields to agree");
581
582     if (RegDef != MRI->def_instr_end() &&
583         RegDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
584       MIRBuilder.buildFIDbgValue(RegDef->getOperand(1).getIndex(),
585                                  DI.getVariable(), DI.getExpression());
586     } else
587       MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
588     return true;
589   }
590   case Intrinsic::vaend:
591     // No target I know of cares about va_end. Certainly no in-tree target
592     // does. Simplest intrinsic ever!
593     return true;
594   case Intrinsic::vastart: {
595     auto &TLI = *MF->getSubtarget().getTargetLowering();
596     Value *Ptr = CI.getArgOperand(0);
597     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
598
599     MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
600         .addUse(getOrCreateVReg(*Ptr))
601         .addMemOperand(MF->getMachineMemOperand(
602             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
603     return true;
604   }
605   case Intrinsic::dbg_value: {
606     // This form of DBG_VALUE is target-independent.
607     const DbgValueInst &DI = cast<DbgValueInst>(CI);
608     const Value *V = DI.getValue();
609     assert(DI.getVariable()->isValidLocationForIntrinsic(
610                MIRBuilder.getDebugLoc()) &&
611            "Expected inlined-at fields to agree");
612     if (!V) {
613       // Currently the optimizer can produce this; insert an undef to
614       // help debugging.  Probably the optimizer should not do this.
615       MIRBuilder.buildIndirectDbgValue(0, DI.getOffset(), DI.getVariable(),
616                                        DI.getExpression());
617     } else if (const auto *CI = dyn_cast<Constant>(V)) {
618       MIRBuilder.buildConstDbgValue(*CI, DI.getOffset(), DI.getVariable(),
619                                     DI.getExpression());
620     } else {
621       unsigned Reg = getOrCreateVReg(*V);
622       // FIXME: This does not handle register-indirect values at offset 0. The
623       // direct/indirect thing shouldn't really be handled by something as
624       // implicit as reg+noreg vs reg+imm in the first palce, but it seems
625       // pretty baked in right now.
626       if (DI.getOffset() != 0)
627         MIRBuilder.buildIndirectDbgValue(Reg, DI.getOffset(), DI.getVariable(),
628                                          DI.getExpression());
629       else
630         MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(),
631                                        DI.getExpression());
632     }
633     return true;
634   }
635   case Intrinsic::uadd_with_overflow:
636     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
637   case Intrinsic::sadd_with_overflow:
638     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
639   case Intrinsic::usub_with_overflow:
640     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
641   case Intrinsic::ssub_with_overflow:
642     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
643   case Intrinsic::umul_with_overflow:
644     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
645   case Intrinsic::smul_with_overflow:
646     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
647   case Intrinsic::pow:
648     MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
649         .addDef(getOrCreateVReg(CI))
650         .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
651         .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
652     return true;
653   case Intrinsic::memcpy:
654   case Intrinsic::memmove:
655   case Intrinsic::memset:
656     return translateMemfunc(CI, MIRBuilder, ID);
657   case Intrinsic::eh_typeid_for: {
658     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
659     unsigned Reg = getOrCreateVReg(CI);
660     unsigned TypeID = MF->getTypeIDFor(GV);
661     MIRBuilder.buildConstant(Reg, TypeID);
662     return true;
663   }
664   case Intrinsic::objectsize: {
665     // If we don't know by now, we're never going to know.
666     const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
667
668     MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
669     return true;
670   }
671   case Intrinsic::stackguard:
672     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
673     return true;
674   case Intrinsic::stackprotector: {
675     LLT PtrTy{*CI.getArgOperand(0)->getType(), *DL};
676     unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
677     getStackGuard(GuardVal, MIRBuilder);
678
679     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
680     MIRBuilder.buildStore(
681         GuardVal, getOrCreateVReg(*Slot),
682         *MF->getMachineMemOperand(
683             MachinePointerInfo::getFixedStack(*MF,
684                                               getOrCreateFrameIndex(*Slot)),
685             MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
686             PtrTy.getSizeInBits() / 8, 8));
687     return true;
688   }
689   }
690   return false;
691 }
692
693 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
694   const CallInst &CI = cast<CallInst>(U);
695   auto TII = MF->getTarget().getIntrinsicInfo();
696   const Function *F = CI.getCalledFunction();
697
698   if (CI.isInlineAsm())
699     return false;
700
701   if (!F || !F->isIntrinsic()) {
702     unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
703     SmallVector<unsigned, 8> Args;
704     for (auto &Arg: CI.arg_operands())
705       Args.push_back(getOrCreateVReg(*Arg));
706
707     return CLI->lowerCall(MIRBuilder, CI, Res, Args, [&]() {
708       return getOrCreateVReg(*CI.getCalledValue());
709     });
710   }
711
712   Intrinsic::ID ID = F->getIntrinsicID();
713   if (TII && ID == Intrinsic::not_intrinsic)
714     ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
715
716   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
717
718   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
719     return true;
720
721   unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI);
722   MachineInstrBuilder MIB =
723       MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
724
725   for (auto &Arg : CI.arg_operands()) {
726     if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg))
727       MIB.addImm(CI->getSExtValue());
728     else
729       MIB.addUse(getOrCreateVReg(*Arg));
730   }
731   return true;
732 }
733
734 bool IRTranslator::translateInvoke(const User &U,
735                                    MachineIRBuilder &MIRBuilder) {
736   const InvokeInst &I = cast<InvokeInst>(U);
737   MCContext &Context = MF->getContext();
738
739   const BasicBlock *ReturnBB = I.getSuccessor(0);
740   const BasicBlock *EHPadBB = I.getSuccessor(1);
741
742   const Value *Callee(I.getCalledValue());
743   const Function *Fn = dyn_cast<Function>(Callee);
744   if (isa<InlineAsm>(Callee))
745     return false;
746
747   // FIXME: support invoking patchpoint and statepoint intrinsics.
748   if (Fn && Fn->isIntrinsic())
749     return false;
750
751   // FIXME: support whatever these are.
752   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
753     return false;
754
755   // FIXME: support Windows exception handling.
756   if (!isa<LandingPadInst>(EHPadBB->front()))
757     return false;
758
759
760   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
761   // the region covered by the try.
762   MCSymbol *BeginSymbol = Context.createTempSymbol();
763   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
764
765   unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I);
766   SmallVector<unsigned, 8> Args;
767   for (auto &Arg: I.arg_operands())
768     Args.push_back(getOrCreateVReg(*Arg));
769
770  CLI->lowerCall(MIRBuilder, I, Res, Args,
771                  [&]() { return getOrCreateVReg(*I.getCalledValue()); });
772
773   MCSymbol *EndSymbol = Context.createTempSymbol();
774   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
775
776   // FIXME: track probabilities.
777   MachineBasicBlock &EHPadMBB = getOrCreateBB(*EHPadBB),
778                     &ReturnMBB = getOrCreateBB(*ReturnBB);
779   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
780   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
781   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
782   MIRBuilder.buildBr(ReturnMBB);
783
784   return true;
785 }
786
787 bool IRTranslator::translateLandingPad(const User &U,
788                                        MachineIRBuilder &MIRBuilder) {
789   const LandingPadInst &LP = cast<LandingPadInst>(U);
790
791   MachineBasicBlock &MBB = MIRBuilder.getMBB();
792   addLandingPadInfo(LP, MBB);
793
794   MBB.setIsEHPad();
795
796   // If there aren't registers to copy the values into (e.g., during SjLj
797   // exceptions), then don't bother.
798   auto &TLI = *MF->getSubtarget().getTargetLowering();
799   const Constant *PersonalityFn = MF->getFunction()->getPersonalityFn();
800   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
801       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
802     return true;
803
804   // If landingpad's return type is token type, we don't create DAG nodes
805   // for its exception pointer and selector value. The extraction of exception
806   // pointer or selector value from token type landingpads is not currently
807   // supported.
808   if (LP.getType()->isTokenTy())
809     return true;
810
811   // Add a label to mark the beginning of the landing pad.  Deletion of the
812   // landing pad can thus be detected via the MachineModuleInfo.
813   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
814     .addSym(MF->addLandingPad(&MBB));
815
816   SmallVector<LLT, 2> Tys;
817   for (Type *Ty : cast<StructType>(LP.getType())->elements())
818     Tys.push_back(LLT{*Ty, *DL});
819   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
820
821   // Mark exception register as live in.
822   SmallVector<unsigned, 2> Regs;
823   SmallVector<uint64_t, 2> Offsets;
824   if (unsigned Reg = TLI.getExceptionPointerRegister(PersonalityFn)) {
825     MBB.addLiveIn(Reg);
826     unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]);
827     MIRBuilder.buildCopy(VReg, Reg);
828     Regs.push_back(VReg);
829     Offsets.push_back(0);
830   }
831
832   if (unsigned Reg = TLI.getExceptionSelectorRegister(PersonalityFn)) {
833     MBB.addLiveIn(Reg);
834
835     // N.b. the exception selector register always has pointer type and may not
836     // match the actual IR-level type in the landingpad so an extra cast is
837     // needed.
838     unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
839     MIRBuilder.buildCopy(PtrVReg, Reg);
840
841     unsigned VReg = MRI->createGenericVirtualRegister(Tys[1]);
842     MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT)
843         .addDef(VReg)
844         .addUse(PtrVReg);
845     Regs.push_back(VReg);
846     Offsets.push_back(Tys[0].getSizeInBits());
847   }
848
849   MIRBuilder.buildSequence(getOrCreateVReg(LP), Regs, Offsets);
850   return true;
851 }
852
853 bool IRTranslator::translateAlloca(const User &U,
854                                    MachineIRBuilder &MIRBuilder) {
855   auto &AI = cast<AllocaInst>(U);
856
857   if (AI.isStaticAlloca()) {
858     unsigned Res = getOrCreateVReg(AI);
859     int FI = getOrCreateFrameIndex(AI);
860     MIRBuilder.buildFrameIndex(Res, FI);
861     return true;
862   }
863
864   // Now we're in the harder dynamic case.
865   Type *Ty = AI.getAllocatedType();
866   unsigned Align =
867       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
868
869   unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
870
871   LLT IntPtrTy = LLT::scalar(DL->getPointerSizeInBits());
872   if (MRI->getType(NumElts) != IntPtrTy) {
873     unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
874     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
875     NumElts = ExtElts;
876   }
877
878   unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
879   unsigned TySize = MRI->createGenericVirtualRegister(IntPtrTy);
880   MIRBuilder.buildConstant(TySize, DL->getTypeAllocSize(Ty));
881   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
882
883   LLT PtrTy = LLT{*AI.getType(), *DL};
884   auto &TLI = *MF->getSubtarget().getTargetLowering();
885   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
886
887   unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
888   MIRBuilder.buildCopy(SPTmp, SPReg);
889
890   unsigned SPInt = MRI->createGenericVirtualRegister(IntPtrTy);
891   MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(SPInt).addUse(SPTmp);
892
893   unsigned AllocInt = MRI->createGenericVirtualRegister(IntPtrTy);
894   MIRBuilder.buildSub(AllocInt, SPInt, AllocSize);
895
896   // Handle alignment. We have to realign if the allocation granule was smaller
897   // than stack alignment, or the specific alloca requires more than stack
898   // alignment.
899   unsigned StackAlign =
900       MF->getSubtarget().getFrameLowering()->getStackAlignment();
901   Align = std::max(Align, StackAlign);
902   if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
903     // Round the size of the allocation up to the stack alignment size
904     // by add SA-1 to the size. This doesn't overflow because we're computing
905     // an address inside an alloca.
906     unsigned TmpSize = MRI->createGenericVirtualRegister(IntPtrTy);
907     unsigned AlignMinus1 = MRI->createGenericVirtualRegister(IntPtrTy);
908     MIRBuilder.buildConstant(AlignMinus1, Align - 1);
909     MIRBuilder.buildSub(TmpSize, AllocInt, AlignMinus1);
910
911     unsigned AlignedAlloc = MRI->createGenericVirtualRegister(IntPtrTy);
912     unsigned AlignMask = MRI->createGenericVirtualRegister(IntPtrTy);
913     MIRBuilder.buildConstant(AlignMask, -(uint64_t)Align);
914     MIRBuilder.buildAnd(AlignedAlloc, TmpSize, AlignMask);
915
916     AllocInt = AlignedAlloc;
917   }
918
919   unsigned DstReg = getOrCreateVReg(AI);
920   MIRBuilder.buildInstr(TargetOpcode::G_INTTOPTR)
921       .addDef(DstReg)
922       .addUse(AllocInt);
923
924   MIRBuilder.buildCopy(SPReg, DstReg);
925
926   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
927   assert(MF->getFrameInfo().hasVarSizedObjects());
928   return true;
929 }
930
931 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
932   const PHINode &PI = cast<PHINode>(U);
933   auto MIB = MIRBuilder.buildInstr(TargetOpcode::PHI);
934   MIB.addDef(getOrCreateVReg(PI));
935
936   PendingPHIs.emplace_back(&PI, MIB.getInstr());
937   return true;
938 }
939
940 void IRTranslator::finishPendingPhis() {
941   for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) {
942     const PHINode *PI = Phi.first;
943     MachineInstrBuilder MIB(*MF, Phi.second);
944
945     // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
946     // won't create extra control flow here, otherwise we need to find the
947     // dominating predecessor here (or perhaps force the weirder IRTranslators
948     // to provide a simple boundary).
949     SmallSet<const BasicBlock *, 4> HandledPreds;
950
951     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
952       auto IRPred = PI->getIncomingBlock(i);
953       if (HandledPreds.count(IRPred))
954         continue;
955
956       HandledPreds.insert(IRPred);
957       unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i));
958       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
959         assert(Pred->isSuccessor(MIB->getParent()) &&
960                "incorrect CFG at MachineBasicBlock level");
961         MIB.addUse(ValReg);
962         MIB.addMBB(Pred);
963       }
964     }
965   }
966 }
967
968 bool IRTranslator::translate(const Instruction &Inst) {
969   CurBuilder.setDebugLoc(Inst.getDebugLoc());
970   switch(Inst.getOpcode()) {
971 #define HANDLE_INST(NUM, OPCODE, CLASS) \
972     case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
973 #include "llvm/IR/Instruction.def"
974   default:
975     if (!TPC->isGlobalISelAbortEnabled())
976       return false;
977     llvm_unreachable("unknown opcode");
978   }
979 }
980
981 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
982   if (auto CI = dyn_cast<ConstantInt>(&C))
983     EntryBuilder.buildConstant(Reg, *CI);
984   else if (auto CF = dyn_cast<ConstantFP>(&C))
985     EntryBuilder.buildFConstant(Reg, *CF);
986   else if (isa<UndefValue>(C))
987     EntryBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(Reg);
988   else if (isa<ConstantPointerNull>(C))
989     EntryBuilder.buildConstant(Reg, 0);
990   else if (auto GV = dyn_cast<GlobalValue>(&C))
991     EntryBuilder.buildGlobalValue(Reg, GV);
992   else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
993     switch(CE->getOpcode()) {
994 #define HANDLE_INST(NUM, OPCODE, CLASS)                         \
995       case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
996 #include "llvm/IR/Instruction.def"
997     default:
998       if (!TPC->isGlobalISelAbortEnabled())
999         return false;
1000       llvm_unreachable("unknown opcode");
1001     }
1002   } else if (!TPC->isGlobalISelAbortEnabled())
1003     return false;
1004   else
1005     llvm_unreachable("unhandled constant kind");
1006
1007   return true;
1008 }
1009
1010 void IRTranslator::finalizeFunction() {
1011   // Release the memory used by the different maps we
1012   // needed during the translation.
1013   PendingPHIs.clear();
1014   ValToVReg.clear();
1015   FrameIndices.clear();
1016   Constants.clear();
1017   MachinePreds.clear();
1018 }
1019
1020 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
1021   MF = &CurMF;
1022   const Function &F = *MF->getFunction();
1023   if (F.empty())
1024     return false;
1025   CLI = MF->getSubtarget().getCallLowering();
1026   CurBuilder.setMF(*MF);
1027   EntryBuilder.setMF(*MF);
1028   MRI = &MF->getRegInfo();
1029   DL = &F.getParent()->getDataLayout();
1030   TPC = &getAnalysis<TargetPassConfig>();
1031
1032   assert(PendingPHIs.empty() && "stale PHIs");
1033
1034   // Setup a separate basic-block for the arguments and constants, falling
1035   // through to the IR-level Function's entry block.
1036   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1037   MF->push_back(EntryBB);
1038   EntryBB->addSuccessor(&getOrCreateBB(F.front()));
1039   EntryBuilder.setMBB(*EntryBB);
1040
1041   // Lower the actual args into this basic block.
1042   SmallVector<unsigned, 8> VRegArgs;
1043   for (const Argument &Arg: F.args())
1044     VRegArgs.push_back(getOrCreateVReg(Arg));
1045   bool Succeeded = CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs);
1046   if (!Succeeded) {
1047     if (!TPC->isGlobalISelAbortEnabled()) {
1048       MF->getProperties().set(
1049           MachineFunctionProperties::Property::FailedISel);
1050       finalizeFunction();
1051       return false;
1052     }
1053     report_fatal_error("Unable to lower arguments");
1054   }
1055
1056   // And translate the function!
1057   for (const BasicBlock &BB: F) {
1058     MachineBasicBlock &MBB = getOrCreateBB(BB);
1059     // Set the insertion point of all the following translations to
1060     // the end of this basic block.
1061     CurBuilder.setMBB(MBB);
1062
1063     for (const Instruction &Inst: BB) {
1064       Succeeded &= translate(Inst);
1065       if (!Succeeded) {
1066         if (TPC->isGlobalISelAbortEnabled())
1067           reportTranslationError(Inst, "unable to translate instruction");
1068         MF->getProperties().set(
1069             MachineFunctionProperties::Property::FailedISel);
1070         break;
1071       }
1072     }
1073   }
1074
1075   if (Succeeded) {
1076     finishPendingPhis();
1077
1078     // Now that the MachineFrameInfo has been configured, no further changes to
1079     // the reserved registers are possible.
1080     MRI->freezeReservedRegs(*MF);
1081
1082     // Merge the argument lowering and constants block with its single
1083     // successor, the LLVM-IR entry block.  We want the basic block to
1084     // be maximal.
1085     assert(EntryBB->succ_size() == 1 &&
1086            "Custom BB used for lowering should have only one successor");
1087     // Get the successor of the current entry block.
1088     MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1089     assert(NewEntryBB.pred_size() == 1 &&
1090            "LLVM-IR entry block has a predecessor!?");
1091     // Move all the instruction from the current entry block to the
1092     // new entry block.
1093     NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1094                       EntryBB->end());
1095
1096     // Update the live-in information for the new entry block.
1097     for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1098       NewEntryBB.addLiveIn(LiveIn);
1099     NewEntryBB.sortUniqueLiveIns();
1100
1101     // Get rid of the now empty basic block.
1102     EntryBB->removeSuccessor(&NewEntryBB);
1103     MF->remove(EntryBB);
1104     MF->DeleteMachineBasicBlock(EntryBB);
1105
1106     assert(&MF->front() == &NewEntryBB &&
1107            "New entry wasn't next in the list of basic block!");
1108   }
1109
1110   finalizeFunction();
1111
1112   return false;
1113 }