OSDN Git Service

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