1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the IRTranslator class.
10 //===----------------------------------------------------------------------===//
11 
12 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
13 #include "llvm/ADT/PostOrderIterator.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/BranchProbabilityInfo.h"
19 #include "llvm/Analysis/Loads.h"
20 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
25 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
26 #include "llvm/CodeGen/LowLevelType.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineMemOperand.h"
32 #include "llvm/CodeGen/MachineOperand.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/StackProtector.h"
35 #include "llvm/CodeGen/TargetFrameLowering.h"
36 #include "llvm/CodeGen/TargetInstrInfo.h"
37 #include "llvm/CodeGen/TargetLowering.h"
38 #include "llvm/CodeGen/TargetPassConfig.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/IR/BasicBlock.h"
42 #include "llvm/IR/CFG.h"
43 #include "llvm/IR/Constant.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugInfo.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GetElementPtrTypeIterator.h"
50 #include "llvm/IR/InlineAsm.h"
51 #include "llvm/IR/InstrTypes.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/IntrinsicInst.h"
54 #include "llvm/IR/Intrinsics.h"
55 #include "llvm/IR/LLVMContext.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/User.h"
59 #include "llvm/IR/Value.h"
60 #include "llvm/InitializePasses.h"
61 #include "llvm/MC/MCContext.h"
62 #include "llvm/Pass.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CodeGen.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/LowLevelTypeImpl.h"
68 #include "llvm/Support/MathExtras.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetIntrinsicInfo.h"
71 #include "llvm/Target/TargetMachine.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <iterator>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 #define DEBUG_TYPE "irtranslator"
81 
82 using namespace llvm;
83 
84 static cl::opt<bool>
85     EnableCSEInIRTranslator("enable-cse-in-irtranslator",
86                             cl::desc("Should enable CSE in irtranslator"),
87                             cl::Optional, cl::init(false));
88 char IRTranslator::ID = 0;
89 
90 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
91                 false, false)
92 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
93 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass)
94 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
95                 false, false)
96 
97 static void reportTranslationError(MachineFunction &MF,
98                                    const TargetPassConfig &TPC,
99                                    OptimizationRemarkEmitter &ORE,
100                                    OptimizationRemarkMissed &R) {
101   MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
102 
103   // Print the function name explicitly if we don't have a debug location (which
104   // makes the diagnostic less useful) or if we're going to emit a raw error.
105   if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
106     R << (" (in function: " + MF.getName() + ")").str();
107 
108   if (TPC.isGlobalISelAbortEnabled())
109     report_fatal_error(R.getMsg());
110   else
111     ORE.emit(R);
112 }
113 
114 IRTranslator::IRTranslator() : MachineFunctionPass(ID) { }
115 
116 #ifndef NDEBUG
117 namespace {
118 /// Verify that every instruction created has the same DILocation as the
119 /// instruction being translated.
120 class DILocationVerifier : public GISelChangeObserver {
121   const Instruction *CurrInst = nullptr;
122 
123 public:
124   DILocationVerifier() = default;
125   ~DILocationVerifier() = default;
126 
127   const Instruction *getCurrentInst() const { return CurrInst; }
128   void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; }
129 
130   void erasingInstr(MachineInstr &MI) override {}
131   void changingInstr(MachineInstr &MI) override {}
132   void changedInstr(MachineInstr &MI) override {}
133 
134   void createdInstr(MachineInstr &MI) override {
135     assert(getCurrentInst() && "Inserted instruction without a current MI");
136 
137     // Only print the check message if we're actually checking it.
138 #ifndef NDEBUG
139     LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst
140                       << " was copied to " << MI);
141 #endif
142     // We allow insts in the entry block to have a debug loc line of 0 because
143     // they could have originated from constants, and we don't want a jumpy
144     // debug experience.
145     assert((CurrInst->getDebugLoc() == MI.getDebugLoc() ||
146             MI.getDebugLoc().getLine() == 0) &&
147            "Line info was not transferred to all instructions");
148   }
149 };
150 } // namespace
151 #endif // ifndef NDEBUG
152 
153 
154 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const {
155   AU.addRequired<StackProtector>();
156   AU.addRequired<TargetPassConfig>();
157   AU.addRequired<GISelCSEAnalysisWrapperPass>();
158   getSelectionDAGFallbackAnalysisUsage(AU);
159   MachineFunctionPass::getAnalysisUsage(AU);
160 }
161 
162 IRTranslator::ValueToVRegInfo::VRegListT &
163 IRTranslator::allocateVRegs(const Value &Val) {
164   assert(!VMap.contains(Val) && "Value already allocated in VMap");
165   auto *Regs = VMap.getVRegs(Val);
166   auto *Offsets = VMap.getOffsets(Val);
167   SmallVector<LLT, 4> SplitTys;
168   computeValueLLTs(*DL, *Val.getType(), SplitTys,
169                    Offsets->empty() ? Offsets : nullptr);
170   for (unsigned i = 0; i < SplitTys.size(); ++i)
171     Regs->push_back(0);
172   return *Regs;
173 }
174 
175 ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) {
176   auto VRegsIt = VMap.findVRegs(Val);
177   if (VRegsIt != VMap.vregs_end())
178     return *VRegsIt->second;
179 
180   if (Val.getType()->isVoidTy())
181     return *VMap.getVRegs(Val);
182 
183   // Create entry for this type.
184   auto *VRegs = VMap.getVRegs(Val);
185   auto *Offsets = VMap.getOffsets(Val);
186 
187   assert(Val.getType()->isSized() &&
188          "Don't know how to create an empty vreg");
189 
190   SmallVector<LLT, 4> SplitTys;
191   computeValueLLTs(*DL, *Val.getType(), SplitTys,
192                    Offsets->empty() ? Offsets : nullptr);
193 
194   if (!isa<Constant>(Val)) {
195     for (auto Ty : SplitTys)
196       VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
197     return *VRegs;
198   }
199 
200   if (Val.getType()->isAggregateType()) {
201     // UndefValue, ConstantAggregateZero
202     auto &C = cast<Constant>(Val);
203     unsigned Idx = 0;
204     while (auto Elt = C.getAggregateElement(Idx++)) {
205       auto EltRegs = getOrCreateVRegs(*Elt);
206       llvm::copy(EltRegs, std::back_inserter(*VRegs));
207     }
208   } else {
209     assert(SplitTys.size() == 1 && "unexpectedly split LLT");
210     VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
211     bool Success = translate(cast<Constant>(Val), VRegs->front());
212     if (!Success) {
213       OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
214                                  MF->getFunction().getSubprogram(),
215                                  &MF->getFunction().getEntryBlock());
216       R << "unable to translate constant: " << ore::NV("Type", Val.getType());
217       reportTranslationError(*MF, *TPC, *ORE, R);
218       return *VRegs;
219     }
220   }
221 
222   return *VRegs;
223 }
224 
225 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
226   if (FrameIndices.find(&AI) != FrameIndices.end())
227     return FrameIndices[&AI];
228 
229   uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType());
230   uint64_t Size =
231       ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
232 
233   // Always allocate at least one byte.
234   Size = std::max<uint64_t>(Size, 1u);
235 
236   unsigned Alignment = AI.getAlignment();
237   if (!Alignment)
238     Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
239 
240   int &FI = FrameIndices[&AI];
241   FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
242   return FI;
243 }
244 
245 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
246   unsigned Alignment = 0;
247   Type *ValTy = nullptr;
248   if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
249     Alignment = SI->getAlignment();
250     ValTy = SI->getValueOperand()->getType();
251   } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
252     Alignment = LI->getAlignment();
253     ValTy = LI->getType();
254   } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
255     // TODO(PR27168): This instruction has no alignment attribute, but unlike
256     // the default alignment for load/store, the default here is to assume
257     // it has NATURAL alignment, not DataLayout-specified alignment.
258     const DataLayout &DL = AI->getModule()->getDataLayout();
259     Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
260     ValTy = AI->getCompareOperand()->getType();
261   } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
262     // TODO(PR27168): This instruction has no alignment attribute, but unlike
263     // the default alignment for load/store, the default here is to assume
264     // it has NATURAL alignment, not DataLayout-specified alignment.
265     const DataLayout &DL = AI->getModule()->getDataLayout();
266     Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
267     ValTy = AI->getType();
268   } else {
269     OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
270     R << "unable to translate memop: " << ore::NV("Opcode", &I);
271     reportTranslationError(*MF, *TPC, *ORE, R);
272     return 1;
273   }
274 
275   return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
276 }
277 
278 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
279   MachineBasicBlock *&MBB = BBToMBB[&BB];
280   assert(MBB && "BasicBlock was not encountered before");
281   return *MBB;
282 }
283 
284 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
285   assert(NewPred && "new predecessor must be a real MachineBasicBlock");
286   MachinePreds[Edge].push_back(NewPred);
287 }
288 
289 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
290                                      MachineIRBuilder &MIRBuilder) {
291   // Get or create a virtual register for each value.
292   // Unless the value is a Constant => loadimm cst?
293   // or inline constant each time?
294   // Creation of a virtual register needs to have a size.
295   Register Op0 = getOrCreateVReg(*U.getOperand(0));
296   Register Op1 = getOrCreateVReg(*U.getOperand(1));
297   Register Res = getOrCreateVReg(U);
298   uint16_t Flags = 0;
299   if (isa<Instruction>(U)) {
300     const Instruction &I = cast<Instruction>(U);
301     Flags = MachineInstr::copyFlagsFromInstruction(I);
302   }
303 
304   MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags);
305   return true;
306 }
307 
308 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
309   // -0.0 - X --> G_FNEG
310   if (isa<Constant>(U.getOperand(0)) &&
311       U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) {
312     Register Op1 = getOrCreateVReg(*U.getOperand(1));
313     Register Res = getOrCreateVReg(U);
314     uint16_t Flags = 0;
315     if (isa<Instruction>(U)) {
316       const Instruction &I = cast<Instruction>(U);
317       Flags = MachineInstr::copyFlagsFromInstruction(I);
318     }
319     // Negate the last operand of the FSUB
320     MIRBuilder.buildFNeg(Res, Op1, Flags);
321     return true;
322   }
323   return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
324 }
325 
326 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) {
327   Register Op0 = getOrCreateVReg(*U.getOperand(0));
328   Register Res = getOrCreateVReg(U);
329   uint16_t Flags = 0;
330   if (isa<Instruction>(U)) {
331     const Instruction &I = cast<Instruction>(U);
332     Flags = MachineInstr::copyFlagsFromInstruction(I);
333   }
334   MIRBuilder.buildFNeg(Res, Op0, Flags);
335   return true;
336 }
337 
338 bool IRTranslator::translateCompare(const User &U,
339                                     MachineIRBuilder &MIRBuilder) {
340   auto *CI = dyn_cast<CmpInst>(&U);
341   Register Op0 = getOrCreateVReg(*U.getOperand(0));
342   Register Op1 = getOrCreateVReg(*U.getOperand(1));
343   Register Res = getOrCreateVReg(U);
344   CmpInst::Predicate Pred =
345       CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
346                                     cast<ConstantExpr>(U).getPredicate());
347   if (CmpInst::isIntPredicate(Pred))
348     MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
349   else if (Pred == CmpInst::FCMP_FALSE)
350     MIRBuilder.buildCopy(
351         Res, getOrCreateVReg(*Constant::getNullValue(U.getType())));
352   else if (Pred == CmpInst::FCMP_TRUE)
353     MIRBuilder.buildCopy(
354         Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType())));
355   else {
356     assert(CI && "Instruction should be CmpInst");
357     MIRBuilder.buildFCmp(Pred, Res, Op0, Op1,
358                          MachineInstr::copyFlagsFromInstruction(*CI));
359   }
360 
361   return true;
362 }
363 
364 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
365   const ReturnInst &RI = cast<ReturnInst>(U);
366   const Value *Ret = RI.getReturnValue();
367   if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
368     Ret = nullptr;
369 
370   ArrayRef<Register> VRegs;
371   if (Ret)
372     VRegs = getOrCreateVRegs(*Ret);
373 
374   Register SwiftErrorVReg = 0;
375   if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) {
376     SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt(
377         &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg());
378   }
379 
380   // The target may mess up with the insertion point, but
381   // this is not important as a return is the last instruction
382   // of the block anyway.
383   return CLI->lowerReturn(MIRBuilder, Ret, VRegs, SwiftErrorVReg);
384 }
385 
386 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
387   const BranchInst &BrInst = cast<BranchInst>(U);
388   unsigned Succ = 0;
389   if (!BrInst.isUnconditional()) {
390     // We want a G_BRCOND to the true BB followed by an unconditional branch.
391     Register Tst = getOrCreateVReg(*BrInst.getCondition());
392     const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
393     MachineBasicBlock &TrueBB = getMBB(TrueTgt);
394     MIRBuilder.buildBrCond(Tst, TrueBB);
395   }
396 
397   const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
398   MachineBasicBlock &TgtBB = getMBB(BrTgt);
399   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
400 
401   // If the unconditional target is the layout successor, fallthrough.
402   if (!CurBB.isLayoutSuccessor(&TgtBB))
403     MIRBuilder.buildBr(TgtBB);
404 
405   // Link successors.
406   for (const BasicBlock *Succ : successors(&BrInst))
407     CurBB.addSuccessor(&getMBB(*Succ));
408   return true;
409 }
410 
411 void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src,
412                                         MachineBasicBlock *Dst,
413                                         BranchProbability Prob) {
414   if (!FuncInfo.BPI) {
415     Src->addSuccessorWithoutProb(Dst);
416     return;
417   }
418   if (Prob.isUnknown())
419     Prob = getEdgeProbability(Src, Dst);
420   Src->addSuccessor(Dst, Prob);
421 }
422 
423 BranchProbability
424 IRTranslator::getEdgeProbability(const MachineBasicBlock *Src,
425                                  const MachineBasicBlock *Dst) const {
426   const BasicBlock *SrcBB = Src->getBasicBlock();
427   const BasicBlock *DstBB = Dst->getBasicBlock();
428   if (!FuncInfo.BPI) {
429     // If BPI is not available, set the default probability as 1 / N, where N is
430     // the number of successors.
431     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
432     return BranchProbability(1, SuccSize);
433   }
434   return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB);
435 }
436 
437 bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) {
438   using namespace SwitchCG;
439   // Extract cases from the switch.
440   const SwitchInst &SI = cast<SwitchInst>(U);
441   BranchProbabilityInfo *BPI = FuncInfo.BPI;
442   CaseClusterVector Clusters;
443   Clusters.reserve(SI.getNumCases());
444   for (auto &I : SI.cases()) {
445     MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor());
446     assert(Succ && "Could not find successor mbb in mapping");
447     const ConstantInt *CaseVal = I.getCaseValue();
448     BranchProbability Prob =
449         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
450             : BranchProbability(1, SI.getNumCases() + 1);
451     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
452   }
453 
454   MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest());
455 
456   // Cluster adjacent cases with the same destination. We do this at all
457   // optimization levels because it's cheap to do and will make codegen faster
458   // if there are many clusters.
459   sortAndRangeify(Clusters);
460 
461   MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent());
462 
463   // If there is only the default destination, jump there directly.
464   if (Clusters.empty()) {
465     SwitchMBB->addSuccessor(DefaultMBB);
466     if (DefaultMBB != SwitchMBB->getNextNode())
467       MIB.buildBr(*DefaultMBB);
468     return true;
469   }
470 
471   SL->findJumpTables(Clusters, &SI, DefaultMBB, nullptr, nullptr);
472 
473   LLVM_DEBUG({
474     dbgs() << "Case clusters: ";
475     for (const CaseCluster &C : Clusters) {
476       if (C.Kind == CC_JumpTable)
477         dbgs() << "JT:";
478       if (C.Kind == CC_BitTests)
479         dbgs() << "BT:";
480 
481       C.Low->getValue().print(dbgs(), true);
482       if (C.Low != C.High) {
483         dbgs() << '-';
484         C.High->getValue().print(dbgs(), true);
485       }
486       dbgs() << ' ';
487     }
488     dbgs() << '\n';
489   });
490 
491   assert(!Clusters.empty());
492   SwitchWorkList WorkList;
493   CaseClusterIt First = Clusters.begin();
494   CaseClusterIt Last = Clusters.end() - 1;
495   auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB);
496   WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
497 
498   // FIXME: At the moment we don't do any splitting optimizations here like
499   // SelectionDAG does, so this worklist only has one entry.
500   while (!WorkList.empty()) {
501     SwitchWorkListItem W = WorkList.back();
502     WorkList.pop_back();
503     if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB))
504       return false;
505   }
506   return true;
507 }
508 
509 void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT,
510                                  MachineBasicBlock *MBB) {
511   // Emit the code for the jump table
512   assert(JT.Reg != -1U && "Should lower JT Header first!");
513   MachineIRBuilder MIB(*MBB->getParent());
514   MIB.setMBB(*MBB);
515   MIB.setDebugLoc(CurBuilder->getDebugLoc());
516 
517   Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext());
518   const LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
519 
520   auto Table = MIB.buildJumpTable(PtrTy, JT.JTI);
521   MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg);
522 }
523 
524 bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT,
525                                        SwitchCG::JumpTableHeader &JTH,
526                                        MachineBasicBlock *HeaderBB) {
527   MachineIRBuilder MIB(*HeaderBB->getParent());
528   MIB.setMBB(*HeaderBB);
529   MIB.setDebugLoc(CurBuilder->getDebugLoc());
530 
531   const Value &SValue = *JTH.SValue;
532   // Subtract the lowest switch case value from the value being switched on.
533   const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL);
534   Register SwitchOpReg = getOrCreateVReg(SValue);
535   auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First);
536   auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst);
537 
538   // This value may be smaller or larger than the target's pointer type, and
539   // therefore require extension or truncating.
540   Type *PtrIRTy = SValue.getType()->getPointerTo();
541   const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy));
542   Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub);
543 
544   JT.Reg = Sub.getReg(0);
545 
546   if (JTH.OmitRangeCheck) {
547     if (JT.MBB != HeaderBB->getNextNode())
548       MIB.buildBr(*JT.MBB);
549     return true;
550   }
551 
552   // Emit the range check for the jump table, and branch to the default block
553   // for the switch statement if the value being switched on exceeds the
554   // largest case in the switch.
555   auto Cst = getOrCreateVReg(
556       *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First));
557   Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0);
558   auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst);
559 
560   auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default);
561 
562   // Avoid emitting unnecessary branches to the next block.
563   if (JT.MBB != HeaderBB->getNextNode())
564     BrCond = MIB.buildBr(*JT.MBB);
565   return true;
566 }
567 
568 void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB,
569                                   MachineBasicBlock *SwitchBB,
570                                   MachineIRBuilder &MIB) {
571   Register CondLHS = getOrCreateVReg(*CB.CmpLHS);
572   Register Cond;
573   DebugLoc OldDbgLoc = MIB.getDebugLoc();
574   MIB.setDebugLoc(CB.DbgLoc);
575   MIB.setMBB(*CB.ThisBB);
576 
577   if (CB.PredInfo.NoCmp) {
578     // Branch or fall through to TrueBB.
579     addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
580     addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
581                       CB.ThisBB);
582     CB.ThisBB->normalizeSuccProbs();
583     if (CB.TrueBB != CB.ThisBB->getNextNode())
584       MIB.buildBr(*CB.TrueBB);
585     MIB.setDebugLoc(OldDbgLoc);
586     return;
587   }
588 
589   const LLT i1Ty = LLT::scalar(1);
590   // Build the compare.
591   if (!CB.CmpMHS) {
592     Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
593     Cond = MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0);
594   } else {
595     assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE &&
596            "Can only handle SLE ranges");
597 
598     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
599     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
600 
601     Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS);
602     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
603       Register CondRHS = getOrCreateVReg(*CB.CmpRHS);
604       Cond =
605           MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0);
606     } else {
607       const LLT &CmpTy = MRI->getType(CmpOpReg);
608       auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS);
609       auto Diff = MIB.buildConstant(CmpTy, High - Low);
610       Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0);
611     }
612   }
613 
614   // Update successor info
615   addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb);
616 
617   addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()},
618                     CB.ThisBB);
619 
620   // TrueBB and FalseBB are always different unless the incoming IR is
621   // degenerate. This only happens when running llc on weird IR.
622   if (CB.TrueBB != CB.FalseBB)
623     addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb);
624   CB.ThisBB->normalizeSuccProbs();
625 
626   //  if (SwitchBB->getBasicBlock() != CB.FalseBB->getBasicBlock())
627     addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()},
628                       CB.ThisBB);
629 
630   // If the lhs block is the next block, invert the condition so that we can
631   // fall through to the lhs instead of the rhs block.
632   if (CB.TrueBB == CB.ThisBB->getNextNode()) {
633     std::swap(CB.TrueBB, CB.FalseBB);
634     auto True = MIB.buildConstant(i1Ty, 1);
635     Cond = MIB.buildXor(i1Ty, Cond, True).getReg(0);
636   }
637 
638   MIB.buildBrCond(Cond, *CB.TrueBB);
639   MIB.buildBr(*CB.FalseBB);
640   MIB.setDebugLoc(OldDbgLoc);
641 }
642 
643 bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W,
644                                           MachineBasicBlock *SwitchMBB,
645                                           MachineBasicBlock *CurMBB,
646                                           MachineBasicBlock *DefaultMBB,
647                                           MachineIRBuilder &MIB,
648                                           MachineFunction::iterator BBI,
649                                           BranchProbability UnhandledProbs,
650                                           SwitchCG::CaseClusterIt I,
651                                           MachineBasicBlock *Fallthrough,
652                                           bool FallthroughUnreachable) {
653   using namespace SwitchCG;
654   MachineFunction *CurMF = SwitchMBB->getParent();
655   // FIXME: Optimize away range check based on pivot comparisons.
656   JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
657   SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
658   BranchProbability DefaultProb = W.DefaultProb;
659 
660   // The jump block hasn't been inserted yet; insert it here.
661   MachineBasicBlock *JumpMBB = JT->MBB;
662   CurMF->insert(BBI, JumpMBB);
663 
664   // Since the jump table block is separate from the switch block, we need
665   // to keep track of it as a machine predecessor to the default block,
666   // otherwise we lose the phi edges.
667   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
668                     CurMBB);
669   addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()},
670                     JumpMBB);
671 
672   auto JumpProb = I->Prob;
673   auto FallthroughProb = UnhandledProbs;
674 
675   // If the default statement is a target of the jump table, we evenly
676   // distribute the default probability to successors of CurMBB. Also
677   // update the probability on the edge from JumpMBB to Fallthrough.
678   for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
679                                         SE = JumpMBB->succ_end();
680        SI != SE; ++SI) {
681     if (*SI == DefaultMBB) {
682       JumpProb += DefaultProb / 2;
683       FallthroughProb -= DefaultProb / 2;
684       JumpMBB->setSuccProbability(SI, DefaultProb / 2);
685       JumpMBB->normalizeSuccProbs();
686     } else {
687       // Also record edges from the jump table block to it's successors.
688       addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()},
689                         JumpMBB);
690     }
691   }
692 
693   // Skip the range check if the fallthrough block is unreachable.
694   if (FallthroughUnreachable)
695     JTH->OmitRangeCheck = true;
696 
697   if (!JTH->OmitRangeCheck)
698     addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
699   addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
700   CurMBB->normalizeSuccProbs();
701 
702   // The jump table header will be inserted in our current block, do the
703   // range check, and fall through to our fallthrough block.
704   JTH->HeaderBB = CurMBB;
705   JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
706 
707   // If we're in the right place, emit the jump table header right now.
708   if (CurMBB == SwitchMBB) {
709     if (!emitJumpTableHeader(*JT, *JTH, CurMBB))
710       return false;
711     JTH->Emitted = true;
712   }
713   return true;
714 }
715 bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I,
716                                             Value *Cond,
717                                             MachineBasicBlock *Fallthrough,
718                                             bool FallthroughUnreachable,
719                                             BranchProbability UnhandledProbs,
720                                             MachineBasicBlock *CurMBB,
721                                             MachineIRBuilder &MIB,
722                                             MachineBasicBlock *SwitchMBB) {
723   using namespace SwitchCG;
724   const Value *RHS, *LHS, *MHS;
725   CmpInst::Predicate Pred;
726   if (I->Low == I->High) {
727     // Check Cond == I->Low.
728     Pred = CmpInst::ICMP_EQ;
729     LHS = Cond;
730     RHS = I->Low;
731     MHS = nullptr;
732   } else {
733     // Check I->Low <= Cond <= I->High.
734     Pred = CmpInst::ICMP_SLE;
735     LHS = I->Low;
736     MHS = Cond;
737     RHS = I->High;
738   }
739 
740   // If Fallthrough is unreachable, fold away the comparison.
741   // The false probability is the sum of all unhandled cases.
742   CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough,
743                CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs);
744 
745   emitSwitchCase(CB, SwitchMBB, MIB);
746   return true;
747 }
748 
749 bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W,
750                                        Value *Cond,
751                                        MachineBasicBlock *SwitchMBB,
752                                        MachineBasicBlock *DefaultMBB,
753                                        MachineIRBuilder &MIB) {
754   using namespace SwitchCG;
755   MachineFunction *CurMF = FuncInfo.MF;
756   MachineBasicBlock *NextMBB = nullptr;
757   MachineFunction::iterator BBI(W.MBB);
758   if (++BBI != FuncInfo.MF->end())
759     NextMBB = &*BBI;
760 
761   if (EnableOpts) {
762     // Here, we order cases by probability so the most likely case will be
763     // checked first. However, two clusters can have the same probability in
764     // which case their relative ordering is non-deterministic. So we use Low
765     // as a tie-breaker as clusters are guaranteed to never overlap.
766     llvm::sort(W.FirstCluster, W.LastCluster + 1,
767                [](const CaseCluster &a, const CaseCluster &b) {
768                  return a.Prob != b.Prob
769                             ? a.Prob > b.Prob
770                             : a.Low->getValue().slt(b.Low->getValue());
771                });
772 
773     // Rearrange the case blocks so that the last one falls through if possible
774     // without changing the order of probabilities.
775     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) {
776       --I;
777       if (I->Prob > W.LastCluster->Prob)
778         break;
779       if (I->Kind == CC_Range && I->MBB == NextMBB) {
780         std::swap(*I, *W.LastCluster);
781         break;
782       }
783     }
784   }
785 
786   // Compute total probability.
787   BranchProbability DefaultProb = W.DefaultProb;
788   BranchProbability UnhandledProbs = DefaultProb;
789   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
790     UnhandledProbs += I->Prob;
791 
792   MachineBasicBlock *CurMBB = W.MBB;
793   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
794     bool FallthroughUnreachable = false;
795     MachineBasicBlock *Fallthrough;
796     if (I == W.LastCluster) {
797       // For the last cluster, fall through to the default destination.
798       Fallthrough = DefaultMBB;
799       FallthroughUnreachable = isa<UnreachableInst>(
800           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
801     } else {
802       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
803       CurMF->insert(BBI, Fallthrough);
804     }
805     UnhandledProbs -= I->Prob;
806 
807     switch (I->Kind) {
808     case CC_BitTests: {
809       LLVM_DEBUG(dbgs() << "Switch to bit test optimization unimplemented");
810       return false; // Bit tests currently unimplemented.
811     }
812     case CC_JumpTable: {
813       if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI,
814                                   UnhandledProbs, I, Fallthrough,
815                                   FallthroughUnreachable)) {
816         LLVM_DEBUG(dbgs() << "Failed to lower jump table");
817         return false;
818       }
819       break;
820     }
821     case CC_Range: {
822       if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough,
823                                     FallthroughUnreachable, UnhandledProbs,
824                                     CurMBB, MIB, SwitchMBB)) {
825         LLVM_DEBUG(dbgs() << "Failed to lower switch range");
826         return false;
827       }
828       break;
829     }
830     }
831     CurMBB = Fallthrough;
832   }
833 
834   return true;
835 }
836 
837 bool IRTranslator::translateIndirectBr(const User &U,
838                                        MachineIRBuilder &MIRBuilder) {
839   const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
840 
841   const Register Tgt = getOrCreateVReg(*BrInst.getAddress());
842   MIRBuilder.buildBrIndirect(Tgt);
843 
844   // Link successors.
845   MachineBasicBlock &CurBB = MIRBuilder.getMBB();
846   for (const BasicBlock *Succ : successors(&BrInst))
847     CurBB.addSuccessor(&getMBB(*Succ));
848 
849   return true;
850 }
851 
852 static bool isSwiftError(const Value *V) {
853   if (auto Arg = dyn_cast<Argument>(V))
854     return Arg->hasSwiftErrorAttr();
855   if (auto AI = dyn_cast<AllocaInst>(V))
856     return AI->isSwiftError();
857   return false;
858 }
859 
860 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
861   const LoadInst &LI = cast<LoadInst>(U);
862   if (DL->getTypeStoreSize(LI.getType()) == 0)
863     return true;
864 
865   ArrayRef<Register> Regs = getOrCreateVRegs(LI);
866   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
867   Register Base = getOrCreateVReg(*LI.getPointerOperand());
868 
869   Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType());
870   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
871 
872   if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) {
873     assert(Regs.size() == 1 && "swifterror should be single pointer");
874     Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(),
875                                                     LI.getPointerOperand());
876     MIRBuilder.buildCopy(Regs[0], VReg);
877     return true;
878   }
879 
880   auto &TLI = *MF->getSubtarget().getTargetLowering();
881   MachineMemOperand::Flags Flags = TLI.getLoadMemOperandFlags(LI, *DL);
882 
883   const MDNode *Ranges =
884       Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr;
885   for (unsigned i = 0; i < Regs.size(); ++i) {
886     Register Addr;
887     MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
888 
889     MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
890     unsigned BaseAlign = getMemOpAlignment(LI);
891     AAMDNodes AAMetadata;
892     LI.getAAMetadata(AAMetadata);
893     auto MMO = MF->getMachineMemOperand(
894         Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
895         MinAlign(BaseAlign, Offsets[i] / 8), AAMetadata, Ranges,
896         LI.getSyncScopeID(), LI.getOrdering());
897     MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
898   }
899 
900   return true;
901 }
902 
903 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
904   const StoreInst &SI = cast<StoreInst>(U);
905   if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
906     return true;
907 
908   ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand());
909   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
910   Register Base = getOrCreateVReg(*SI.getPointerOperand());
911 
912   Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType());
913   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
914 
915   if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) {
916     assert(Vals.size() == 1 && "swifterror should be single pointer");
917 
918     Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(),
919                                                     SI.getPointerOperand());
920     MIRBuilder.buildCopy(VReg, Vals[0]);
921     return true;
922   }
923 
924   auto &TLI = *MF->getSubtarget().getTargetLowering();
925   MachineMemOperand::Flags Flags = TLI.getStoreMemOperandFlags(SI, *DL);
926 
927   for (unsigned i = 0; i < Vals.size(); ++i) {
928     Register Addr;
929     MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8);
930 
931     MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
932     unsigned BaseAlign = getMemOpAlignment(SI);
933     AAMDNodes AAMetadata;
934     SI.getAAMetadata(AAMetadata);
935     auto MMO = MF->getMachineMemOperand(
936         Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
937         MinAlign(BaseAlign, Offsets[i] / 8), AAMetadata, nullptr,
938         SI.getSyncScopeID(), SI.getOrdering());
939     MIRBuilder.buildStore(Vals[i], Addr, *MMO);
940   }
941   return true;
942 }
943 
944 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
945   const Value *Src = U.getOperand(0);
946   Type *Int32Ty = Type::getInt32Ty(U.getContext());
947 
948   // getIndexedOffsetInType is designed for GEPs, so the first index is the
949   // usual array element rather than looking into the actual aggregate.
950   SmallVector<Value *, 1> Indices;
951   Indices.push_back(ConstantInt::get(Int32Ty, 0));
952 
953   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
954     for (auto Idx : EVI->indices())
955       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
956   } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
957     for (auto Idx : IVI->indices())
958       Indices.push_back(ConstantInt::get(Int32Ty, Idx));
959   } else {
960     for (unsigned i = 1; i < U.getNumOperands(); ++i)
961       Indices.push_back(U.getOperand(i));
962   }
963 
964   return 8 * static_cast<uint64_t>(
965                  DL.getIndexedOffsetInType(Src->getType(), Indices));
966 }
967 
968 bool IRTranslator::translateExtractValue(const User &U,
969                                          MachineIRBuilder &MIRBuilder) {
970   const Value *Src = U.getOperand(0);
971   uint64_t Offset = getOffsetFromIndices(U, *DL);
972   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
973   ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
974   unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin();
975   auto &DstRegs = allocateVRegs(U);
976 
977   for (unsigned i = 0; i < DstRegs.size(); ++i)
978     DstRegs[i] = SrcRegs[Idx++];
979 
980   return true;
981 }
982 
983 bool IRTranslator::translateInsertValue(const User &U,
984                                         MachineIRBuilder &MIRBuilder) {
985   const Value *Src = U.getOperand(0);
986   uint64_t Offset = getOffsetFromIndices(U, *DL);
987   auto &DstRegs = allocateVRegs(U);
988   ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
989   ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src);
990   ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
991   auto InsertedIt = InsertedRegs.begin();
992 
993   for (unsigned i = 0; i < DstRegs.size(); ++i) {
994     if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
995       DstRegs[i] = *InsertedIt++;
996     else
997       DstRegs[i] = SrcRegs[i];
998   }
999 
1000   return true;
1001 }
1002 
1003 bool IRTranslator::translateSelect(const User &U,
1004                                    MachineIRBuilder &MIRBuilder) {
1005   Register Tst = getOrCreateVReg(*U.getOperand(0));
1006   ArrayRef<Register> ResRegs = getOrCreateVRegs(U);
1007   ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
1008   ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
1009 
1010   const SelectInst &SI = cast<SelectInst>(U);
1011   uint16_t Flags = 0;
1012   if (const CmpInst *Cmp = dyn_cast<CmpInst>(SI.getCondition()))
1013     Flags = MachineInstr::copyFlagsFromInstruction(*Cmp);
1014 
1015   for (unsigned i = 0; i < ResRegs.size(); ++i) {
1016     MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags);
1017   }
1018 
1019   return true;
1020 }
1021 
1022 bool IRTranslator::translateBitCast(const User &U,
1023                                     MachineIRBuilder &MIRBuilder) {
1024   // If we're bitcasting to the source type, we can reuse the source vreg.
1025   if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
1026       getLLTForType(*U.getType(), *DL)) {
1027     Register SrcReg = getOrCreateVReg(*U.getOperand(0));
1028     auto &Regs = *VMap.getVRegs(U);
1029     // If we already assigned a vreg for this bitcast, we can't change that.
1030     // Emit a copy to satisfy the users we already emitted.
1031     if (!Regs.empty())
1032       MIRBuilder.buildCopy(Regs[0], SrcReg);
1033     else {
1034       Regs.push_back(SrcReg);
1035       VMap.getOffsets(U)->push_back(0);
1036     }
1037     return true;
1038   }
1039   return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
1040 }
1041 
1042 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
1043                                  MachineIRBuilder &MIRBuilder) {
1044   Register Op = getOrCreateVReg(*U.getOperand(0));
1045   Register Res = getOrCreateVReg(U);
1046   MIRBuilder.buildInstr(Opcode, {Res}, {Op});
1047   return true;
1048 }
1049 
1050 bool IRTranslator::translateGetElementPtr(const User &U,
1051                                           MachineIRBuilder &MIRBuilder) {
1052   // FIXME: support vector GEPs.
1053   if (U.getType()->isVectorTy())
1054     return false;
1055 
1056   Value &Op0 = *U.getOperand(0);
1057   Register BaseReg = getOrCreateVReg(Op0);
1058   Type *PtrIRTy = Op0.getType();
1059   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1060   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1061   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1062 
1063   int64_t Offset = 0;
1064   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
1065        GTI != E; ++GTI) {
1066     const Value *Idx = GTI.getOperand();
1067     if (StructType *StTy = GTI.getStructTypeOrNull()) {
1068       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
1069       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
1070       continue;
1071     } else {
1072       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
1073 
1074       // If this is a scalar constant or a splat vector of constants,
1075       // handle it quickly.
1076       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
1077         Offset += ElementSize * CI->getSExtValue();
1078         continue;
1079       }
1080 
1081       if (Offset != 0) {
1082         LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1083         auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
1084         BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0))
1085                       .getReg(0);
1086         Offset = 0;
1087       }
1088 
1089       Register IdxReg = getOrCreateVReg(*Idx);
1090       if (MRI->getType(IdxReg) != OffsetTy)
1091         IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
1092 
1093       // N = N + Idx * ElementSize;
1094       // Avoid doing it for ElementSize of 1.
1095       Register GepOffsetReg;
1096       if (ElementSize != 1) {
1097         auto ElementSizeMIB = MIRBuilder.buildConstant(
1098             getLLTForType(*OffsetIRTy, *DL), ElementSize);
1099         GepOffsetReg =
1100             MIRBuilder.buildMul(OffsetTy, ElementSizeMIB, IdxReg).getReg(0);
1101       } else
1102         GepOffsetReg = IdxReg;
1103 
1104       BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0);
1105     }
1106   }
1107 
1108   if (Offset != 0) {
1109     auto OffsetMIB =
1110         MIRBuilder.buildConstant(getLLTForType(*OffsetIRTy, *DL), Offset);
1111     MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
1112     return true;
1113   }
1114 
1115   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
1116   return true;
1117 }
1118 
1119 bool IRTranslator::translateMemFunc(const CallInst &CI,
1120                                     MachineIRBuilder &MIRBuilder,
1121                                     Intrinsic::ID ID) {
1122 
1123   // If the source is undef, then just emit a nop.
1124   if (isa<UndefValue>(CI.getArgOperand(1)))
1125     return true;
1126 
1127   ArrayRef<Register> Res;
1128   auto ICall = MIRBuilder.buildIntrinsic(ID, Res, true);
1129   for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI)
1130     ICall.addUse(getOrCreateVReg(**AI));
1131 
1132   unsigned DstAlign = 0, SrcAlign = 0;
1133   unsigned IsVol =
1134       cast<ConstantInt>(CI.getArgOperand(CI.getNumArgOperands() - 1))
1135           ->getZExtValue();
1136 
1137   if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
1138     DstAlign = std::max<unsigned>(MCI->getDestAlignment(), 1);
1139     SrcAlign = std::max<unsigned>(MCI->getSourceAlignment(), 1);
1140   } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
1141     DstAlign = std::max<unsigned>(MMI->getDestAlignment(), 1);
1142     SrcAlign = std::max<unsigned>(MMI->getSourceAlignment(), 1);
1143   } else {
1144     auto *MSI = cast<MemSetInst>(&CI);
1145     DstAlign = std::max<unsigned>(MSI->getDestAlignment(), 1);
1146   }
1147 
1148   // We need to propagate the tail call flag from the IR inst as an argument.
1149   // Otherwise, we have to pessimize and assume later that we cannot tail call
1150   // any memory intrinsics.
1151   ICall.addImm(CI.isTailCall() ? 1 : 0);
1152 
1153   // Create mem operands to store the alignment and volatile info.
1154   auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
1155   ICall.addMemOperand(MF->getMachineMemOperand(
1156       MachinePointerInfo(CI.getArgOperand(0)),
1157       MachineMemOperand::MOStore | VolFlag, 1, DstAlign));
1158   if (ID != Intrinsic::memset)
1159     ICall.addMemOperand(MF->getMachineMemOperand(
1160         MachinePointerInfo(CI.getArgOperand(1)),
1161         MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign));
1162 
1163   return true;
1164 }
1165 
1166 void IRTranslator::getStackGuard(Register DstReg,
1167                                  MachineIRBuilder &MIRBuilder) {
1168   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1169   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
1170   auto MIB =
1171       MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
1172 
1173   auto &TLI = *MF->getSubtarget().getTargetLowering();
1174   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
1175   if (!Global)
1176     return;
1177 
1178   MachinePointerInfo MPInfo(Global);
1179   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
1180                MachineMemOperand::MODereferenceable;
1181   MachineMemOperand *MemRef =
1182       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
1183                                DL->getPointerABIAlignment(0).value());
1184   MIB.setMemRefs({MemRef});
1185 }
1186 
1187 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
1188                                               MachineIRBuilder &MIRBuilder) {
1189   ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
1190   MIRBuilder.buildInstr(
1191       Op, {ResRegs[0], ResRegs[1]},
1192       {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
1193 
1194   return true;
1195 }
1196 
1197 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
1198   switch (ID) {
1199     default:
1200       break;
1201     case Intrinsic::bswap:
1202       return TargetOpcode::G_BSWAP;
1203   case Intrinsic::bitreverse:
1204       return TargetOpcode::G_BITREVERSE;
1205     case Intrinsic::ceil:
1206       return TargetOpcode::G_FCEIL;
1207     case Intrinsic::cos:
1208       return TargetOpcode::G_FCOS;
1209     case Intrinsic::ctpop:
1210       return TargetOpcode::G_CTPOP;
1211     case Intrinsic::exp:
1212       return TargetOpcode::G_FEXP;
1213     case Intrinsic::exp2:
1214       return TargetOpcode::G_FEXP2;
1215     case Intrinsic::fabs:
1216       return TargetOpcode::G_FABS;
1217     case Intrinsic::copysign:
1218       return TargetOpcode::G_FCOPYSIGN;
1219     case Intrinsic::minnum:
1220       return TargetOpcode::G_FMINNUM;
1221     case Intrinsic::maxnum:
1222       return TargetOpcode::G_FMAXNUM;
1223     case Intrinsic::minimum:
1224       return TargetOpcode::G_FMINIMUM;
1225     case Intrinsic::maximum:
1226       return TargetOpcode::G_FMAXIMUM;
1227     case Intrinsic::canonicalize:
1228       return TargetOpcode::G_FCANONICALIZE;
1229     case Intrinsic::floor:
1230       return TargetOpcode::G_FFLOOR;
1231     case Intrinsic::fma:
1232       return TargetOpcode::G_FMA;
1233     case Intrinsic::log:
1234       return TargetOpcode::G_FLOG;
1235     case Intrinsic::log2:
1236       return TargetOpcode::G_FLOG2;
1237     case Intrinsic::log10:
1238       return TargetOpcode::G_FLOG10;
1239     case Intrinsic::nearbyint:
1240       return TargetOpcode::G_FNEARBYINT;
1241     case Intrinsic::pow:
1242       return TargetOpcode::G_FPOW;
1243     case Intrinsic::rint:
1244       return TargetOpcode::G_FRINT;
1245     case Intrinsic::round:
1246       return TargetOpcode::G_INTRINSIC_ROUND;
1247     case Intrinsic::sin:
1248       return TargetOpcode::G_FSIN;
1249     case Intrinsic::sqrt:
1250       return TargetOpcode::G_FSQRT;
1251     case Intrinsic::trunc:
1252       return TargetOpcode::G_INTRINSIC_TRUNC;
1253     case Intrinsic::readcyclecounter:
1254       return TargetOpcode::G_READCYCLECOUNTER;
1255   }
1256   return Intrinsic::not_intrinsic;
1257 }
1258 
1259 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
1260                                             Intrinsic::ID ID,
1261                                             MachineIRBuilder &MIRBuilder) {
1262 
1263   unsigned Op = getSimpleIntrinsicOpcode(ID);
1264 
1265   // Is this a simple intrinsic?
1266   if (Op == Intrinsic::not_intrinsic)
1267     return false;
1268 
1269   // Yes. Let's translate it.
1270   SmallVector<llvm::SrcOp, 4> VRegs;
1271   for (auto &Arg : CI.arg_operands())
1272     VRegs.push_back(getOrCreateVReg(*Arg));
1273 
1274   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
1275                         MachineInstr::copyFlagsFromInstruction(CI));
1276   return true;
1277 }
1278 
1279 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
1280                                            MachineIRBuilder &MIRBuilder) {
1281 
1282   // If this is a simple intrinsic (that is, we just need to add a def of
1283   // a vreg, and uses for each arg operand, then translate it.
1284   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
1285     return true;
1286 
1287   switch (ID) {
1288   default:
1289     break;
1290   case Intrinsic::lifetime_start:
1291   case Intrinsic::lifetime_end: {
1292     // No stack colouring in O0, discard region information.
1293     if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
1294       return true;
1295 
1296     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
1297                                                   : TargetOpcode::LIFETIME_END;
1298 
1299     // Get the underlying objects for the location passed on the lifetime
1300     // marker.
1301     SmallVector<const Value *, 4> Allocas;
1302     GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
1303 
1304     // Iterate over each underlying object, creating lifetime markers for each
1305     // static alloca. Quit if we find a non-static alloca.
1306     for (const Value *V : Allocas) {
1307       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
1308       if (!AI)
1309         continue;
1310 
1311       if (!AI->isStaticAlloca())
1312         return true;
1313 
1314       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
1315     }
1316     return true;
1317   }
1318   case Intrinsic::dbg_declare: {
1319     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
1320     assert(DI.getVariable() && "Missing variable");
1321 
1322     const Value *Address = DI.getAddress();
1323     if (!Address || isa<UndefValue>(Address)) {
1324       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
1325       return true;
1326     }
1327 
1328     assert(DI.getVariable()->isValidLocationForIntrinsic(
1329                MIRBuilder.getDebugLoc()) &&
1330            "Expected inlined-at fields to agree");
1331     auto AI = dyn_cast<AllocaInst>(Address);
1332     if (AI && AI->isStaticAlloca()) {
1333       // Static allocas are tracked at the MF level, no need for DBG_VALUE
1334       // instructions (in fact, they get ignored if they *do* exist).
1335       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
1336                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
1337     } else {
1338       // A dbg.declare describes the address of a source variable, so lower it
1339       // into an indirect DBG_VALUE.
1340       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
1341                                        DI.getVariable(), DI.getExpression());
1342     }
1343     return true;
1344   }
1345   case Intrinsic::dbg_label: {
1346     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
1347     assert(DI.getLabel() && "Missing label");
1348 
1349     assert(DI.getLabel()->isValidLocationForIntrinsic(
1350                MIRBuilder.getDebugLoc()) &&
1351            "Expected inlined-at fields to agree");
1352 
1353     MIRBuilder.buildDbgLabel(DI.getLabel());
1354     return true;
1355   }
1356   case Intrinsic::vaend:
1357     // No target I know of cares about va_end. Certainly no in-tree target
1358     // does. Simplest intrinsic ever!
1359     return true;
1360   case Intrinsic::vastart: {
1361     auto &TLI = *MF->getSubtarget().getTargetLowering();
1362     Value *Ptr = CI.getArgOperand(0);
1363     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
1364 
1365     // FIXME: Get alignment
1366     MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
1367         .addMemOperand(MF->getMachineMemOperand(
1368             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
1369     return true;
1370   }
1371   case Intrinsic::dbg_value: {
1372     // This form of DBG_VALUE is target-independent.
1373     const DbgValueInst &DI = cast<DbgValueInst>(CI);
1374     const Value *V = DI.getValue();
1375     assert(DI.getVariable()->isValidLocationForIntrinsic(
1376                MIRBuilder.getDebugLoc()) &&
1377            "Expected inlined-at fields to agree");
1378     if (!V) {
1379       // Currently the optimizer can produce this; insert an undef to
1380       // help debugging.  Probably the optimizer should not do this.
1381       MIRBuilder.buildDirectDbgValue(0, DI.getVariable(), DI.getExpression());
1382     } else if (const auto *CI = dyn_cast<Constant>(V)) {
1383       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
1384     } else {
1385       for (Register Reg : getOrCreateVRegs(*V)) {
1386         // FIXME: This does not handle register-indirect values at offset 0. The
1387         // direct/indirect thing shouldn't really be handled by something as
1388         // implicit as reg+noreg vs reg+imm in the first place, but it seems
1389         // pretty baked in right now.
1390         MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
1391       }
1392     }
1393     return true;
1394   }
1395   case Intrinsic::uadd_with_overflow:
1396     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
1397   case Intrinsic::sadd_with_overflow:
1398     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
1399   case Intrinsic::usub_with_overflow:
1400     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
1401   case Intrinsic::ssub_with_overflow:
1402     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
1403   case Intrinsic::umul_with_overflow:
1404     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
1405   case Intrinsic::smul_with_overflow:
1406     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
1407   case Intrinsic::fmuladd: {
1408     const TargetMachine &TM = MF->getTarget();
1409     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1410     Register Dst = getOrCreateVReg(CI);
1411     Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
1412     Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
1413     Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
1414     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
1415         TLI.isFMAFasterThanFMulAndFAdd(*MF,
1416                                        TLI.getValueType(*DL, CI.getType()))) {
1417       // TODO: Revisit this to see if we should move this part of the
1418       // lowering to the combiner.
1419       MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
1420                           MachineInstr::copyFlagsFromInstruction(CI));
1421     } else {
1422       LLT Ty = getLLTForType(*CI.getType(), *DL);
1423       auto FMul = MIRBuilder.buildFMul(
1424           Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
1425       MIRBuilder.buildFAdd(Dst, FMul, Op2,
1426                            MachineInstr::copyFlagsFromInstruction(CI));
1427     }
1428     return true;
1429   }
1430   case Intrinsic::memcpy:
1431   case Intrinsic::memmove:
1432   case Intrinsic::memset:
1433     return translateMemFunc(CI, MIRBuilder, ID);
1434   case Intrinsic::eh_typeid_for: {
1435     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
1436     Register Reg = getOrCreateVReg(CI);
1437     unsigned TypeID = MF->getTypeIDFor(GV);
1438     MIRBuilder.buildConstant(Reg, TypeID);
1439     return true;
1440   }
1441   case Intrinsic::objectsize:
1442     llvm_unreachable("llvm.objectsize.* should have been lowered already");
1443 
1444   case Intrinsic::is_constant:
1445     llvm_unreachable("llvm.is.constant.* should have been lowered already");
1446 
1447   case Intrinsic::stackguard:
1448     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
1449     return true;
1450   case Intrinsic::stackprotector: {
1451     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1452     Register GuardVal = MRI->createGenericVirtualRegister(PtrTy);
1453     getStackGuard(GuardVal, MIRBuilder);
1454 
1455     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
1456     int FI = getOrCreateFrameIndex(*Slot);
1457     MF->getFrameInfo().setStackProtectorIndex(FI);
1458 
1459     MIRBuilder.buildStore(
1460         GuardVal, getOrCreateVReg(*Slot),
1461         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1462                                   MachineMemOperand::MOStore |
1463                                       MachineMemOperand::MOVolatile,
1464                                   PtrTy.getSizeInBits() / 8, 8));
1465     return true;
1466   }
1467   case Intrinsic::stacksave: {
1468     // Save the stack pointer to the location provided by the intrinsic.
1469     Register Reg = getOrCreateVReg(CI);
1470     Register StackPtr = MF->getSubtarget()
1471                             .getTargetLowering()
1472                             ->getStackPointerRegisterToSaveRestore();
1473 
1474     // If the target doesn't specify a stack pointer, then fall back.
1475     if (!StackPtr)
1476       return false;
1477 
1478     MIRBuilder.buildCopy(Reg, StackPtr);
1479     return true;
1480   }
1481   case Intrinsic::stackrestore: {
1482     // Restore the stack pointer from the location provided by the intrinsic.
1483     Register Reg = getOrCreateVReg(*CI.getArgOperand(0));
1484     Register StackPtr = MF->getSubtarget()
1485                             .getTargetLowering()
1486                             ->getStackPointerRegisterToSaveRestore();
1487 
1488     // If the target doesn't specify a stack pointer, then fall back.
1489     if (!StackPtr)
1490       return false;
1491 
1492     MIRBuilder.buildCopy(StackPtr, Reg);
1493     return true;
1494   }
1495   case Intrinsic::cttz:
1496   case Intrinsic::ctlz: {
1497     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1498     bool isTrailing = ID == Intrinsic::cttz;
1499     unsigned Opcode = isTrailing
1500                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
1501                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
1502                           : Cst->isZero() ? TargetOpcode::G_CTLZ
1503                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1504     MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
1505                           {getOrCreateVReg(*CI.getArgOperand(0))});
1506     return true;
1507   }
1508   case Intrinsic::invariant_start: {
1509     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1510     Register Undef = MRI->createGenericVirtualRegister(PtrTy);
1511     MIRBuilder.buildUndef(Undef);
1512     return true;
1513   }
1514   case Intrinsic::invariant_end:
1515     return true;
1516   case Intrinsic::assume:
1517   case Intrinsic::var_annotation:
1518   case Intrinsic::sideeffect:
1519     // Discard annotate attributes, assumptions, and artificial side-effects.
1520     return true;
1521   case Intrinsic::read_register: {
1522     Value *Arg = CI.getArgOperand(0);
1523     MIRBuilder
1524         .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
1525         .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
1526     return true;
1527   }
1528   }
1529   return false;
1530 }
1531 
1532 bool IRTranslator::translateInlineAsm(const CallInst &CI,
1533                                       MachineIRBuilder &MIRBuilder) {
1534   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1535   if (!IA.getConstraintString().empty())
1536     return false;
1537 
1538   unsigned ExtraInfo = 0;
1539   if (IA.hasSideEffects())
1540     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1541   if (IA.getDialect() == InlineAsm::AD_Intel)
1542     ExtraInfo |= InlineAsm::Extra_AsmDialect;
1543 
1544   MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1545     .addExternalSymbol(IA.getAsmString().c_str())
1546     .addImm(ExtraInfo);
1547 
1548   return true;
1549 }
1550 
1551 bool IRTranslator::translateCallSite(const ImmutableCallSite &CS,
1552                                      MachineIRBuilder &MIRBuilder) {
1553   const Instruction &I = *CS.getInstruction();
1554   ArrayRef<Register> Res = getOrCreateVRegs(I);
1555 
1556   SmallVector<ArrayRef<Register>, 8> Args;
1557   Register SwiftInVReg = 0;
1558   Register SwiftErrorVReg = 0;
1559   for (auto &Arg : CS.args()) {
1560     if (CLI->supportSwiftError() && isSwiftError(Arg)) {
1561       assert(SwiftInVReg == 0 && "Expected only one swift error argument");
1562       LLT Ty = getLLTForType(*Arg->getType(), *DL);
1563       SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
1564       MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
1565                                             &I, &MIRBuilder.getMBB(), Arg));
1566       Args.emplace_back(makeArrayRef(SwiftInVReg));
1567       SwiftErrorVReg =
1568           SwiftError.getOrCreateVRegDefAt(&I, &MIRBuilder.getMBB(), Arg);
1569       continue;
1570     }
1571     Args.push_back(getOrCreateVRegs(*Arg));
1572   }
1573 
1574   // We don't set HasCalls on MFI here yet because call lowering may decide to
1575   // optimize into tail calls. Instead, we defer that to selection where a final
1576   // scan is done to check if any instructions are calls.
1577   bool Success =
1578       CLI->lowerCall(MIRBuilder, CS, Res, Args, SwiftErrorVReg,
1579                      [&]() { return getOrCreateVReg(*CS.getCalledValue()); });
1580 
1581   // Check if we just inserted a tail call.
1582   if (Success) {
1583     assert(!HasTailCall && "Can't tail call return twice from block?");
1584     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1585     HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
1586   }
1587 
1588   return Success;
1589 }
1590 
1591 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
1592   const CallInst &CI = cast<CallInst>(U);
1593   auto TII = MF->getTarget().getIntrinsicInfo();
1594   const Function *F = CI.getCalledFunction();
1595 
1596   // FIXME: support Windows dllimport function calls.
1597   if (F && (F->hasDLLImportStorageClass() ||
1598             (MF->getTarget().getTargetTriple().isOSWindows() &&
1599              F->hasExternalWeakLinkage())))
1600     return false;
1601 
1602   // FIXME: support control flow guard targets.
1603   if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
1604     return false;
1605 
1606   if (CI.isInlineAsm())
1607     return translateInlineAsm(CI, MIRBuilder);
1608 
1609   Intrinsic::ID ID = Intrinsic::not_intrinsic;
1610   if (F && F->isIntrinsic()) {
1611     ID = F->getIntrinsicID();
1612     if (TII && ID == Intrinsic::not_intrinsic)
1613       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1614   }
1615 
1616   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic)
1617     return translateCallSite(&CI, MIRBuilder);
1618 
1619   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1620 
1621   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1622     return true;
1623 
1624   ArrayRef<Register> ResultRegs;
1625   if (!CI.getType()->isVoidTy())
1626     ResultRegs = getOrCreateVRegs(CI);
1627 
1628   // Ignore the callsite attributes. Backend code is most likely not expecting
1629   // an intrinsic to sometimes have side effects and sometimes not.
1630   MachineInstrBuilder MIB =
1631       MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory());
1632   if (isa<FPMathOperator>(CI))
1633     MIB->copyIRFlags(CI);
1634 
1635   for (auto &Arg : enumerate(CI.arg_operands())) {
1636     // Some intrinsics take metadata parameters. Reject them.
1637     if (isa<MetadataAsValue>(Arg.value()))
1638       return false;
1639 
1640     // If this is required to be an immediate, don't materialize it in a
1641     // register.
1642     if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
1643       if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
1644         // imm arguments are more convenient than cimm (and realistically
1645         // probably sufficient), so use them.
1646         assert(CI->getBitWidth() <= 64 &&
1647                "large intrinsic immediates not handled");
1648         MIB.addImm(CI->getSExtValue());
1649       } else {
1650         MIB.addFPImm(cast<ConstantFP>(Arg.value()));
1651       }
1652     } else {
1653       ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
1654       if (VRegs.size() > 1)
1655         return false;
1656       MIB.addUse(VRegs[0]);
1657     }
1658   }
1659 
1660   // Add a MachineMemOperand if it is a target mem intrinsic.
1661   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1662   TargetLowering::IntrinsicInfo Info;
1663   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
1664   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
1665     MaybeAlign Align = Info.align;
1666     if (!Align)
1667       Align = MaybeAlign(
1668           DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext())));
1669 
1670     uint64_t Size = Info.memVT.getStoreSize();
1671     MIB.addMemOperand(MF->getMachineMemOperand(
1672         MachinePointerInfo(Info.ptrVal), Info.flags, Size, Align->value()));
1673   }
1674 
1675   return true;
1676 }
1677 
1678 bool IRTranslator::translateInvoke(const User &U,
1679                                    MachineIRBuilder &MIRBuilder) {
1680   const InvokeInst &I = cast<InvokeInst>(U);
1681   MCContext &Context = MF->getContext();
1682 
1683   const BasicBlock *ReturnBB = I.getSuccessor(0);
1684   const BasicBlock *EHPadBB = I.getSuccessor(1);
1685 
1686   const Value *Callee = I.getCalledValue();
1687   const Function *Fn = dyn_cast<Function>(Callee);
1688   if (isa<InlineAsm>(Callee))
1689     return false;
1690 
1691   // FIXME: support invoking patchpoint and statepoint intrinsics.
1692   if (Fn && Fn->isIntrinsic())
1693     return false;
1694 
1695   // FIXME: support whatever these are.
1696   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1697     return false;
1698 
1699   // FIXME: support control flow guard targets.
1700   if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
1701     return false;
1702 
1703   // FIXME: support Windows exception handling.
1704   if (!isa<LandingPadInst>(EHPadBB->front()))
1705     return false;
1706 
1707   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
1708   // the region covered by the try.
1709   MCSymbol *BeginSymbol = Context.createTempSymbol();
1710   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1711 
1712   if (!translateCallSite(&I, MIRBuilder))
1713     return false;
1714 
1715   MCSymbol *EndSymbol = Context.createTempSymbol();
1716   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1717 
1718   // FIXME: track probabilities.
1719   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1720                     &ReturnMBB = getMBB(*ReturnBB);
1721   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1722   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1723   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
1724   MIRBuilder.buildBr(ReturnMBB);
1725 
1726   return true;
1727 }
1728 
1729 bool IRTranslator::translateCallBr(const User &U,
1730                                    MachineIRBuilder &MIRBuilder) {
1731   // FIXME: Implement this.
1732   return false;
1733 }
1734 
1735 bool IRTranslator::translateLandingPad(const User &U,
1736                                        MachineIRBuilder &MIRBuilder) {
1737   const LandingPadInst &LP = cast<LandingPadInst>(U);
1738 
1739   MachineBasicBlock &MBB = MIRBuilder.getMBB();
1740 
1741   MBB.setIsEHPad();
1742 
1743   // If there aren't registers to copy the values into (e.g., during SjLj
1744   // exceptions), then don't bother.
1745   auto &TLI = *MF->getSubtarget().getTargetLowering();
1746   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1747   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1748       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1749     return true;
1750 
1751   // If landingpad's return type is token type, we don't create DAG nodes
1752   // for its exception pointer and selector value. The extraction of exception
1753   // pointer or selector value from token type landingpads is not currently
1754   // supported.
1755   if (LP.getType()->isTokenTy())
1756     return true;
1757 
1758   // Add a label to mark the beginning of the landing pad.  Deletion of the
1759   // landing pad can thus be detected via the MachineModuleInfo.
1760   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
1761     .addSym(MF->addLandingPad(&MBB));
1762 
1763   LLT Ty = getLLTForType(*LP.getType(), *DL);
1764   Register Undef = MRI->createGenericVirtualRegister(Ty);
1765   MIRBuilder.buildUndef(Undef);
1766 
1767   SmallVector<LLT, 2> Tys;
1768   for (Type *Ty : cast<StructType>(LP.getType())->elements())
1769     Tys.push_back(getLLTForType(*Ty, *DL));
1770   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1771 
1772   // Mark exception register as live in.
1773   Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1774   if (!ExceptionReg)
1775     return false;
1776 
1777   MBB.addLiveIn(ExceptionReg);
1778   ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
1779   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
1780 
1781   Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1782   if (!SelectorReg)
1783     return false;
1784 
1785   MBB.addLiveIn(SelectorReg);
1786   Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1787   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
1788   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
1789 
1790   return true;
1791 }
1792 
1793 bool IRTranslator::translateAlloca(const User &U,
1794                                    MachineIRBuilder &MIRBuilder) {
1795   auto &AI = cast<AllocaInst>(U);
1796 
1797   if (AI.isSwiftError())
1798     return true;
1799 
1800   if (AI.isStaticAlloca()) {
1801     Register Res = getOrCreateVReg(AI);
1802     int FI = getOrCreateFrameIndex(AI);
1803     MIRBuilder.buildFrameIndex(Res, FI);
1804     return true;
1805   }
1806 
1807   // FIXME: support stack probing for Windows.
1808   if (MF->getTarget().getTargetTriple().isOSWindows())
1809     return false;
1810 
1811   // Now we're in the harder dynamic case.
1812   Type *Ty = AI.getAllocatedType();
1813   unsigned Align =
1814       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1815 
1816   Register NumElts = getOrCreateVReg(*AI.getArraySize());
1817 
1818   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1819   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
1820   if (MRI->getType(NumElts) != IntPtrTy) {
1821     Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1822     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1823     NumElts = ExtElts;
1824   }
1825 
1826   Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
1827   Register TySize =
1828       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty)));
1829   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1830 
1831   unsigned StackAlign =
1832       MF->getSubtarget().getFrameLowering()->getStackAlignment();
1833   if (Align <= StackAlign)
1834     Align = 0;
1835 
1836   // Round the size of the allocation up to the stack alignment size
1837   // by add SA-1 to the size. This doesn't overflow because we're computing
1838   // an address inside an alloca.
1839   auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign - 1);
1840   auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
1841                                       MachineInstr::NoUWrap);
1842   auto AlignCst =
1843       MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign - 1));
1844   auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
1845 
1846   MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Align);
1847 
1848   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1849   assert(MF->getFrameInfo().hasVarSizedObjects());
1850   return true;
1851 }
1852 
1853 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1854   // FIXME: We may need more info about the type. Because of how LLT works,
1855   // we're completely discarding the i64/double distinction here (amongst
1856   // others). Fortunately the ABIs I know of where that matters don't use va_arg
1857   // anyway but that's not guaranteed.
1858   MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
1859                         {getOrCreateVReg(*U.getOperand(0)),
1860                          uint64_t(DL->getABITypeAlignment(U.getType()))});
1861   return true;
1862 }
1863 
1864 bool IRTranslator::translateInsertElement(const User &U,
1865                                           MachineIRBuilder &MIRBuilder) {
1866   // If it is a <1 x Ty> vector, use the scalar as it is
1867   // not a legal vector type in LLT.
1868   if (U.getType()->getVectorNumElements() == 1) {
1869     Register Elt = getOrCreateVReg(*U.getOperand(1));
1870     auto &Regs = *VMap.getVRegs(U);
1871     if (Regs.empty()) {
1872       Regs.push_back(Elt);
1873       VMap.getOffsets(U)->push_back(0);
1874     } else {
1875       MIRBuilder.buildCopy(Regs[0], Elt);
1876     }
1877     return true;
1878   }
1879 
1880   Register Res = getOrCreateVReg(U);
1881   Register Val = getOrCreateVReg(*U.getOperand(0));
1882   Register Elt = getOrCreateVReg(*U.getOperand(1));
1883   Register Idx = getOrCreateVReg(*U.getOperand(2));
1884   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
1885   return true;
1886 }
1887 
1888 bool IRTranslator::translateExtractElement(const User &U,
1889                                            MachineIRBuilder &MIRBuilder) {
1890   // If it is a <1 x Ty> vector, use the scalar as it is
1891   // not a legal vector type in LLT.
1892   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1893     Register Elt = getOrCreateVReg(*U.getOperand(0));
1894     auto &Regs = *VMap.getVRegs(U);
1895     if (Regs.empty()) {
1896       Regs.push_back(Elt);
1897       VMap.getOffsets(U)->push_back(0);
1898     } else {
1899       MIRBuilder.buildCopy(Regs[0], Elt);
1900     }
1901     return true;
1902   }
1903   Register Res = getOrCreateVReg(U);
1904   Register Val = getOrCreateVReg(*U.getOperand(0));
1905   const auto &TLI = *MF->getSubtarget().getTargetLowering();
1906   unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1907   Register Idx;
1908   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1909     if (CI->getBitWidth() != PreferredVecIdxWidth) {
1910       APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1911       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1912       Idx = getOrCreateVReg(*NewIdxCI);
1913     }
1914   }
1915   if (!Idx)
1916     Idx = getOrCreateVReg(*U.getOperand(1));
1917   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1918     const LLT &VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1919     Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx)->getOperand(0).getReg();
1920   }
1921   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
1922   return true;
1923 }
1924 
1925 bool IRTranslator::translateShuffleVector(const User &U,
1926                                           MachineIRBuilder &MIRBuilder) {
1927   SmallVector<int, 8> Mask;
1928   ShuffleVectorInst::getShuffleMask(cast<Constant>(U.getOperand(2)), Mask);
1929   ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
1930   MIRBuilder
1931       .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
1932                   {getOrCreateVReg(*U.getOperand(0)),
1933                    getOrCreateVReg(*U.getOperand(1))})
1934       .addShuffleMask(MaskAlloc);
1935   return true;
1936 }
1937 
1938 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1939   const PHINode &PI = cast<PHINode>(U);
1940 
1941   SmallVector<MachineInstr *, 4> Insts;
1942   for (auto Reg : getOrCreateVRegs(PI)) {
1943     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
1944     Insts.push_back(MIB.getInstr());
1945   }
1946 
1947   PendingPHIs.emplace_back(&PI, std::move(Insts));
1948   return true;
1949 }
1950 
1951 bool IRTranslator::translateAtomicCmpXchg(const User &U,
1952                                           MachineIRBuilder &MIRBuilder) {
1953   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1954 
1955   if (I.isWeak())
1956     return false;
1957 
1958   auto &TLI = *MF->getSubtarget().getTargetLowering();
1959   auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
1960 
1961   Type *ResType = I.getType();
1962   Type *ValType = ResType->Type::getStructElementType(0);
1963 
1964   auto Res = getOrCreateVRegs(I);
1965   Register OldValRes = Res[0];
1966   Register SuccessRes = Res[1];
1967   Register Addr = getOrCreateVReg(*I.getPointerOperand());
1968   Register Cmp = getOrCreateVReg(*I.getCompareOperand());
1969   Register NewVal = getOrCreateVReg(*I.getNewValOperand());
1970 
1971   AAMDNodes AAMetadata;
1972   I.getAAMetadata(AAMetadata);
1973 
1974   MIRBuilder.buildAtomicCmpXchgWithSuccess(
1975       OldValRes, SuccessRes, Addr, Cmp, NewVal,
1976       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
1977                                 Flags, DL->getTypeStoreSize(ValType),
1978                                 getMemOpAlignment(I), AAMetadata, nullptr,
1979                                 I.getSyncScopeID(), I.getSuccessOrdering(),
1980                                 I.getFailureOrdering()));
1981   return true;
1982 }
1983 
1984 bool IRTranslator::translateAtomicRMW(const User &U,
1985                                       MachineIRBuilder &MIRBuilder) {
1986   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1987   auto &TLI = *MF->getSubtarget().getTargetLowering();
1988   auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
1989 
1990   Type *ResType = I.getType();
1991 
1992   Register Res = getOrCreateVReg(I);
1993   Register Addr = getOrCreateVReg(*I.getPointerOperand());
1994   Register Val = getOrCreateVReg(*I.getValOperand());
1995 
1996   unsigned Opcode = 0;
1997   switch (I.getOperation()) {
1998   default:
1999     return false;
2000   case AtomicRMWInst::Xchg:
2001     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
2002     break;
2003   case AtomicRMWInst::Add:
2004     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
2005     break;
2006   case AtomicRMWInst::Sub:
2007     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
2008     break;
2009   case AtomicRMWInst::And:
2010     Opcode = TargetOpcode::G_ATOMICRMW_AND;
2011     break;
2012   case AtomicRMWInst::Nand:
2013     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
2014     break;
2015   case AtomicRMWInst::Or:
2016     Opcode = TargetOpcode::G_ATOMICRMW_OR;
2017     break;
2018   case AtomicRMWInst::Xor:
2019     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
2020     break;
2021   case AtomicRMWInst::Max:
2022     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
2023     break;
2024   case AtomicRMWInst::Min:
2025     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
2026     break;
2027   case AtomicRMWInst::UMax:
2028     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
2029     break;
2030   case AtomicRMWInst::UMin:
2031     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
2032     break;
2033   case AtomicRMWInst::FAdd:
2034     Opcode = TargetOpcode::G_ATOMICRMW_FADD;
2035     break;
2036   case AtomicRMWInst::FSub:
2037     Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
2038     break;
2039   }
2040 
2041   AAMDNodes AAMetadata;
2042   I.getAAMetadata(AAMetadata);
2043 
2044   MIRBuilder.buildAtomicRMW(
2045       Opcode, Res, Addr, Val,
2046       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
2047                                 Flags, DL->getTypeStoreSize(ResType),
2048                                 getMemOpAlignment(I), AAMetadata,
2049                                 nullptr, I.getSyncScopeID(), I.getOrdering()));
2050   return true;
2051 }
2052 
2053 bool IRTranslator::translateFence(const User &U,
2054                                   MachineIRBuilder &MIRBuilder) {
2055   const FenceInst &Fence = cast<FenceInst>(U);
2056   MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
2057                         Fence.getSyncScopeID());
2058   return true;
2059 }
2060 
2061 void IRTranslator::finishPendingPhis() {
2062 #ifndef NDEBUG
2063   DILocationVerifier Verifier;
2064   GISelObserverWrapper WrapperObserver(&Verifier);
2065   RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2066 #endif // ifndef NDEBUG
2067   for (auto &Phi : PendingPHIs) {
2068     const PHINode *PI = Phi.first;
2069     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
2070     MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
2071     EntryBuilder->setDebugLoc(PI->getDebugLoc());
2072 #ifndef NDEBUG
2073     Verifier.setCurrentInst(PI);
2074 #endif // ifndef NDEBUG
2075 
2076     SmallSet<const MachineBasicBlock *, 16> SeenPreds;
2077     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
2078       auto IRPred = PI->getIncomingBlock(i);
2079       ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
2080       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
2081         if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
2082           continue;
2083         SeenPreds.insert(Pred);
2084         for (unsigned j = 0; j < ValRegs.size(); ++j) {
2085           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
2086           MIB.addUse(ValRegs[j]);
2087           MIB.addMBB(Pred);
2088         }
2089       }
2090     }
2091   }
2092 }
2093 
2094 bool IRTranslator::valueIsSplit(const Value &V,
2095                                 SmallVectorImpl<uint64_t> *Offsets) {
2096   SmallVector<LLT, 4> SplitTys;
2097   if (Offsets && !Offsets->empty())
2098     Offsets->clear();
2099   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
2100   return SplitTys.size() > 1;
2101 }
2102 
2103 bool IRTranslator::translate(const Instruction &Inst) {
2104   CurBuilder->setDebugLoc(Inst.getDebugLoc());
2105   // We only emit constants into the entry block from here. To prevent jumpy
2106   // debug behaviour set the line to 0.
2107   if (const DebugLoc &DL = Inst.getDebugLoc())
2108     EntryBuilder->setDebugLoc(
2109         DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
2110   else
2111     EntryBuilder->setDebugLoc(DebugLoc());
2112 
2113   switch (Inst.getOpcode()) {
2114 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2115   case Instruction::OPCODE:                                                    \
2116     return translate##OPCODE(Inst, *CurBuilder.get());
2117 #include "llvm/IR/Instruction.def"
2118   default:
2119     return false;
2120   }
2121 }
2122 
2123 bool IRTranslator::translate(const Constant &C, Register Reg) {
2124   if (auto CI = dyn_cast<ConstantInt>(&C))
2125     EntryBuilder->buildConstant(Reg, *CI);
2126   else if (auto CF = dyn_cast<ConstantFP>(&C))
2127     EntryBuilder->buildFConstant(Reg, *CF);
2128   else if (isa<UndefValue>(C))
2129     EntryBuilder->buildUndef(Reg);
2130   else if (isa<ConstantPointerNull>(C)) {
2131     // As we are trying to build a constant val of 0 into a pointer,
2132     // insert a cast to make them correct with respect to types.
2133     unsigned NullSize = DL->getTypeSizeInBits(C.getType());
2134     auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
2135     auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
2136     Register ZeroReg = getOrCreateVReg(*ZeroVal);
2137     EntryBuilder->buildCast(Reg, ZeroReg);
2138   } else if (auto GV = dyn_cast<GlobalValue>(&C))
2139     EntryBuilder->buildGlobalValue(Reg, GV);
2140   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
2141     if (!CAZ->getType()->isVectorTy())
2142       return false;
2143     // Return the scalar if it is a <1 x Ty> vector.
2144     if (CAZ->getNumElements() == 1)
2145       return translate(*CAZ->getElementValue(0u), Reg);
2146     SmallVector<Register, 4> Ops;
2147     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
2148       Constant &Elt = *CAZ->getElementValue(i);
2149       Ops.push_back(getOrCreateVReg(Elt));
2150     }
2151     EntryBuilder->buildBuildVector(Reg, Ops);
2152   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
2153     // Return the scalar if it is a <1 x Ty> vector.
2154     if (CV->getNumElements() == 1)
2155       return translate(*CV->getElementAsConstant(0), Reg);
2156     SmallVector<Register, 4> Ops;
2157     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
2158       Constant &Elt = *CV->getElementAsConstant(i);
2159       Ops.push_back(getOrCreateVReg(Elt));
2160     }
2161     EntryBuilder->buildBuildVector(Reg, Ops);
2162   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
2163     switch(CE->getOpcode()) {
2164 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2165   case Instruction::OPCODE:                                                    \
2166     return translate##OPCODE(*CE, *EntryBuilder.get());
2167 #include "llvm/IR/Instruction.def"
2168     default:
2169       return false;
2170     }
2171   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
2172     if (CV->getNumOperands() == 1)
2173       return translate(*CV->getOperand(0), Reg);
2174     SmallVector<Register, 4> Ops;
2175     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
2176       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
2177     }
2178     EntryBuilder->buildBuildVector(Reg, Ops);
2179   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
2180     EntryBuilder->buildBlockAddress(Reg, BA);
2181   } else
2182     return false;
2183 
2184   return true;
2185 }
2186 
2187 void IRTranslator::finalizeBasicBlock() {
2188   for (auto &JTCase : SL->JTCases) {
2189     // Emit header first, if it wasn't already emitted.
2190     if (!JTCase.first.Emitted)
2191       emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
2192 
2193     emitJumpTable(JTCase.second, JTCase.second.MBB);
2194   }
2195   SL->JTCases.clear();
2196 }
2197 
2198 void IRTranslator::finalizeFunction() {
2199   // Release the memory used by the different maps we
2200   // needed during the translation.
2201   PendingPHIs.clear();
2202   VMap.reset();
2203   FrameIndices.clear();
2204   MachinePreds.clear();
2205   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
2206   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
2207   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
2208   EntryBuilder.reset();
2209   CurBuilder.reset();
2210   FuncInfo.clear();
2211 }
2212 
2213 /// Returns true if a BasicBlock \p BB within a variadic function contains a
2214 /// variadic musttail call.
2215 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
2216   if (!IsVarArg)
2217     return false;
2218 
2219   // Walk the block backwards, because tail calls usually only appear at the end
2220   // of a block.
2221   return std::any_of(BB.rbegin(), BB.rend(), [](const Instruction &I) {
2222     const auto *CI = dyn_cast<CallInst>(&I);
2223     return CI && CI->isMustTailCall();
2224   });
2225 }
2226 
2227 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
2228   MF = &CurMF;
2229   const Function &F = MF->getFunction();
2230   if (F.empty())
2231     return false;
2232   GISelCSEAnalysisWrapper &Wrapper =
2233       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
2234   // Set the CSEConfig and run the analysis.
2235   GISelCSEInfo *CSEInfo = nullptr;
2236   TPC = &getAnalysis<TargetPassConfig>();
2237   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
2238                        ? EnableCSEInIRTranslator
2239                        : TPC->isGISelCSEEnabled();
2240 
2241   if (EnableCSE) {
2242     EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2243     CSEInfo = &Wrapper.get(TPC->getCSEConfig());
2244     EntryBuilder->setCSEInfo(CSEInfo);
2245     CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2246     CurBuilder->setCSEInfo(CSEInfo);
2247   } else {
2248     EntryBuilder = std::make_unique<MachineIRBuilder>();
2249     CurBuilder = std::make_unique<MachineIRBuilder>();
2250   }
2251   CLI = MF->getSubtarget().getCallLowering();
2252   CurBuilder->setMF(*MF);
2253   EntryBuilder->setMF(*MF);
2254   MRI = &MF->getRegInfo();
2255   DL = &F.getParent()->getDataLayout();
2256   ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2257   FuncInfo.MF = MF;
2258   FuncInfo.BPI = nullptr;
2259   const auto &TLI = *MF->getSubtarget().getTargetLowering();
2260   const TargetMachine &TM = MF->getTarget();
2261   SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
2262   SL->init(TLI, TM, *DL);
2263 
2264   EnableOpts = TM.getOptLevel() != CodeGenOpt::None && !skipFunction(F);
2265 
2266   assert(PendingPHIs.empty() && "stale PHIs");
2267 
2268   if (!DL->isLittleEndian()) {
2269     // Currently we don't properly handle big endian code.
2270     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2271                                F.getSubprogram(), &F.getEntryBlock());
2272     R << "unable to translate in big endian mode";
2273     reportTranslationError(*MF, *TPC, *ORE, R);
2274   }
2275 
2276   // Release the per-function state when we return, whether we succeeded or not.
2277   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
2278 
2279   // Setup a separate basic-block for the arguments and constants
2280   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
2281   MF->push_back(EntryBB);
2282   EntryBuilder->setMBB(*EntryBB);
2283 
2284   DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc();
2285   SwiftError.setFunction(CurMF);
2286   SwiftError.createEntriesInEntryBlock(DbgLoc);
2287 
2288   bool IsVarArg = F.isVarArg();
2289   bool HasMustTailInVarArgFn = false;
2290 
2291   // Create all blocks, in IR order, to preserve the layout.
2292   for (const BasicBlock &BB: F) {
2293     auto *&MBB = BBToMBB[&BB];
2294 
2295     MBB = MF->CreateMachineBasicBlock(&BB);
2296     MF->push_back(MBB);
2297 
2298     if (BB.hasAddressTaken())
2299       MBB->setHasAddressTaken();
2300 
2301     if (!HasMustTailInVarArgFn)
2302       HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
2303   }
2304 
2305   MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
2306 
2307   // Make our arguments/constants entry block fallthrough to the IR entry block.
2308   EntryBB->addSuccessor(&getMBB(F.front()));
2309 
2310   // Lower the actual args into this basic block.
2311   SmallVector<ArrayRef<Register>, 8> VRegArgs;
2312   for (const Argument &Arg: F.args()) {
2313     if (DL->getTypeStoreSize(Arg.getType()) == 0)
2314       continue; // Don't handle zero sized types.
2315     ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
2316     VRegArgs.push_back(VRegs);
2317 
2318     if (Arg.hasSwiftErrorAttr()) {
2319       assert(VRegs.size() == 1 && "Too many vregs for Swift error");
2320       SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
2321     }
2322   }
2323 
2324   if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
2325     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2326                                F.getSubprogram(), &F.getEntryBlock());
2327     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
2328     reportTranslationError(*MF, *TPC, *ORE, R);
2329     return false;
2330   }
2331 
2332   // Need to visit defs before uses when translating instructions.
2333   GISelObserverWrapper WrapperObserver;
2334   if (EnableCSE && CSEInfo)
2335     WrapperObserver.addObserver(CSEInfo);
2336   {
2337     ReversePostOrderTraversal<const Function *> RPOT(&F);
2338 #ifndef NDEBUG
2339     DILocationVerifier Verifier;
2340     WrapperObserver.addObserver(&Verifier);
2341 #endif // ifndef NDEBUG
2342     RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2343     for (const BasicBlock *BB : RPOT) {
2344       MachineBasicBlock &MBB = getMBB(*BB);
2345       // Set the insertion point of all the following translations to
2346       // the end of this basic block.
2347       CurBuilder->setMBB(MBB);
2348       HasTailCall = false;
2349       for (const Instruction &Inst : *BB) {
2350         // If we translated a tail call in the last step, then we know
2351         // everything after the call is either a return, or something that is
2352         // handled by the call itself. (E.g. a lifetime marker or assume
2353         // intrinsic.) In this case, we should stop translating the block and
2354         // move on.
2355         if (HasTailCall)
2356           break;
2357 #ifndef NDEBUG
2358         Verifier.setCurrentInst(&Inst);
2359 #endif // ifndef NDEBUG
2360         if (translate(Inst))
2361           continue;
2362 
2363         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2364                                    Inst.getDebugLoc(), BB);
2365         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
2366 
2367         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
2368           std::string InstStrStorage;
2369           raw_string_ostream InstStr(InstStrStorage);
2370           InstStr << Inst;
2371 
2372           R << ": '" << InstStr.str() << "'";
2373         }
2374 
2375         reportTranslationError(*MF, *TPC, *ORE, R);
2376         return false;
2377       }
2378 
2379       finalizeBasicBlock();
2380     }
2381 #ifndef NDEBUG
2382     WrapperObserver.removeObserver(&Verifier);
2383 #endif
2384   }
2385 
2386   finishPendingPhis();
2387 
2388   SwiftError.propagateVRegs();
2389 
2390   // Merge the argument lowering and constants block with its single
2391   // successor, the LLVM-IR entry block.  We want the basic block to
2392   // be maximal.
2393   assert(EntryBB->succ_size() == 1 &&
2394          "Custom BB used for lowering should have only one successor");
2395   // Get the successor of the current entry block.
2396   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
2397   assert(NewEntryBB.pred_size() == 1 &&
2398          "LLVM-IR entry block has a predecessor!?");
2399   // Move all the instruction from the current entry block to the
2400   // new entry block.
2401   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
2402                     EntryBB->end());
2403 
2404   // Update the live-in information for the new entry block.
2405   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
2406     NewEntryBB.addLiveIn(LiveIn);
2407   NewEntryBB.sortUniqueLiveIns();
2408 
2409   // Get rid of the now empty basic block.
2410   EntryBB->removeSuccessor(&NewEntryBB);
2411   MF->remove(EntryBB);
2412   MF->DeleteMachineBasicBlock(EntryBB);
2413 
2414   assert(&MF->front() == &NewEntryBB &&
2415          "New entry wasn't next in the list of basic block!");
2416 
2417   // Initialize stack protector information.
2418   StackProtector &SP = getAnalysis<StackProtector>();
2419   SP.copyToMachineFrameInfo(MF->getFrameInfo());
2420 
2421   return false;
2422 }
2423