OSDN Git Service

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