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   Value &Op0 = *U.getOperand(0);
1053   Register BaseReg = getOrCreateVReg(Op0);
1054   Type *PtrIRTy = Op0.getType();
1055   LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
1056   Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1057   LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1058 
1059   // Normalize Vector GEP - all scalar operands should be converted to the
1060   // splat vector.
1061   unsigned VectorWidth = 0;
1062   if (auto *VT = dyn_cast<VectorType>(U.getType()))
1063     VectorWidth = VT->getNumElements();
1064 
1065   // We might need to splat the base pointer into a vector if the offsets
1066   // are vectors.
1067   if (VectorWidth && !PtrTy.isVector()) {
1068     BaseReg =
1069         MIRBuilder.buildSplatVector(LLT::vector(VectorWidth, PtrTy), BaseReg)
1070             .getReg(0);
1071     PtrIRTy = VectorType::get(PtrIRTy, VectorWidth);
1072     PtrTy = getLLTForType(*PtrIRTy, *DL);
1073     OffsetIRTy = DL->getIntPtrType(PtrIRTy);
1074     OffsetTy = getLLTForType(*OffsetIRTy, *DL);
1075   }
1076 
1077   int64_t Offset = 0;
1078   for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
1079        GTI != E; ++GTI) {
1080     const Value *Idx = GTI.getOperand();
1081     if (StructType *StTy = GTI.getStructTypeOrNull()) {
1082       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
1083       Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
1084       continue;
1085     } else {
1086       uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
1087 
1088       // If this is a scalar constant or a splat vector of constants,
1089       // handle it quickly.
1090       if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
1091         Offset += ElementSize * CI->getSExtValue();
1092         continue;
1093       }
1094 
1095       if (Offset != 0) {
1096         auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset);
1097         BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0))
1098                       .getReg(0);
1099         Offset = 0;
1100       }
1101 
1102       Register IdxReg = getOrCreateVReg(*Idx);
1103       LLT IdxTy = MRI->getType(IdxReg);
1104       if (IdxTy != OffsetTy) {
1105         if (!IdxTy.isVector() && VectorWidth) {
1106           IdxReg = MIRBuilder.buildSplatVector(
1107             OffsetTy.changeElementType(IdxTy), IdxReg).getReg(0);
1108         }
1109 
1110         IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0);
1111       }
1112 
1113       // N = N + Idx * ElementSize;
1114       // Avoid doing it for ElementSize of 1.
1115       Register GepOffsetReg;
1116       if (ElementSize != 1) {
1117         auto ElementSizeMIB = MIRBuilder.buildConstant(
1118             getLLTForType(*OffsetIRTy, *DL), ElementSize);
1119         GepOffsetReg =
1120             MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB).getReg(0);
1121       } else
1122         GepOffsetReg = IdxReg;
1123 
1124       BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0);
1125     }
1126   }
1127 
1128   if (Offset != 0) {
1129     auto OffsetMIB =
1130         MIRBuilder.buildConstant(OffsetTy, Offset);
1131     MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0));
1132     return true;
1133   }
1134 
1135   MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
1136   return true;
1137 }
1138 
1139 bool IRTranslator::translateMemFunc(const CallInst &CI,
1140                                     MachineIRBuilder &MIRBuilder,
1141                                     Intrinsic::ID ID) {
1142 
1143   // If the source is undef, then just emit a nop.
1144   if (isa<UndefValue>(CI.getArgOperand(1)))
1145     return true;
1146 
1147   ArrayRef<Register> Res;
1148   auto ICall = MIRBuilder.buildIntrinsic(ID, Res, true);
1149   for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI)
1150     ICall.addUse(getOrCreateVReg(**AI));
1151 
1152   unsigned DstAlign = 0, SrcAlign = 0;
1153   unsigned IsVol =
1154       cast<ConstantInt>(CI.getArgOperand(CI.getNumArgOperands() - 1))
1155           ->getZExtValue();
1156 
1157   if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) {
1158     DstAlign = std::max<unsigned>(MCI->getDestAlignment(), 1);
1159     SrcAlign = std::max<unsigned>(MCI->getSourceAlignment(), 1);
1160   } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) {
1161     DstAlign = std::max<unsigned>(MMI->getDestAlignment(), 1);
1162     SrcAlign = std::max<unsigned>(MMI->getSourceAlignment(), 1);
1163   } else {
1164     auto *MSI = cast<MemSetInst>(&CI);
1165     DstAlign = std::max<unsigned>(MSI->getDestAlignment(), 1);
1166   }
1167 
1168   // We need to propagate the tail call flag from the IR inst as an argument.
1169   // Otherwise, we have to pessimize and assume later that we cannot tail call
1170   // any memory intrinsics.
1171   ICall.addImm(CI.isTailCall() ? 1 : 0);
1172 
1173   // Create mem operands to store the alignment and volatile info.
1174   auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
1175   ICall.addMemOperand(MF->getMachineMemOperand(
1176       MachinePointerInfo(CI.getArgOperand(0)),
1177       MachineMemOperand::MOStore | VolFlag, 1, DstAlign));
1178   if (ID != Intrinsic::memset)
1179     ICall.addMemOperand(MF->getMachineMemOperand(
1180         MachinePointerInfo(CI.getArgOperand(1)),
1181         MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign));
1182 
1183   return true;
1184 }
1185 
1186 void IRTranslator::getStackGuard(Register DstReg,
1187                                  MachineIRBuilder &MIRBuilder) {
1188   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1189   MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
1190   auto MIB =
1191       MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {});
1192 
1193   auto &TLI = *MF->getSubtarget().getTargetLowering();
1194   Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
1195   if (!Global)
1196     return;
1197 
1198   MachinePointerInfo MPInfo(Global);
1199   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
1200                MachineMemOperand::MODereferenceable;
1201   MachineMemOperand *MemRef =
1202       MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
1203                                DL->getPointerABIAlignment(0).value());
1204   MIB.setMemRefs({MemRef});
1205 }
1206 
1207 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
1208                                               MachineIRBuilder &MIRBuilder) {
1209   ArrayRef<Register> ResRegs = getOrCreateVRegs(CI);
1210   MIRBuilder.buildInstr(
1211       Op, {ResRegs[0], ResRegs[1]},
1212       {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))});
1213 
1214   return true;
1215 }
1216 
1217 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) {
1218   switch (ID) {
1219     default:
1220       break;
1221     case Intrinsic::bswap:
1222       return TargetOpcode::G_BSWAP;
1223   case Intrinsic::bitreverse:
1224       return TargetOpcode::G_BITREVERSE;
1225     case Intrinsic::ceil:
1226       return TargetOpcode::G_FCEIL;
1227     case Intrinsic::cos:
1228       return TargetOpcode::G_FCOS;
1229     case Intrinsic::ctpop:
1230       return TargetOpcode::G_CTPOP;
1231     case Intrinsic::exp:
1232       return TargetOpcode::G_FEXP;
1233     case Intrinsic::exp2:
1234       return TargetOpcode::G_FEXP2;
1235     case Intrinsic::fabs:
1236       return TargetOpcode::G_FABS;
1237     case Intrinsic::copysign:
1238       return TargetOpcode::G_FCOPYSIGN;
1239     case Intrinsic::minnum:
1240       return TargetOpcode::G_FMINNUM;
1241     case Intrinsic::maxnum:
1242       return TargetOpcode::G_FMAXNUM;
1243     case Intrinsic::minimum:
1244       return TargetOpcode::G_FMINIMUM;
1245     case Intrinsic::maximum:
1246       return TargetOpcode::G_FMAXIMUM;
1247     case Intrinsic::canonicalize:
1248       return TargetOpcode::G_FCANONICALIZE;
1249     case Intrinsic::floor:
1250       return TargetOpcode::G_FFLOOR;
1251     case Intrinsic::fma:
1252       return TargetOpcode::G_FMA;
1253     case Intrinsic::log:
1254       return TargetOpcode::G_FLOG;
1255     case Intrinsic::log2:
1256       return TargetOpcode::G_FLOG2;
1257     case Intrinsic::log10:
1258       return TargetOpcode::G_FLOG10;
1259     case Intrinsic::nearbyint:
1260       return TargetOpcode::G_FNEARBYINT;
1261     case Intrinsic::pow:
1262       return TargetOpcode::G_FPOW;
1263     case Intrinsic::rint:
1264       return TargetOpcode::G_FRINT;
1265     case Intrinsic::round:
1266       return TargetOpcode::G_INTRINSIC_ROUND;
1267     case Intrinsic::sin:
1268       return TargetOpcode::G_FSIN;
1269     case Intrinsic::sqrt:
1270       return TargetOpcode::G_FSQRT;
1271     case Intrinsic::trunc:
1272       return TargetOpcode::G_INTRINSIC_TRUNC;
1273     case Intrinsic::readcyclecounter:
1274       return TargetOpcode::G_READCYCLECOUNTER;
1275   }
1276   return Intrinsic::not_intrinsic;
1277 }
1278 
1279 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI,
1280                                             Intrinsic::ID ID,
1281                                             MachineIRBuilder &MIRBuilder) {
1282 
1283   unsigned Op = getSimpleIntrinsicOpcode(ID);
1284 
1285   // Is this a simple intrinsic?
1286   if (Op == Intrinsic::not_intrinsic)
1287     return false;
1288 
1289   // Yes. Let's translate it.
1290   SmallVector<llvm::SrcOp, 4> VRegs;
1291   for (auto &Arg : CI.arg_operands())
1292     VRegs.push_back(getOrCreateVReg(*Arg));
1293 
1294   MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs,
1295                         MachineInstr::copyFlagsFromInstruction(CI));
1296   return true;
1297 }
1298 
1299 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
1300                                            MachineIRBuilder &MIRBuilder) {
1301 
1302   // If this is a simple intrinsic (that is, we just need to add a def of
1303   // a vreg, and uses for each arg operand, then translate it.
1304   if (translateSimpleIntrinsic(CI, ID, MIRBuilder))
1305     return true;
1306 
1307   switch (ID) {
1308   default:
1309     break;
1310   case Intrinsic::lifetime_start:
1311   case Intrinsic::lifetime_end: {
1312     // No stack colouring in O0, discard region information.
1313     if (MF->getTarget().getOptLevel() == CodeGenOpt::None)
1314       return true;
1315 
1316     unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START
1317                                                   : TargetOpcode::LIFETIME_END;
1318 
1319     // Get the underlying objects for the location passed on the lifetime
1320     // marker.
1321     SmallVector<const Value *, 4> Allocas;
1322     GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL);
1323 
1324     // Iterate over each underlying object, creating lifetime markers for each
1325     // static alloca. Quit if we find a non-static alloca.
1326     for (const Value *V : Allocas) {
1327       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
1328       if (!AI)
1329         continue;
1330 
1331       if (!AI->isStaticAlloca())
1332         return true;
1333 
1334       MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI));
1335     }
1336     return true;
1337   }
1338   case Intrinsic::dbg_declare: {
1339     const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
1340     assert(DI.getVariable() && "Missing variable");
1341 
1342     const Value *Address = DI.getAddress();
1343     if (!Address || isa<UndefValue>(Address)) {
1344       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
1345       return true;
1346     }
1347 
1348     assert(DI.getVariable()->isValidLocationForIntrinsic(
1349                MIRBuilder.getDebugLoc()) &&
1350            "Expected inlined-at fields to agree");
1351     auto AI = dyn_cast<AllocaInst>(Address);
1352     if (AI && AI->isStaticAlloca()) {
1353       // Static allocas are tracked at the MF level, no need for DBG_VALUE
1354       // instructions (in fact, they get ignored if they *do* exist).
1355       MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(),
1356                              getOrCreateFrameIndex(*AI), DI.getDebugLoc());
1357     } else {
1358       // A dbg.declare describes the address of a source variable, so lower it
1359       // into an indirect DBG_VALUE.
1360       MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address),
1361                                        DI.getVariable(), DI.getExpression());
1362     }
1363     return true;
1364   }
1365   case Intrinsic::dbg_label: {
1366     const DbgLabelInst &DI = cast<DbgLabelInst>(CI);
1367     assert(DI.getLabel() && "Missing label");
1368 
1369     assert(DI.getLabel()->isValidLocationForIntrinsic(
1370                MIRBuilder.getDebugLoc()) &&
1371            "Expected inlined-at fields to agree");
1372 
1373     MIRBuilder.buildDbgLabel(DI.getLabel());
1374     return true;
1375   }
1376   case Intrinsic::vaend:
1377     // No target I know of cares about va_end. Certainly no in-tree target
1378     // does. Simplest intrinsic ever!
1379     return true;
1380   case Intrinsic::vastart: {
1381     auto &TLI = *MF->getSubtarget().getTargetLowering();
1382     Value *Ptr = CI.getArgOperand(0);
1383     unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
1384 
1385     // FIXME: Get alignment
1386     MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)})
1387         .addMemOperand(MF->getMachineMemOperand(
1388             MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 1));
1389     return true;
1390   }
1391   case Intrinsic::dbg_value: {
1392     // This form of DBG_VALUE is target-independent.
1393     const DbgValueInst &DI = cast<DbgValueInst>(CI);
1394     const Value *V = DI.getValue();
1395     assert(DI.getVariable()->isValidLocationForIntrinsic(
1396                MIRBuilder.getDebugLoc()) &&
1397            "Expected inlined-at fields to agree");
1398     if (!V) {
1399       // Currently the optimizer can produce this; insert an undef to
1400       // help debugging.  Probably the optimizer should not do this.
1401       MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
1402     } else if (const auto *CI = dyn_cast<Constant>(V)) {
1403       MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
1404     } else {
1405       for (Register Reg : getOrCreateVRegs(*V)) {
1406         // FIXME: This does not handle register-indirect values at offset 0. The
1407         // direct/indirect thing shouldn't really be handled by something as
1408         // implicit as reg+noreg vs reg+imm in the first place, but it seems
1409         // pretty baked in right now.
1410         MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
1411       }
1412     }
1413     return true;
1414   }
1415   case Intrinsic::uadd_with_overflow:
1416     return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder);
1417   case Intrinsic::sadd_with_overflow:
1418     return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
1419   case Intrinsic::usub_with_overflow:
1420     return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder);
1421   case Intrinsic::ssub_with_overflow:
1422     return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
1423   case Intrinsic::umul_with_overflow:
1424     return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
1425   case Intrinsic::smul_with_overflow:
1426     return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
1427   case Intrinsic::uadd_sat:
1428     return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder);
1429   case Intrinsic::sadd_sat:
1430     return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder);
1431   case Intrinsic::usub_sat:
1432     return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder);
1433   case Intrinsic::ssub_sat:
1434     return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder);
1435   case Intrinsic::fmuladd: {
1436     const TargetMachine &TM = MF->getTarget();
1437     const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1438     Register Dst = getOrCreateVReg(CI);
1439     Register Op0 = getOrCreateVReg(*CI.getArgOperand(0));
1440     Register Op1 = getOrCreateVReg(*CI.getArgOperand(1));
1441     Register Op2 = getOrCreateVReg(*CI.getArgOperand(2));
1442     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
1443         TLI.isFMAFasterThanFMulAndFAdd(*MF,
1444                                        TLI.getValueType(*DL, CI.getType()))) {
1445       // TODO: Revisit this to see if we should move this part of the
1446       // lowering to the combiner.
1447       MIRBuilder.buildFMA(Dst, Op0, Op1, Op2,
1448                           MachineInstr::copyFlagsFromInstruction(CI));
1449     } else {
1450       LLT Ty = getLLTForType(*CI.getType(), *DL);
1451       auto FMul = MIRBuilder.buildFMul(
1452           Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI));
1453       MIRBuilder.buildFAdd(Dst, FMul, Op2,
1454                            MachineInstr::copyFlagsFromInstruction(CI));
1455     }
1456     return true;
1457   }
1458   case Intrinsic::memcpy:
1459   case Intrinsic::memmove:
1460   case Intrinsic::memset:
1461     return translateMemFunc(CI, MIRBuilder, ID);
1462   case Intrinsic::eh_typeid_for: {
1463     GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0));
1464     Register Reg = getOrCreateVReg(CI);
1465     unsigned TypeID = MF->getTypeIDFor(GV);
1466     MIRBuilder.buildConstant(Reg, TypeID);
1467     return true;
1468   }
1469   case Intrinsic::objectsize:
1470     llvm_unreachable("llvm.objectsize.* should have been lowered already");
1471 
1472   case Intrinsic::is_constant:
1473     llvm_unreachable("llvm.is.constant.* should have been lowered already");
1474 
1475   case Intrinsic::stackguard:
1476     getStackGuard(getOrCreateVReg(CI), MIRBuilder);
1477     return true;
1478   case Intrinsic::stackprotector: {
1479     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1480     Register GuardVal = MRI->createGenericVirtualRegister(PtrTy);
1481     getStackGuard(GuardVal, MIRBuilder);
1482 
1483     AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
1484     int FI = getOrCreateFrameIndex(*Slot);
1485     MF->getFrameInfo().setStackProtectorIndex(FI);
1486 
1487     MIRBuilder.buildStore(
1488         GuardVal, getOrCreateVReg(*Slot),
1489         *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
1490                                   MachineMemOperand::MOStore |
1491                                       MachineMemOperand::MOVolatile,
1492                                   PtrTy.getSizeInBits() / 8, 8));
1493     return true;
1494   }
1495   case Intrinsic::stacksave: {
1496     // Save the stack pointer to the location provided by the intrinsic.
1497     Register Reg = getOrCreateVReg(CI);
1498     Register StackPtr = MF->getSubtarget()
1499                             .getTargetLowering()
1500                             ->getStackPointerRegisterToSaveRestore();
1501 
1502     // If the target doesn't specify a stack pointer, then fall back.
1503     if (!StackPtr)
1504       return false;
1505 
1506     MIRBuilder.buildCopy(Reg, StackPtr);
1507     return true;
1508   }
1509   case Intrinsic::stackrestore: {
1510     // Restore the stack pointer from the location provided by the intrinsic.
1511     Register Reg = getOrCreateVReg(*CI.getArgOperand(0));
1512     Register StackPtr = MF->getSubtarget()
1513                             .getTargetLowering()
1514                             ->getStackPointerRegisterToSaveRestore();
1515 
1516     // If the target doesn't specify a stack pointer, then fall back.
1517     if (!StackPtr)
1518       return false;
1519 
1520     MIRBuilder.buildCopy(StackPtr, Reg);
1521     return true;
1522   }
1523   case Intrinsic::cttz:
1524   case Intrinsic::ctlz: {
1525     ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1));
1526     bool isTrailing = ID == Intrinsic::cttz;
1527     unsigned Opcode = isTrailing
1528                           ? Cst->isZero() ? TargetOpcode::G_CTTZ
1529                                           : TargetOpcode::G_CTTZ_ZERO_UNDEF
1530                           : Cst->isZero() ? TargetOpcode::G_CTLZ
1531                                           : TargetOpcode::G_CTLZ_ZERO_UNDEF;
1532     MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)},
1533                           {getOrCreateVReg(*CI.getArgOperand(0))});
1534     return true;
1535   }
1536   case Intrinsic::invariant_start: {
1537     LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
1538     Register Undef = MRI->createGenericVirtualRegister(PtrTy);
1539     MIRBuilder.buildUndef(Undef);
1540     return true;
1541   }
1542   case Intrinsic::invariant_end:
1543     return true;
1544   case Intrinsic::assume:
1545   case Intrinsic::var_annotation:
1546   case Intrinsic::sideeffect:
1547     // Discard annotate attributes, assumptions, and artificial side-effects.
1548     return true;
1549   case Intrinsic::read_register: {
1550     Value *Arg = CI.getArgOperand(0);
1551     MIRBuilder
1552         .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {})
1553         .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()));
1554     return true;
1555   }
1556   case Intrinsic::write_register: {
1557     Value *Arg = CI.getArgOperand(0);
1558     MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER)
1559       .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata()))
1560       .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
1561     return true;
1562   }
1563   }
1564   return false;
1565 }
1566 
1567 bool IRTranslator::translateInlineAsm(const CallInst &CI,
1568                                       MachineIRBuilder &MIRBuilder) {
1569   const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
1570   StringRef ConstraintStr = IA.getConstraintString();
1571 
1572   bool HasOnlyMemoryClobber = false;
1573   if (!ConstraintStr.empty()) {
1574     // Until we have full inline assembly support, we just try to handle the
1575     // very simple case of just "~{memory}" to avoid falling back so often.
1576     if (ConstraintStr != "~{memory}")
1577       return false;
1578     HasOnlyMemoryClobber = true;
1579   }
1580 
1581   unsigned ExtraInfo = 0;
1582   if (IA.hasSideEffects())
1583     ExtraInfo |= InlineAsm::Extra_HasSideEffects;
1584   if (IA.getDialect() == InlineAsm::AD_Intel)
1585     ExtraInfo |= InlineAsm::Extra_AsmDialect;
1586 
1587   // HACK: special casing for ~memory.
1588   if (HasOnlyMemoryClobber)
1589     ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
1590 
1591   auto Inst = MIRBuilder.buildInstr(TargetOpcode::INLINEASM)
1592                   .addExternalSymbol(IA.getAsmString().c_str())
1593                   .addImm(ExtraInfo);
1594   if (const MDNode *SrcLoc = CI.getMetadata("srcloc"))
1595     Inst.addMetadata(SrcLoc);
1596 
1597   return true;
1598 }
1599 
1600 bool IRTranslator::translateCallSite(const ImmutableCallSite &CS,
1601                                      MachineIRBuilder &MIRBuilder) {
1602   const Instruction &I = *CS.getInstruction();
1603   ArrayRef<Register> Res = getOrCreateVRegs(I);
1604 
1605   SmallVector<ArrayRef<Register>, 8> Args;
1606   Register SwiftInVReg = 0;
1607   Register SwiftErrorVReg = 0;
1608   for (auto &Arg : CS.args()) {
1609     if (CLI->supportSwiftError() && isSwiftError(Arg)) {
1610       assert(SwiftInVReg == 0 && "Expected only one swift error argument");
1611       LLT Ty = getLLTForType(*Arg->getType(), *DL);
1612       SwiftInVReg = MRI->createGenericVirtualRegister(Ty);
1613       MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt(
1614                                             &I, &MIRBuilder.getMBB(), Arg));
1615       Args.emplace_back(makeArrayRef(SwiftInVReg));
1616       SwiftErrorVReg =
1617           SwiftError.getOrCreateVRegDefAt(&I, &MIRBuilder.getMBB(), Arg);
1618       continue;
1619     }
1620     Args.push_back(getOrCreateVRegs(*Arg));
1621   }
1622 
1623   // We don't set HasCalls on MFI here yet because call lowering may decide to
1624   // optimize into tail calls. Instead, we defer that to selection where a final
1625   // scan is done to check if any instructions are calls.
1626   bool Success =
1627       CLI->lowerCall(MIRBuilder, CS, Res, Args, SwiftErrorVReg,
1628                      [&]() { return getOrCreateVReg(*CS.getCalledValue()); });
1629 
1630   // Check if we just inserted a tail call.
1631   if (Success) {
1632     assert(!HasTailCall && "Can't tail call return twice from block?");
1633     const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1634     HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt()));
1635   }
1636 
1637   return Success;
1638 }
1639 
1640 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
1641   const CallInst &CI = cast<CallInst>(U);
1642   auto TII = MF->getTarget().getIntrinsicInfo();
1643   const Function *F = CI.getCalledFunction();
1644 
1645   // FIXME: support Windows dllimport function calls.
1646   if (F && (F->hasDLLImportStorageClass() ||
1647             (MF->getTarget().getTargetTriple().isOSWindows() &&
1648              F->hasExternalWeakLinkage())))
1649     return false;
1650 
1651   // FIXME: support control flow guard targets.
1652   if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
1653     return false;
1654 
1655   if (CI.isInlineAsm())
1656     return translateInlineAsm(CI, MIRBuilder);
1657 
1658   Intrinsic::ID ID = Intrinsic::not_intrinsic;
1659   if (F && F->isIntrinsic()) {
1660     ID = F->getIntrinsicID();
1661     if (TII && ID == Intrinsic::not_intrinsic)
1662       ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
1663   }
1664 
1665   if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic)
1666     return translateCallSite(&CI, MIRBuilder);
1667 
1668   assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1669 
1670   if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1671     return true;
1672 
1673   ArrayRef<Register> ResultRegs;
1674   if (!CI.getType()->isVoidTy())
1675     ResultRegs = getOrCreateVRegs(CI);
1676 
1677   // Ignore the callsite attributes. Backend code is most likely not expecting
1678   // an intrinsic to sometimes have side effects and sometimes not.
1679   MachineInstrBuilder MIB =
1680       MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory());
1681   if (isa<FPMathOperator>(CI))
1682     MIB->copyIRFlags(CI);
1683 
1684   for (auto &Arg : enumerate(CI.arg_operands())) {
1685     // Some intrinsics take metadata parameters. Reject them.
1686     if (isa<MetadataAsValue>(Arg.value()))
1687       return false;
1688 
1689     // If this is required to be an immediate, don't materialize it in a
1690     // register.
1691     if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) {
1692       if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) {
1693         // imm arguments are more convenient than cimm (and realistically
1694         // probably sufficient), so use them.
1695         assert(CI->getBitWidth() <= 64 &&
1696                "large intrinsic immediates not handled");
1697         MIB.addImm(CI->getSExtValue());
1698       } else {
1699         MIB.addFPImm(cast<ConstantFP>(Arg.value()));
1700       }
1701     } else {
1702       ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value());
1703       if (VRegs.size() > 1)
1704         return false;
1705       MIB.addUse(VRegs[0]);
1706     }
1707   }
1708 
1709   // Add a MachineMemOperand if it is a target mem intrinsic.
1710   const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1711   TargetLowering::IntrinsicInfo Info;
1712   // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
1713   if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
1714     MaybeAlign Align = Info.align;
1715     if (!Align)
1716       Align = MaybeAlign(
1717           DL->getABITypeAlignment(Info.memVT.getTypeForEVT(F->getContext())));
1718 
1719     uint64_t Size = Info.memVT.getStoreSize();
1720     MIB.addMemOperand(MF->getMachineMemOperand(
1721         MachinePointerInfo(Info.ptrVal), Info.flags, Size, Align->value()));
1722   }
1723 
1724   return true;
1725 }
1726 
1727 bool IRTranslator::translateInvoke(const User &U,
1728                                    MachineIRBuilder &MIRBuilder) {
1729   const InvokeInst &I = cast<InvokeInst>(U);
1730   MCContext &Context = MF->getContext();
1731 
1732   const BasicBlock *ReturnBB = I.getSuccessor(0);
1733   const BasicBlock *EHPadBB = I.getSuccessor(1);
1734 
1735   const Value *Callee = I.getCalledValue();
1736   const Function *Fn = dyn_cast<Function>(Callee);
1737   if (isa<InlineAsm>(Callee))
1738     return false;
1739 
1740   // FIXME: support invoking patchpoint and statepoint intrinsics.
1741   if (Fn && Fn->isIntrinsic())
1742     return false;
1743 
1744   // FIXME: support whatever these are.
1745   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
1746     return false;
1747 
1748   // FIXME: support control flow guard targets.
1749   if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget))
1750     return false;
1751 
1752   // FIXME: support Windows exception handling.
1753   if (!isa<LandingPadInst>(EHPadBB->front()))
1754     return false;
1755 
1756   // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
1757   // the region covered by the try.
1758   MCSymbol *BeginSymbol = Context.createTempSymbol();
1759   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1760 
1761   if (!translateCallSite(&I, MIRBuilder))
1762     return false;
1763 
1764   MCSymbol *EndSymbol = Context.createTempSymbol();
1765   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1766 
1767   // FIXME: track probabilities.
1768   MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1769                     &ReturnMBB = getMBB(*ReturnBB);
1770   MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1771   MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1772   MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
1773   MIRBuilder.buildBr(ReturnMBB);
1774 
1775   return true;
1776 }
1777 
1778 bool IRTranslator::translateCallBr(const User &U,
1779                                    MachineIRBuilder &MIRBuilder) {
1780   // FIXME: Implement this.
1781   return false;
1782 }
1783 
1784 bool IRTranslator::translateLandingPad(const User &U,
1785                                        MachineIRBuilder &MIRBuilder) {
1786   const LandingPadInst &LP = cast<LandingPadInst>(U);
1787 
1788   MachineBasicBlock &MBB = MIRBuilder.getMBB();
1789 
1790   MBB.setIsEHPad();
1791 
1792   // If there aren't registers to copy the values into (e.g., during SjLj
1793   // exceptions), then don't bother.
1794   auto &TLI = *MF->getSubtarget().getTargetLowering();
1795   const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1796   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1797       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1798     return true;
1799 
1800   // If landingpad's return type is token type, we don't create DAG nodes
1801   // for its exception pointer and selector value. The extraction of exception
1802   // pointer or selector value from token type landingpads is not currently
1803   // supported.
1804   if (LP.getType()->isTokenTy())
1805     return true;
1806 
1807   // Add a label to mark the beginning of the landing pad.  Deletion of the
1808   // landing pad can thus be detected via the MachineModuleInfo.
1809   MIRBuilder.buildInstr(TargetOpcode::EH_LABEL)
1810     .addSym(MF->addLandingPad(&MBB));
1811 
1812   LLT Ty = getLLTForType(*LP.getType(), *DL);
1813   Register Undef = MRI->createGenericVirtualRegister(Ty);
1814   MIRBuilder.buildUndef(Undef);
1815 
1816   SmallVector<LLT, 2> Tys;
1817   for (Type *Ty : cast<StructType>(LP.getType())->elements())
1818     Tys.push_back(getLLTForType(*Ty, *DL));
1819   assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1820 
1821   // Mark exception register as live in.
1822   Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1823   if (!ExceptionReg)
1824     return false;
1825 
1826   MBB.addLiveIn(ExceptionReg);
1827   ArrayRef<Register> ResRegs = getOrCreateVRegs(LP);
1828   MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
1829 
1830   Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1831   if (!SelectorReg)
1832     return false;
1833 
1834   MBB.addLiveIn(SelectorReg);
1835   Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1836   MIRBuilder.buildCopy(PtrVReg, SelectorReg);
1837   MIRBuilder.buildCast(ResRegs[1], PtrVReg);
1838 
1839   return true;
1840 }
1841 
1842 bool IRTranslator::translateAlloca(const User &U,
1843                                    MachineIRBuilder &MIRBuilder) {
1844   auto &AI = cast<AllocaInst>(U);
1845 
1846   if (AI.isSwiftError())
1847     return true;
1848 
1849   if (AI.isStaticAlloca()) {
1850     Register Res = getOrCreateVReg(AI);
1851     int FI = getOrCreateFrameIndex(AI);
1852     MIRBuilder.buildFrameIndex(Res, FI);
1853     return true;
1854   }
1855 
1856   // FIXME: support stack probing for Windows.
1857   if (MF->getTarget().getTargetTriple().isOSWindows())
1858     return false;
1859 
1860   // Now we're in the harder dynamic case.
1861   Type *Ty = AI.getAllocatedType();
1862   unsigned Align =
1863       std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1864 
1865   Register NumElts = getOrCreateVReg(*AI.getArraySize());
1866 
1867   Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1868   LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
1869   if (MRI->getType(NumElts) != IntPtrTy) {
1870     Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1871     MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1872     NumElts = ExtElts;
1873   }
1874 
1875   Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
1876   Register TySize =
1877       getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty)));
1878   MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1879 
1880   unsigned StackAlign =
1881       MF->getSubtarget().getFrameLowering()->getStackAlignment();
1882   if (Align <= StackAlign)
1883     Align = 0;
1884 
1885   // Round the size of the allocation up to the stack alignment size
1886   // by add SA-1 to the size. This doesn't overflow because we're computing
1887   // an address inside an alloca.
1888   auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign - 1);
1889   auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne,
1890                                       MachineInstr::NoUWrap);
1891   auto AlignCst =
1892       MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign - 1));
1893   auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst);
1894 
1895   MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Align);
1896 
1897   MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1898   assert(MF->getFrameInfo().hasVarSizedObjects());
1899   return true;
1900 }
1901 
1902 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1903   // FIXME: We may need more info about the type. Because of how LLT works,
1904   // we're completely discarding the i64/double distinction here (amongst
1905   // others). Fortunately the ABIs I know of where that matters don't use va_arg
1906   // anyway but that's not guaranteed.
1907   MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)},
1908                         {getOrCreateVReg(*U.getOperand(0)),
1909                          uint64_t(DL->getABITypeAlignment(U.getType()))});
1910   return true;
1911 }
1912 
1913 bool IRTranslator::translateInsertElement(const User &U,
1914                                           MachineIRBuilder &MIRBuilder) {
1915   // If it is a <1 x Ty> vector, use the scalar as it is
1916   // not a legal vector type in LLT.
1917   if (U.getType()->getVectorNumElements() == 1) {
1918     Register Elt = getOrCreateVReg(*U.getOperand(1));
1919     auto &Regs = *VMap.getVRegs(U);
1920     if (Regs.empty()) {
1921       Regs.push_back(Elt);
1922       VMap.getOffsets(U)->push_back(0);
1923     } else {
1924       MIRBuilder.buildCopy(Regs[0], Elt);
1925     }
1926     return true;
1927   }
1928 
1929   Register Res = getOrCreateVReg(U);
1930   Register Val = getOrCreateVReg(*U.getOperand(0));
1931   Register Elt = getOrCreateVReg(*U.getOperand(1));
1932   Register Idx = getOrCreateVReg(*U.getOperand(2));
1933   MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
1934   return true;
1935 }
1936 
1937 bool IRTranslator::translateExtractElement(const User &U,
1938                                            MachineIRBuilder &MIRBuilder) {
1939   // If it is a <1 x Ty> vector, use the scalar as it is
1940   // not a legal vector type in LLT.
1941   if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1942     Register Elt = getOrCreateVReg(*U.getOperand(0));
1943     auto &Regs = *VMap.getVRegs(U);
1944     if (Regs.empty()) {
1945       Regs.push_back(Elt);
1946       VMap.getOffsets(U)->push_back(0);
1947     } else {
1948       MIRBuilder.buildCopy(Regs[0], Elt);
1949     }
1950     return true;
1951   }
1952   Register Res = getOrCreateVReg(U);
1953   Register Val = getOrCreateVReg(*U.getOperand(0));
1954   const auto &TLI = *MF->getSubtarget().getTargetLowering();
1955   unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits();
1956   Register Idx;
1957   if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) {
1958     if (CI->getBitWidth() != PreferredVecIdxWidth) {
1959       APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth);
1960       auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx);
1961       Idx = getOrCreateVReg(*NewIdxCI);
1962     }
1963   }
1964   if (!Idx)
1965     Idx = getOrCreateVReg(*U.getOperand(1));
1966   if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) {
1967     const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth);
1968     Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx).getReg(0);
1969   }
1970   MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
1971   return true;
1972 }
1973 
1974 bool IRTranslator::translateShuffleVector(const User &U,
1975                                           MachineIRBuilder &MIRBuilder) {
1976   SmallVector<int, 8> Mask;
1977   ShuffleVectorInst::getShuffleMask(cast<Constant>(U.getOperand(2)), Mask);
1978   ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask);
1979   MIRBuilder
1980       .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)},
1981                   {getOrCreateVReg(*U.getOperand(0)),
1982                    getOrCreateVReg(*U.getOperand(1))})
1983       .addShuffleMask(MaskAlloc);
1984   return true;
1985 }
1986 
1987 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1988   const PHINode &PI = cast<PHINode>(U);
1989 
1990   SmallVector<MachineInstr *, 4> Insts;
1991   for (auto Reg : getOrCreateVRegs(PI)) {
1992     auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {});
1993     Insts.push_back(MIB.getInstr());
1994   }
1995 
1996   PendingPHIs.emplace_back(&PI, std::move(Insts));
1997   return true;
1998 }
1999 
2000 bool IRTranslator::translateAtomicCmpXchg(const User &U,
2001                                           MachineIRBuilder &MIRBuilder) {
2002   const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
2003 
2004   if (I.isWeak())
2005     return false;
2006 
2007   auto &TLI = *MF->getSubtarget().getTargetLowering();
2008   auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
2009 
2010   Type *ResType = I.getType();
2011   Type *ValType = ResType->Type::getStructElementType(0);
2012 
2013   auto Res = getOrCreateVRegs(I);
2014   Register OldValRes = Res[0];
2015   Register SuccessRes = Res[1];
2016   Register Addr = getOrCreateVReg(*I.getPointerOperand());
2017   Register Cmp = getOrCreateVReg(*I.getCompareOperand());
2018   Register NewVal = getOrCreateVReg(*I.getNewValOperand());
2019 
2020   AAMDNodes AAMetadata;
2021   I.getAAMetadata(AAMetadata);
2022 
2023   MIRBuilder.buildAtomicCmpXchgWithSuccess(
2024       OldValRes, SuccessRes, Addr, Cmp, NewVal,
2025       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
2026                                 Flags, DL->getTypeStoreSize(ValType),
2027                                 getMemOpAlignment(I), AAMetadata, nullptr,
2028                                 I.getSyncScopeID(), I.getSuccessOrdering(),
2029                                 I.getFailureOrdering()));
2030   return true;
2031 }
2032 
2033 bool IRTranslator::translateAtomicRMW(const User &U,
2034                                       MachineIRBuilder &MIRBuilder) {
2035   const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
2036   auto &TLI = *MF->getSubtarget().getTargetLowering();
2037   auto Flags = TLI.getAtomicMemOperandFlags(I, *DL);
2038 
2039   Type *ResType = I.getType();
2040 
2041   Register Res = getOrCreateVReg(I);
2042   Register Addr = getOrCreateVReg(*I.getPointerOperand());
2043   Register Val = getOrCreateVReg(*I.getValOperand());
2044 
2045   unsigned Opcode = 0;
2046   switch (I.getOperation()) {
2047   default:
2048     return false;
2049   case AtomicRMWInst::Xchg:
2050     Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
2051     break;
2052   case AtomicRMWInst::Add:
2053     Opcode = TargetOpcode::G_ATOMICRMW_ADD;
2054     break;
2055   case AtomicRMWInst::Sub:
2056     Opcode = TargetOpcode::G_ATOMICRMW_SUB;
2057     break;
2058   case AtomicRMWInst::And:
2059     Opcode = TargetOpcode::G_ATOMICRMW_AND;
2060     break;
2061   case AtomicRMWInst::Nand:
2062     Opcode = TargetOpcode::G_ATOMICRMW_NAND;
2063     break;
2064   case AtomicRMWInst::Or:
2065     Opcode = TargetOpcode::G_ATOMICRMW_OR;
2066     break;
2067   case AtomicRMWInst::Xor:
2068     Opcode = TargetOpcode::G_ATOMICRMW_XOR;
2069     break;
2070   case AtomicRMWInst::Max:
2071     Opcode = TargetOpcode::G_ATOMICRMW_MAX;
2072     break;
2073   case AtomicRMWInst::Min:
2074     Opcode = TargetOpcode::G_ATOMICRMW_MIN;
2075     break;
2076   case AtomicRMWInst::UMax:
2077     Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
2078     break;
2079   case AtomicRMWInst::UMin:
2080     Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
2081     break;
2082   case AtomicRMWInst::FAdd:
2083     Opcode = TargetOpcode::G_ATOMICRMW_FADD;
2084     break;
2085   case AtomicRMWInst::FSub:
2086     Opcode = TargetOpcode::G_ATOMICRMW_FSUB;
2087     break;
2088   }
2089 
2090   AAMDNodes AAMetadata;
2091   I.getAAMetadata(AAMetadata);
2092 
2093   MIRBuilder.buildAtomicRMW(
2094       Opcode, Res, Addr, Val,
2095       *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
2096                                 Flags, DL->getTypeStoreSize(ResType),
2097                                 getMemOpAlignment(I), AAMetadata,
2098                                 nullptr, I.getSyncScopeID(), I.getOrdering()));
2099   return true;
2100 }
2101 
2102 bool IRTranslator::translateFence(const User &U,
2103                                   MachineIRBuilder &MIRBuilder) {
2104   const FenceInst &Fence = cast<FenceInst>(U);
2105   MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()),
2106                         Fence.getSyncScopeID());
2107   return true;
2108 }
2109 
2110 void IRTranslator::finishPendingPhis() {
2111 #ifndef NDEBUG
2112   DILocationVerifier Verifier;
2113   GISelObserverWrapper WrapperObserver(&Verifier);
2114   RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2115 #endif // ifndef NDEBUG
2116   for (auto &Phi : PendingPHIs) {
2117     const PHINode *PI = Phi.first;
2118     ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
2119     MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent();
2120     EntryBuilder->setDebugLoc(PI->getDebugLoc());
2121 #ifndef NDEBUG
2122     Verifier.setCurrentInst(PI);
2123 #endif // ifndef NDEBUG
2124 
2125     SmallSet<const MachineBasicBlock *, 16> SeenPreds;
2126     for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
2127       auto IRPred = PI->getIncomingBlock(i);
2128       ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
2129       for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
2130         if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred))
2131           continue;
2132         SeenPreds.insert(Pred);
2133         for (unsigned j = 0; j < ValRegs.size(); ++j) {
2134           MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
2135           MIB.addUse(ValRegs[j]);
2136           MIB.addMBB(Pred);
2137         }
2138       }
2139     }
2140   }
2141 }
2142 
2143 bool IRTranslator::valueIsSplit(const Value &V,
2144                                 SmallVectorImpl<uint64_t> *Offsets) {
2145   SmallVector<LLT, 4> SplitTys;
2146   if (Offsets && !Offsets->empty())
2147     Offsets->clear();
2148   computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
2149   return SplitTys.size() > 1;
2150 }
2151 
2152 bool IRTranslator::translate(const Instruction &Inst) {
2153   CurBuilder->setDebugLoc(Inst.getDebugLoc());
2154   // We only emit constants into the entry block from here. To prevent jumpy
2155   // debug behaviour set the line to 0.
2156   if (const DebugLoc &DL = Inst.getDebugLoc())
2157     EntryBuilder->setDebugLoc(
2158         DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt()));
2159   else
2160     EntryBuilder->setDebugLoc(DebugLoc());
2161 
2162   switch (Inst.getOpcode()) {
2163 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2164   case Instruction::OPCODE:                                                    \
2165     return translate##OPCODE(Inst, *CurBuilder.get());
2166 #include "llvm/IR/Instruction.def"
2167   default:
2168     return false;
2169   }
2170 }
2171 
2172 bool IRTranslator::translate(const Constant &C, Register Reg) {
2173   if (auto CI = dyn_cast<ConstantInt>(&C))
2174     EntryBuilder->buildConstant(Reg, *CI);
2175   else if (auto CF = dyn_cast<ConstantFP>(&C))
2176     EntryBuilder->buildFConstant(Reg, *CF);
2177   else if (isa<UndefValue>(C))
2178     EntryBuilder->buildUndef(Reg);
2179   else if (isa<ConstantPointerNull>(C)) {
2180     // As we are trying to build a constant val of 0 into a pointer,
2181     // insert a cast to make them correct with respect to types.
2182     unsigned NullSize = DL->getTypeSizeInBits(C.getType());
2183     auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
2184     auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
2185     Register ZeroReg = getOrCreateVReg(*ZeroVal);
2186     EntryBuilder->buildCast(Reg, ZeroReg);
2187   } else if (auto GV = dyn_cast<GlobalValue>(&C))
2188     EntryBuilder->buildGlobalValue(Reg, GV);
2189   else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
2190     if (!CAZ->getType()->isVectorTy())
2191       return false;
2192     // Return the scalar if it is a <1 x Ty> vector.
2193     if (CAZ->getNumElements() == 1)
2194       return translate(*CAZ->getElementValue(0u), Reg);
2195     SmallVector<Register, 4> Ops;
2196     for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
2197       Constant &Elt = *CAZ->getElementValue(i);
2198       Ops.push_back(getOrCreateVReg(Elt));
2199     }
2200     EntryBuilder->buildBuildVector(Reg, Ops);
2201   } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
2202     // Return the scalar if it is a <1 x Ty> vector.
2203     if (CV->getNumElements() == 1)
2204       return translate(*CV->getElementAsConstant(0), Reg);
2205     SmallVector<Register, 4> Ops;
2206     for (unsigned i = 0; i < CV->getNumElements(); ++i) {
2207       Constant &Elt = *CV->getElementAsConstant(i);
2208       Ops.push_back(getOrCreateVReg(Elt));
2209     }
2210     EntryBuilder->buildBuildVector(Reg, Ops);
2211   } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
2212     switch(CE->getOpcode()) {
2213 #define HANDLE_INST(NUM, OPCODE, CLASS)                                        \
2214   case Instruction::OPCODE:                                                    \
2215     return translate##OPCODE(*CE, *EntryBuilder.get());
2216 #include "llvm/IR/Instruction.def"
2217     default:
2218       return false;
2219     }
2220   } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
2221     if (CV->getNumOperands() == 1)
2222       return translate(*CV->getOperand(0), Reg);
2223     SmallVector<Register, 4> Ops;
2224     for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
2225       Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
2226     }
2227     EntryBuilder->buildBuildVector(Reg, Ops);
2228   } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
2229     EntryBuilder->buildBlockAddress(Reg, BA);
2230   } else
2231     return false;
2232 
2233   return true;
2234 }
2235 
2236 void IRTranslator::finalizeBasicBlock() {
2237   for (auto &JTCase : SL->JTCases) {
2238     // Emit header first, if it wasn't already emitted.
2239     if (!JTCase.first.Emitted)
2240       emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB);
2241 
2242     emitJumpTable(JTCase.second, JTCase.second.MBB);
2243   }
2244   SL->JTCases.clear();
2245 }
2246 
2247 void IRTranslator::finalizeFunction() {
2248   // Release the memory used by the different maps we
2249   // needed during the translation.
2250   PendingPHIs.clear();
2251   VMap.reset();
2252   FrameIndices.clear();
2253   MachinePreds.clear();
2254   // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
2255   // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
2256   // destroying it twice (in ~IRTranslator() and ~LLVMContext())
2257   EntryBuilder.reset();
2258   CurBuilder.reset();
2259   FuncInfo.clear();
2260 }
2261 
2262 /// Returns true if a BasicBlock \p BB within a variadic function contains a
2263 /// variadic musttail call.
2264 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) {
2265   if (!IsVarArg)
2266     return false;
2267 
2268   // Walk the block backwards, because tail calls usually only appear at the end
2269   // of a block.
2270   return std::any_of(BB.rbegin(), BB.rend(), [](const Instruction &I) {
2271     const auto *CI = dyn_cast<CallInst>(&I);
2272     return CI && CI->isMustTailCall();
2273   });
2274 }
2275 
2276 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) {
2277   MF = &CurMF;
2278   const Function &F = MF->getFunction();
2279   if (F.empty())
2280     return false;
2281   GISelCSEAnalysisWrapper &Wrapper =
2282       getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper();
2283   // Set the CSEConfig and run the analysis.
2284   GISelCSEInfo *CSEInfo = nullptr;
2285   TPC = &getAnalysis<TargetPassConfig>();
2286   bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences()
2287                        ? EnableCSEInIRTranslator
2288                        : TPC->isGISelCSEEnabled();
2289 
2290   if (EnableCSE) {
2291     EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2292     CSEInfo = &Wrapper.get(TPC->getCSEConfig());
2293     EntryBuilder->setCSEInfo(CSEInfo);
2294     CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF);
2295     CurBuilder->setCSEInfo(CSEInfo);
2296   } else {
2297     EntryBuilder = std::make_unique<MachineIRBuilder>();
2298     CurBuilder = std::make_unique<MachineIRBuilder>();
2299   }
2300   CLI = MF->getSubtarget().getCallLowering();
2301   CurBuilder->setMF(*MF);
2302   EntryBuilder->setMF(*MF);
2303   MRI = &MF->getRegInfo();
2304   DL = &F.getParent()->getDataLayout();
2305   ORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2306   FuncInfo.MF = MF;
2307   FuncInfo.BPI = nullptr;
2308   const auto &TLI = *MF->getSubtarget().getTargetLowering();
2309   const TargetMachine &TM = MF->getTarget();
2310   SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo);
2311   SL->init(TLI, TM, *DL);
2312 
2313   EnableOpts = TM.getOptLevel() != CodeGenOpt::None && !skipFunction(F);
2314 
2315   assert(PendingPHIs.empty() && "stale PHIs");
2316 
2317   if (!DL->isLittleEndian()) {
2318     // Currently we don't properly handle big endian code.
2319     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2320                                F.getSubprogram(), &F.getEntryBlock());
2321     R << "unable to translate in big endian mode";
2322     reportTranslationError(*MF, *TPC, *ORE, R);
2323   }
2324 
2325   // Release the per-function state when we return, whether we succeeded or not.
2326   auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
2327 
2328   // Setup a separate basic-block for the arguments and constants
2329   MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
2330   MF->push_back(EntryBB);
2331   EntryBuilder->setMBB(*EntryBB);
2332 
2333   DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc();
2334   SwiftError.setFunction(CurMF);
2335   SwiftError.createEntriesInEntryBlock(DbgLoc);
2336 
2337   bool IsVarArg = F.isVarArg();
2338   bool HasMustTailInVarArgFn = false;
2339 
2340   // Create all blocks, in IR order, to preserve the layout.
2341   for (const BasicBlock &BB: F) {
2342     auto *&MBB = BBToMBB[&BB];
2343 
2344     MBB = MF->CreateMachineBasicBlock(&BB);
2345     MF->push_back(MBB);
2346 
2347     if (BB.hasAddressTaken())
2348       MBB->setHasAddressTaken();
2349 
2350     if (!HasMustTailInVarArgFn)
2351       HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB);
2352   }
2353 
2354   MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn);
2355 
2356   // Make our arguments/constants entry block fallthrough to the IR entry block.
2357   EntryBB->addSuccessor(&getMBB(F.front()));
2358 
2359   // Lower the actual args into this basic block.
2360   SmallVector<ArrayRef<Register>, 8> VRegArgs;
2361   for (const Argument &Arg: F.args()) {
2362     if (DL->getTypeStoreSize(Arg.getType()) == 0)
2363       continue; // Don't handle zero sized types.
2364     ArrayRef<Register> VRegs = getOrCreateVRegs(Arg);
2365     VRegArgs.push_back(VRegs);
2366 
2367     if (Arg.hasSwiftErrorAttr()) {
2368       assert(VRegs.size() == 1 && "Too many vregs for Swift error");
2369       SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]);
2370     }
2371   }
2372 
2373   if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) {
2374     OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2375                                F.getSubprogram(), &F.getEntryBlock());
2376     R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
2377     reportTranslationError(*MF, *TPC, *ORE, R);
2378     return false;
2379   }
2380 
2381   // Need to visit defs before uses when translating instructions.
2382   GISelObserverWrapper WrapperObserver;
2383   if (EnableCSE && CSEInfo)
2384     WrapperObserver.addObserver(CSEInfo);
2385   {
2386     ReversePostOrderTraversal<const Function *> RPOT(&F);
2387 #ifndef NDEBUG
2388     DILocationVerifier Verifier;
2389     WrapperObserver.addObserver(&Verifier);
2390 #endif // ifndef NDEBUG
2391     RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver);
2392     RAIIMFObserverInstaller ObsInstall(*MF, WrapperObserver);
2393     for (const BasicBlock *BB : RPOT) {
2394       MachineBasicBlock &MBB = getMBB(*BB);
2395       // Set the insertion point of all the following translations to
2396       // the end of this basic block.
2397       CurBuilder->setMBB(MBB);
2398       HasTailCall = false;
2399       for (const Instruction &Inst : *BB) {
2400         // If we translated a tail call in the last step, then we know
2401         // everything after the call is either a return, or something that is
2402         // handled by the call itself. (E.g. a lifetime marker or assume
2403         // intrinsic.) In this case, we should stop translating the block and
2404         // move on.
2405         if (HasTailCall)
2406           break;
2407 #ifndef NDEBUG
2408         Verifier.setCurrentInst(&Inst);
2409 #endif // ifndef NDEBUG
2410         if (translate(Inst))
2411           continue;
2412 
2413         OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
2414                                    Inst.getDebugLoc(), BB);
2415         R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
2416 
2417         if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
2418           std::string InstStrStorage;
2419           raw_string_ostream InstStr(InstStrStorage);
2420           InstStr << Inst;
2421 
2422           R << ": '" << InstStr.str() << "'";
2423         }
2424 
2425         reportTranslationError(*MF, *TPC, *ORE, R);
2426         return false;
2427       }
2428 
2429       finalizeBasicBlock();
2430     }
2431 #ifndef NDEBUG
2432     WrapperObserver.removeObserver(&Verifier);
2433 #endif
2434   }
2435 
2436   finishPendingPhis();
2437 
2438   SwiftError.propagateVRegs();
2439 
2440   // Merge the argument lowering and constants block with its single
2441   // successor, the LLVM-IR entry block.  We want the basic block to
2442   // be maximal.
2443   assert(EntryBB->succ_size() == 1 &&
2444          "Custom BB used for lowering should have only one successor");
2445   // Get the successor of the current entry block.
2446   MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
2447   assert(NewEntryBB.pred_size() == 1 &&
2448          "LLVM-IR entry block has a predecessor!?");
2449   // Move all the instruction from the current entry block to the
2450   // new entry block.
2451   NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
2452                     EntryBB->end());
2453 
2454   // Update the live-in information for the new entry block.
2455   for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
2456     NewEntryBB.addLiveIn(LiveIn);
2457   NewEntryBB.sortUniqueLiveIns();
2458 
2459   // Get rid of the now empty basic block.
2460   EntryBB->removeSuccessor(&NewEntryBB);
2461   MF->remove(EntryBB);
2462   MF->DeleteMachineBasicBlock(EntryBB);
2463 
2464   assert(&MF->front() == &NewEntryBB &&
2465          "New entry wasn't next in the list of basic block!");
2466 
2467   // Initialize stack protector information.
2468   StackProtector &SP = getAnalysis<StackProtector>();
2469   SP.copyToMachineFrameInfo(MF->getFrameInfo());
2470 
2471   return false;
2472 }
2473