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