LLVM  7.0.0
IRTranslator.cpp
Go to the documentation of this file.
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 
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/Analysis.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/CFG.h"
38 #include "llvm/IR/Constant.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DebugInfo.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
45 #include "llvm/IR/InlineAsm.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/User.h"
54 #include "llvm/IR/Value.h"
55 #include "llvm/MC/MCContext.h"
56 #include "llvm/Pass.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/CodeGen.h"
59 #include "llvm/Support/Debug.h"
66 #include <algorithm>
67 #include <cassert>
68 #include <cstdint>
69 #include <iterator>
70 #include <string>
71 #include <utility>
72 #include <vector>
73 
74 #define DEBUG_TYPE "irtranslator"
75 
76 using namespace llvm;
77 
78 char IRTranslator::ID = 0;
79 
80 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
81  false, false)
83 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI",
84  false, false)
85 
91 
92  // Print the function name explicitly if we don't have a debug location (which
93  // makes the diagnostic less useful) or if we're going to emit a raw error.
94  if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled())
95  R << (" (in function: " + MF.getName() + ")").str();
96 
97  if (TPC.isGlobalISelAbortEnabled())
98  report_fatal_error(R.getMsg());
99  else
100  ORE.emit(R);
101 }
102 
105 }
106 
112 }
113 
114 static void computeValueLLTs(const DataLayout &DL, Type &Ty,
115  SmallVectorImpl<LLT> &ValueTys,
117  uint64_t StartingOffset = 0) {
118  // Given a struct type, recursively traverse the elements.
119  if (StructType *STy = dyn_cast<StructType>(&Ty)) {
120  const StructLayout *SL = DL.getStructLayout(STy);
121  for (unsigned I = 0, E = STy->getNumElements(); I != E; ++I)
122  computeValueLLTs(DL, *STy->getElementType(I), ValueTys, Offsets,
123  StartingOffset + SL->getElementOffset(I));
124  return;
125  }
126  // Given an array type, recursively traverse the elements.
127  if (ArrayType *ATy = dyn_cast<ArrayType>(&Ty)) {
128  Type *EltTy = ATy->getElementType();
129  uint64_t EltSize = DL.getTypeAllocSize(EltTy);
130  for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
131  computeValueLLTs(DL, *EltTy, ValueTys, Offsets,
132  StartingOffset + i * EltSize);
133  return;
134  }
135  // Interpret void as zero return values.
136  if (Ty.isVoidTy())
137  return;
138  // Base case: we can get an LLT for this LLVM IR type.
139  ValueTys.push_back(getLLTForType(Ty, DL));
140  if (Offsets != nullptr)
141  Offsets->push_back(StartingOffset * 8);
142 }
143 
145 IRTranslator::allocateVRegs(const Value &Val) {
146  assert(!VMap.contains(Val) && "Value already allocated in VMap");
147  auto *Regs = VMap.getVRegs(Val);
148  auto *Offsets = VMap.getOffsets(Val);
149  SmallVector<LLT, 4> SplitTys;
150  computeValueLLTs(*DL, *Val.getType(), SplitTys,
151  Offsets->empty() ? Offsets : nullptr);
152  for (unsigned i = 0; i < SplitTys.size(); ++i)
153  Regs->push_back(0);
154  return *Regs;
155 }
156 
157 ArrayRef<unsigned> IRTranslator::getOrCreateVRegs(const Value &Val) {
158  auto VRegsIt = VMap.findVRegs(Val);
159  if (VRegsIt != VMap.vregs_end())
160  return *VRegsIt->second;
161 
162  if (Val.getType()->isVoidTy())
163  return *VMap.getVRegs(Val);
164 
165  // Create entry for this type.
166  auto *VRegs = VMap.getVRegs(Val);
167  auto *Offsets = VMap.getOffsets(Val);
168 
169  assert(Val.getType()->isSized() &&
170  "Don't know how to create an empty vreg");
171 
172  SmallVector<LLT, 4> SplitTys;
173  computeValueLLTs(*DL, *Val.getType(), SplitTys,
174  Offsets->empty() ? Offsets : nullptr);
175 
176  if (!isa<Constant>(Val)) {
177  for (auto Ty : SplitTys)
178  VRegs->push_back(MRI->createGenericVirtualRegister(Ty));
179  return *VRegs;
180  }
181 
182  if (Val.getType()->isAggregateType()) {
183  // UndefValue, ConstantAggregateZero
184  auto &C = cast<Constant>(Val);
185  unsigned Idx = 0;
186  while (auto Elt = C.getAggregateElement(Idx++)) {
187  auto EltRegs = getOrCreateVRegs(*Elt);
188  std::copy(EltRegs.begin(), EltRegs.end(), std::back_inserter(*VRegs));
189  }
190  } else {
191  assert(SplitTys.size() == 1 && "unexpectedly split LLT");
192  VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0]));
193  bool Success = translate(cast<Constant>(Val), VRegs->front());
194  if (!Success) {
195  OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
196  MF->getFunction().getSubprogram(),
197  &MF->getFunction().getEntryBlock());
198  R << "unable to translate constant: " << ore::NV("Type", Val.getType());
199  reportTranslationError(*MF, *TPC, *ORE, R);
200  return *VRegs;
201  }
202  }
203 
204  return *VRegs;
205 }
206 
207 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) {
208  if (FrameIndices.find(&AI) != FrameIndices.end())
209  return FrameIndices[&AI];
210 
211  unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType());
212  unsigned Size =
213  ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue();
214 
215  // Always allocate at least one byte.
216  Size = std::max(Size, 1u);
217 
218  unsigned Alignment = AI.getAlignment();
219  if (!Alignment)
220  Alignment = DL->getABITypeAlignment(AI.getAllocatedType());
221 
222  int &FI = FrameIndices[&AI];
223  FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI);
224  return FI;
225 }
226 
227 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) {
228  unsigned Alignment = 0;
229  Type *ValTy = nullptr;
230  if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
231  Alignment = SI->getAlignment();
232  ValTy = SI->getValueOperand()->getType();
233  } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
234  Alignment = LI->getAlignment();
235  ValTy = LI->getType();
236  } else if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) {
237  // TODO(PR27168): This instruction has no alignment attribute, but unlike
238  // the default alignment for load/store, the default here is to assume
239  // it has NATURAL alignment, not DataLayout-specified alignment.
240  const DataLayout &DL = AI->getModule()->getDataLayout();
241  Alignment = DL.getTypeStoreSize(AI->getCompareOperand()->getType());
242  ValTy = AI->getCompareOperand()->getType();
243  } else if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) {
244  // TODO(PR27168): This instruction has no alignment attribute, but unlike
245  // the default alignment for load/store, the default here is to assume
246  // it has NATURAL alignment, not DataLayout-specified alignment.
247  const DataLayout &DL = AI->getModule()->getDataLayout();
248  Alignment = DL.getTypeStoreSize(AI->getValOperand()->getType());
249  ValTy = AI->getType();
250  } else {
251  OptimizationRemarkMissed R("gisel-irtranslator", "", &I);
252  R << "unable to translate memop: " << ore::NV("Opcode", &I);
253  reportTranslationError(*MF, *TPC, *ORE, R);
254  return 1;
255  }
256 
257  return Alignment ? Alignment : DL->getABITypeAlignment(ValTy);
258 }
259 
260 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) {
261  MachineBasicBlock *&MBB = BBToMBB[&BB];
262  assert(MBB && "BasicBlock was not encountered before");
263  return *MBB;
264 }
265 
266 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) {
267  assert(NewPred && "new predecessor must be a real MachineBasicBlock");
268  MachinePreds[Edge].push_back(NewPred);
269 }
270 
271 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U,
272  MachineIRBuilder &MIRBuilder) {
273  // FIXME: handle signed/unsigned wrapping flags.
274 
275  // Get or create a virtual register for each value.
276  // Unless the value is a Constant => loadimm cst?
277  // or inline constant each time?
278  // Creation of a virtual register needs to have a size.
279  unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
280  unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
281  unsigned Res = getOrCreateVReg(U);
282  MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1);
283  return true;
284 }
285 
286 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
287  // -0.0 - X --> G_FNEG
288  if (isa<Constant>(U.getOperand(0)) &&
290  MIRBuilder.buildInstr(TargetOpcode::G_FNEG)
291  .addDef(getOrCreateVReg(U))
292  .addUse(getOrCreateVReg(*U.getOperand(1)));
293  return true;
294  }
295  return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
296 }
297 
298 bool IRTranslator::translateCompare(const User &U,
299  MachineIRBuilder &MIRBuilder) {
300  const CmpInst *CI = dyn_cast<CmpInst>(&U);
301  unsigned Op0 = getOrCreateVReg(*U.getOperand(0));
302  unsigned Op1 = getOrCreateVReg(*U.getOperand(1));
303  unsigned Res = getOrCreateVReg(U);
304  CmpInst::Predicate Pred =
305  CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>(
306  cast<ConstantExpr>(U).getPredicate());
307  if (CmpInst::isIntPredicate(Pred))
308  MIRBuilder.buildICmp(Pred, Res, Op0, Op1);
309  else if (Pred == CmpInst::FCMP_FALSE)
310  MIRBuilder.buildCopy(
311  Res, getOrCreateVReg(*Constant::getNullValue(CI->getType())));
312  else if (Pred == CmpInst::FCMP_TRUE)
313  MIRBuilder.buildCopy(
314  Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType())));
315  else
316  MIRBuilder.buildFCmp(Pred, Res, Op0, Op1);
317 
318  return true;
319 }
320 
321 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) {
322  const ReturnInst &RI = cast<ReturnInst>(U);
323  const Value *Ret = RI.getReturnValue();
324  if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0)
325  Ret = nullptr;
326  // The target may mess up with the insertion point, but
327  // this is not important as a return is the last instruction
328  // of the block anyway.
329 
330  // FIXME: this interface should simplify when CallLowering gets adapted to
331  // multiple VRegs per Value.
332  unsigned VReg = Ret ? packRegs(*Ret, MIRBuilder) : 0;
333  return CLI->lowerReturn(MIRBuilder, Ret, VReg);
334 }
335 
336 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) {
337  const BranchInst &BrInst = cast<BranchInst>(U);
338  unsigned Succ = 0;
339  if (!BrInst.isUnconditional()) {
340  // We want a G_BRCOND to the true BB followed by an unconditional branch.
341  unsigned Tst = getOrCreateVReg(*BrInst.getCondition());
342  const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++));
343  MachineBasicBlock &TrueBB = getMBB(TrueTgt);
344  MIRBuilder.buildBrCond(Tst, TrueBB);
345  }
346 
347  const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ));
348  MachineBasicBlock &TgtBB = getMBB(BrTgt);
349  MachineBasicBlock &CurBB = MIRBuilder.getMBB();
350 
351  // If the unconditional target is the layout successor, fallthrough.
352  if (!CurBB.isLayoutSuccessor(&TgtBB))
353  MIRBuilder.buildBr(TgtBB);
354 
355  // Link successors.
356  for (const BasicBlock *Succ : BrInst.successors())
357  CurBB.addSuccessor(&getMBB(*Succ));
358  return true;
359 }
360 
361 bool IRTranslator::translateSwitch(const User &U,
362  MachineIRBuilder &MIRBuilder) {
363  // For now, just translate as a chain of conditional branches.
364  // FIXME: could we share most of the logic/code in
365  // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel?
366  // At first sight, it seems most of the logic in there is independent of
367  // SelectionDAG-specifics and a lot of work went in to optimize switch
368  // lowering in there.
369 
370  const SwitchInst &SwInst = cast<SwitchInst>(U);
371  const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition());
372  const BasicBlock *OrigBB = SwInst.getParent();
373 
374  LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL);
375  for (auto &CaseIt : SwInst.cases()) {
376  const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue());
377  const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1);
378  MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue);
379  MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
380  const BasicBlock *TrueBB = CaseIt.getCaseSuccessor();
381  MachineBasicBlock &TrueMBB = getMBB(*TrueBB);
382 
383  MIRBuilder.buildBrCond(Tst, TrueMBB);
384  CurMBB.addSuccessor(&TrueMBB);
385  addMachineCFGPred({OrigBB, TrueBB}, &CurMBB);
386 
387  MachineBasicBlock *FalseMBB =
388  MF->CreateMachineBasicBlock(SwInst.getParent());
389  // Insert the comparison blocks one after the other.
390  MF->insert(std::next(CurMBB.getIterator()), FalseMBB);
391  MIRBuilder.buildBr(*FalseMBB);
392  CurMBB.addSuccessor(FalseMBB);
393 
394  MIRBuilder.setMBB(*FalseMBB);
395  }
396  // handle default case
397  const BasicBlock *DefaultBB = SwInst.getDefaultDest();
398  MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB);
399  MIRBuilder.buildBr(DefaultMBB);
400  MachineBasicBlock &CurMBB = MIRBuilder.getMBB();
401  CurMBB.addSuccessor(&DefaultMBB);
402  addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB);
403 
404  return true;
405 }
406 
407 bool IRTranslator::translateIndirectBr(const User &U,
408  MachineIRBuilder &MIRBuilder) {
409  const IndirectBrInst &BrInst = cast<IndirectBrInst>(U);
410 
411  const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress());
412  MIRBuilder.buildBrIndirect(Tgt);
413 
414  // Link successors.
415  MachineBasicBlock &CurBB = MIRBuilder.getMBB();
416  for (const BasicBlock *Succ : BrInst.successors())
417  CurBB.addSuccessor(&getMBB(*Succ));
418 
419  return true;
420 }
421 
422 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) {
423  const LoadInst &LI = cast<LoadInst>(U);
424 
425  auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile
427  Flags |= MachineMemOperand::MOLoad;
428 
429  if (DL->getTypeStoreSize(LI.getType()) == 0)
430  return true;
431 
432  ArrayRef<unsigned> Regs = getOrCreateVRegs(LI);
433  ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI);
434  unsigned Base = getOrCreateVReg(*LI.getPointerOperand());
435 
436  for (unsigned i = 0; i < Regs.size(); ++i) {
437  unsigned Addr = 0;
438  MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
439 
440  MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8);
441  unsigned BaseAlign = getMemOpAlignment(LI);
442  auto MMO = MF->getMachineMemOperand(
443  Ptr, Flags, (MRI->getType(Regs[i]).getSizeInBits() + 7) / 8,
444  MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
445  LI.getSyncScopeID(), LI.getOrdering());
446  MIRBuilder.buildLoad(Regs[i], Addr, *MMO);
447  }
448 
449  return true;
450 }
451 
452 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) {
453  const StoreInst &SI = cast<StoreInst>(U);
454  auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile
457 
458  if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0)
459  return true;
460 
461  ArrayRef<unsigned> Vals = getOrCreateVRegs(*SI.getValueOperand());
462  ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand());
463  unsigned Base = getOrCreateVReg(*SI.getPointerOperand());
464 
465  for (unsigned i = 0; i < Vals.size(); ++i) {
466  unsigned Addr = 0;
467  MIRBuilder.materializeGEP(Addr, Base, LLT::scalar(64), Offsets[i] / 8);
468 
469  MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8);
470  unsigned BaseAlign = getMemOpAlignment(SI);
471  auto MMO = MF->getMachineMemOperand(
472  Ptr, Flags, (MRI->getType(Vals[i]).getSizeInBits() + 7) / 8,
473  MinAlign(BaseAlign, Offsets[i] / 8), AAMDNodes(), nullptr,
474  SI.getSyncScopeID(), SI.getOrdering());
475  MIRBuilder.buildStore(Vals[i], Addr, *MMO);
476  }
477  return true;
478 }
479 
480 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) {
481  const Value *Src = U.getOperand(0);
483 
484  // getIndexedOffsetInType is designed for GEPs, so the first index is the
485  // usual array element rather than looking into the actual aggregate.
486  SmallVector<Value *, 1> Indices;
487  Indices.push_back(ConstantInt::get(Int32Ty, 0));
488 
489  if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) {
490  for (auto Idx : EVI->indices())
491  Indices.push_back(ConstantInt::get(Int32Ty, Idx));
492  } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) {
493  for (auto Idx : IVI->indices())
494  Indices.push_back(ConstantInt::get(Int32Ty, Idx));
495  } else {
496  for (unsigned i = 1; i < U.getNumOperands(); ++i)
497  Indices.push_back(U.getOperand(i));
498  }
499 
500  return 8 * static_cast<uint64_t>(
501  DL.getIndexedOffsetInType(Src->getType(), Indices));
502 }
503 
504 bool IRTranslator::translateExtractValue(const User &U,
505  MachineIRBuilder &MIRBuilder) {
506  const Value *Src = U.getOperand(0);
507  uint64_t Offset = getOffsetFromIndices(U, *DL);
508  ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
509  ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src);
510  unsigned Idx = std::lower_bound(Offsets.begin(), Offsets.end(), Offset) -
511  Offsets.begin();
512  auto &DstRegs = allocateVRegs(U);
513 
514  for (unsigned i = 0; i < DstRegs.size(); ++i)
515  DstRegs[i] = SrcRegs[Idx++];
516 
517  return true;
518 }
519 
520 bool IRTranslator::translateInsertValue(const User &U,
521  MachineIRBuilder &MIRBuilder) {
522  const Value *Src = U.getOperand(0);
523  uint64_t Offset = getOffsetFromIndices(U, *DL);
524  auto &DstRegs = allocateVRegs(U);
525  ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U);
526  ArrayRef<unsigned> SrcRegs = getOrCreateVRegs(*Src);
527  ArrayRef<unsigned> InsertedRegs = getOrCreateVRegs(*U.getOperand(1));
528  auto InsertedIt = InsertedRegs.begin();
529 
530  for (unsigned i = 0; i < DstRegs.size(); ++i) {
531  if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end())
532  DstRegs[i] = *InsertedIt++;
533  else
534  DstRegs[i] = SrcRegs[i];
535  }
536 
537  return true;
538 }
539 
540 bool IRTranslator::translateSelect(const User &U,
541  MachineIRBuilder &MIRBuilder) {
542  unsigned Tst = getOrCreateVReg(*U.getOperand(0));
543  ArrayRef<unsigned> ResRegs = getOrCreateVRegs(U);
544  ArrayRef<unsigned> Op0Regs = getOrCreateVRegs(*U.getOperand(1));
545  ArrayRef<unsigned> Op1Regs = getOrCreateVRegs(*U.getOperand(2));
546 
547  for (unsigned i = 0; i < ResRegs.size(); ++i)
548  MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i]);
549 
550  return true;
551 }
552 
553 bool IRTranslator::translateBitCast(const User &U,
554  MachineIRBuilder &MIRBuilder) {
555  // If we're bitcasting to the source type, we can reuse the source vreg.
556  if (getLLTForType(*U.getOperand(0)->getType(), *DL) ==
557  getLLTForType(*U.getType(), *DL)) {
558  unsigned SrcReg = getOrCreateVReg(*U.getOperand(0));
559  auto &Regs = *VMap.getVRegs(U);
560  // If we already assigned a vreg for this bitcast, we can't change that.
561  // Emit a copy to satisfy the users we already emitted.
562  if (!Regs.empty())
563  MIRBuilder.buildCopy(Regs[0], SrcReg);
564  else {
565  Regs.push_back(SrcReg);
566  VMap.getOffsets(U)->push_back(0);
567  }
568  return true;
569  }
570  return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder);
571 }
572 
573 bool IRTranslator::translateCast(unsigned Opcode, const User &U,
574  MachineIRBuilder &MIRBuilder) {
575  unsigned Op = getOrCreateVReg(*U.getOperand(0));
576  unsigned Res = getOrCreateVReg(U);
577  MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op);
578  return true;
579 }
580 
581 bool IRTranslator::translateGetElementPtr(const User &U,
582  MachineIRBuilder &MIRBuilder) {
583  // FIXME: support vector GEPs.
584  if (U.getType()->isVectorTy())
585  return false;
586 
587  Value &Op0 = *U.getOperand(0);
588  unsigned BaseReg = getOrCreateVReg(Op0);
589  Type *PtrIRTy = Op0.getType();
590  LLT PtrTy = getLLTForType(*PtrIRTy, *DL);
591  Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy);
592  LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL);
593 
594  int64_t Offset = 0;
595  for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U);
596  GTI != E; ++GTI) {
597  const Value *Idx = GTI.getOperand();
598  if (StructType *StTy = GTI.getStructTypeOrNull()) {
599  unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
600  Offset += DL->getStructLayout(StTy)->getElementOffset(Field);
601  continue;
602  } else {
603  uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
604 
605  // If this is a scalar constant or a splat vector of constants,
606  // handle it quickly.
607  if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
608  Offset += ElementSize * CI->getSExtValue();
609  continue;
610  }
611 
612  if (Offset != 0) {
613  unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
614  unsigned OffsetReg =
615  getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
616  MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg);
617 
618  BaseReg = NewBaseReg;
619  Offset = 0;
620  }
621 
622  unsigned IdxReg = getOrCreateVReg(*Idx);
623  if (MRI->getType(IdxReg) != OffsetTy) {
624  unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy);
625  MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg);
626  IdxReg = NewIdxReg;
627  }
628 
629  // N = N + Idx * ElementSize;
630  // Avoid doing it for ElementSize of 1.
631  unsigned GepOffsetReg;
632  if (ElementSize != 1) {
633  unsigned ElementSizeReg =
634  getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize));
635 
636  GepOffsetReg = MRI->createGenericVirtualRegister(OffsetTy);
637  MIRBuilder.buildMul(GepOffsetReg, ElementSizeReg, IdxReg);
638  } else
639  GepOffsetReg = IdxReg;
640 
641  unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy);
642  MIRBuilder.buildGEP(NewBaseReg, BaseReg, GepOffsetReg);
643  BaseReg = NewBaseReg;
644  }
645  }
646 
647  if (Offset != 0) {
648  unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset));
649  MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg);
650  return true;
651  }
652 
653  MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg);
654  return true;
655 }
656 
657 bool IRTranslator::translateMemfunc(const CallInst &CI,
658  MachineIRBuilder &MIRBuilder,
659  unsigned ID) {
660  LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL);
661  Type *DstTy = CI.getArgOperand(0)->getType();
662  if (cast<PointerType>(DstTy)->getAddressSpace() != 0 ||
663  SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0))
664  return false;
665 
667  for (int i = 0; i < 3; ++i) {
668  const auto &Arg = CI.getArgOperand(i);
669  Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType());
670  }
671 
672  const char *Callee;
673  switch (ID) {
674  case Intrinsic::memmove:
675  case Intrinsic::memcpy: {
676  Type *SrcTy = CI.getArgOperand(1)->getType();
677  if(cast<PointerType>(SrcTy)->getAddressSpace() != 0)
678  return false;
679  Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove";
680  break;
681  }
682  case Intrinsic::memset:
683  Callee = "memset";
684  break;
685  default:
686  return false;
687  }
688 
689  return CLI->lowerCall(MIRBuilder, CI.getCallingConv(),
690  MachineOperand::CreateES(Callee),
691  CallLowering::ArgInfo(0, CI.getType()), Args);
692 }
693 
694 void IRTranslator::getStackGuard(unsigned DstReg,
695  MachineIRBuilder &MIRBuilder) {
697  MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF));
698  auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD);
699  MIB.addDef(DstReg);
700 
701  auto &TLI = *MF->getSubtarget().getTargetLowering();
702  Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent());
703  if (!Global)
704  return;
705 
706  MachinePointerInfo MPInfo(Global);
710  *MemRefs =
711  MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8,
712  DL->getPointerABIAlignment(0));
713  MIB.setMemRefs(MemRefs, MemRefs + 1);
714 }
715 
716 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
717  MachineIRBuilder &MIRBuilder) {
718  ArrayRef<unsigned> ResRegs = getOrCreateVRegs(CI);
719  auto MIB = MIRBuilder.buildInstr(Op)
720  .addDef(ResRegs[0])
721  .addDef(ResRegs[1])
722  .addUse(getOrCreateVReg(*CI.getOperand(0)))
723  .addUse(getOrCreateVReg(*CI.getOperand(1)));
724 
725  if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) {
726  unsigned Zero = getOrCreateVReg(
728  MIB.addUse(Zero);
729  }
730 
731  return true;
732 }
733 
734 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
735  MachineIRBuilder &MIRBuilder) {
736  switch (ID) {
737  default:
738  break;
739  case Intrinsic::lifetime_start:
740  case Intrinsic::lifetime_end:
741  // Stack coloring is not enabled in O0 (which we care about now) so we can
742  // drop these. Make sure someone notices when we start compiling at higher
743  // opts though.
744  if (MF->getTarget().getOptLevel() != CodeGenOpt::None)
745  return false;
746  return true;
747  case Intrinsic::dbg_declare: {
748  const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI);
749  assert(DI.getVariable() && "Missing variable");
750 
751  const Value *Address = DI.getAddress();
752  if (!Address || isa<UndefValue>(Address)) {
753  LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
754  return true;
755  }
756 
758  MIRBuilder.getDebugLoc()) &&
759  "Expected inlined-at fields to agree");
760  auto AI = dyn_cast<AllocaInst>(Address);
761  if (AI && AI->isStaticAlloca()) {
762  // Static allocas are tracked at the MF level, no need for DBG_VALUE
763  // instructions (in fact, they get ignored if they *do* exist).
765  getOrCreateFrameIndex(*AI), DI.getDebugLoc());
766  } else
767  MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address),
768  DI.getVariable(), DI.getExpression());
769  return true;
770  }
771  case Intrinsic::vaend:
772  // No target I know of cares about va_end. Certainly no in-tree target
773  // does. Simplest intrinsic ever!
774  return true;
775  case Intrinsic::vastart: {
776  auto &TLI = *MF->getSubtarget().getTargetLowering();
777  Value *Ptr = CI.getArgOperand(0);
778  unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8;
779 
780  MIRBuilder.buildInstr(TargetOpcode::G_VASTART)
781  .addUse(getOrCreateVReg(*Ptr))
783  MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0));
784  return true;
785  }
786  case Intrinsic::dbg_value: {
787  // This form of DBG_VALUE is target-independent.
788  const DbgValueInst &DI = cast<DbgValueInst>(CI);
789  const Value *V = DI.getValue();
791  MIRBuilder.getDebugLoc()) &&
792  "Expected inlined-at fields to agree");
793  if (!V) {
794  // Currently the optimizer can produce this; insert an undef to
795  // help debugging. Probably the optimizer should not do this.
796  MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression());
797  } else if (const auto *CI = dyn_cast<Constant>(V)) {
798  MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression());
799  } else {
800  unsigned Reg = getOrCreateVReg(*V);
801  // FIXME: This does not handle register-indirect values at offset 0. The
802  // direct/indirect thing shouldn't really be handled by something as
803  // implicit as reg+noreg vs reg+imm in the first palce, but it seems
804  // pretty baked in right now.
805  MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression());
806  }
807  return true;
808  }
809  case Intrinsic::uadd_with_overflow:
810  return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder);
811  case Intrinsic::sadd_with_overflow:
812  return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder);
813  case Intrinsic::usub_with_overflow:
814  return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder);
815  case Intrinsic::ssub_with_overflow:
816  return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder);
817  case Intrinsic::umul_with_overflow:
818  return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder);
819  case Intrinsic::smul_with_overflow:
820  return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder);
821  case Intrinsic::pow:
822  MIRBuilder.buildInstr(TargetOpcode::G_FPOW)
823  .addDef(getOrCreateVReg(CI))
824  .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
825  .addUse(getOrCreateVReg(*CI.getArgOperand(1)));
826  return true;
827  case Intrinsic::exp:
828  MIRBuilder.buildInstr(TargetOpcode::G_FEXP)
829  .addDef(getOrCreateVReg(CI))
830  .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
831  return true;
832  case Intrinsic::exp2:
833  MIRBuilder.buildInstr(TargetOpcode::G_FEXP2)
834  .addDef(getOrCreateVReg(CI))
835  .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
836  return true;
837  case Intrinsic::log:
838  MIRBuilder.buildInstr(TargetOpcode::G_FLOG)
839  .addDef(getOrCreateVReg(CI))
840  .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
841  return true;
842  case Intrinsic::log2:
843  MIRBuilder.buildInstr(TargetOpcode::G_FLOG2)
844  .addDef(getOrCreateVReg(CI))
845  .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
846  return true;
847  case Intrinsic::fabs:
848  MIRBuilder.buildInstr(TargetOpcode::G_FABS)
849  .addDef(getOrCreateVReg(CI))
850  .addUse(getOrCreateVReg(*CI.getArgOperand(0)));
851  return true;
852  case Intrinsic::fma:
853  MIRBuilder.buildInstr(TargetOpcode::G_FMA)
854  .addDef(getOrCreateVReg(CI))
855  .addUse(getOrCreateVReg(*CI.getArgOperand(0)))
856  .addUse(getOrCreateVReg(*CI.getArgOperand(1)))
857  .addUse(getOrCreateVReg(*CI.getArgOperand(2)));
858  return true;
859  case Intrinsic::fmuladd: {
860  const TargetMachine &TM = MF->getTarget();
861  const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
862  unsigned Dst = getOrCreateVReg(CI);
863  unsigned Op0 = getOrCreateVReg(*CI.getArgOperand(0));
864  unsigned Op1 = getOrCreateVReg(*CI.getArgOperand(1));
865  unsigned Op2 = getOrCreateVReg(*CI.getArgOperand(2));
867  TLI.isFMAFasterThanFMulAndFAdd(TLI.getValueType(*DL, CI.getType()))) {
868  // TODO: Revisit this to see if we should move this part of the
869  // lowering to the combiner.
870  MIRBuilder.buildInstr(TargetOpcode::G_FMA, Dst, Op0, Op1, Op2);
871  } else {
872  LLT Ty = getLLTForType(*CI.getType(), *DL);
873  auto FMul = MIRBuilder.buildInstr(TargetOpcode::G_FMUL, Ty, Op0, Op1);
874  MIRBuilder.buildInstr(TargetOpcode::G_FADD, Dst, FMul, Op2);
875  }
876  return true;
877  }
878  case Intrinsic::memcpy:
879  case Intrinsic::memmove:
880  case Intrinsic::memset:
881  return translateMemfunc(CI, MIRBuilder, ID);
882  case Intrinsic::eh_typeid_for: {
884  unsigned Reg = getOrCreateVReg(CI);
885  unsigned TypeID = MF->getTypeIDFor(GV);
886  MIRBuilder.buildConstant(Reg, TypeID);
887  return true;
888  }
889  case Intrinsic::objectsize: {
890  // If we don't know by now, we're never going to know.
891  const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1));
892 
893  MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0);
894  return true;
895  }
896  case Intrinsic::stackguard:
897  getStackGuard(getOrCreateVReg(CI), MIRBuilder);
898  return true;
899  case Intrinsic::stackprotector: {
900  LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL);
901  unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy);
902  getStackGuard(GuardVal, MIRBuilder);
903 
904  AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1));
905  MIRBuilder.buildStore(
906  GuardVal, getOrCreateVReg(*Slot),
909  getOrCreateFrameIndex(*Slot)),
911  PtrTy.getSizeInBits() / 8, 8));
912  return true;
913  }
914  }
915  return false;
916 }
917 
918 bool IRTranslator::translateInlineAsm(const CallInst &CI,
919  MachineIRBuilder &MIRBuilder) {
920  const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue());
921  if (!IA.getConstraintString().empty())
922  return false;
923 
924  unsigned ExtraInfo = 0;
925  if (IA.hasSideEffects())
926  ExtraInfo |= InlineAsm::Extra_HasSideEffects;
927  if (IA.getDialect() == InlineAsm::AD_Intel)
928  ExtraInfo |= InlineAsm::Extra_AsmDialect;
929 
931  .addExternalSymbol(IA.getAsmString().c_str())
932  .addImm(ExtraInfo);
933 
934  return true;
935 }
936 
937 unsigned IRTranslator::packRegs(const Value &V,
938  MachineIRBuilder &MIRBuilder) {
939  ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
940  ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
941  LLT BigTy = getLLTForType(*V.getType(), *DL);
942 
943  if (Regs.size() == 1)
944  return Regs[0];
945 
946  unsigned Dst = MRI->createGenericVirtualRegister(BigTy);
947  MIRBuilder.buildUndef(Dst);
948  for (unsigned i = 0; i < Regs.size(); ++i) {
949  unsigned NewDst = MRI->createGenericVirtualRegister(BigTy);
950  MIRBuilder.buildInsert(NewDst, Dst, Regs[i], Offsets[i]);
951  Dst = NewDst;
952  }
953  return Dst;
954 }
955 
956 void IRTranslator::unpackRegs(const Value &V, unsigned Src,
957  MachineIRBuilder &MIRBuilder) {
958  ArrayRef<unsigned> Regs = getOrCreateVRegs(V);
959  ArrayRef<uint64_t> Offsets = *VMap.getOffsets(V);
960 
961  for (unsigned i = 0; i < Regs.size(); ++i)
962  MIRBuilder.buildExtract(Regs[i], Src, Offsets[i]);
963 }
964 
965 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) {
966  const CallInst &CI = cast<CallInst>(U);
967  auto TII = MF->getTarget().getIntrinsicInfo();
968  const Function *F = CI.getCalledFunction();
969 
970  // FIXME: support Windows dllimport function calls.
971  if (F && F->hasDLLImportStorageClass())
972  return false;
973 
974  if (CI.isInlineAsm())
975  return translateInlineAsm(CI, MIRBuilder);
976 
978  if (F && F->isIntrinsic()) {
979  ID = F->getIntrinsicID();
980  if (TII && ID == Intrinsic::not_intrinsic)
981  ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F));
982  }
983 
984  bool IsSplitType = valueIsSplit(CI);
985  if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) {
986  unsigned Res = IsSplitType ? MRI->createGenericVirtualRegister(
987  getLLTForType(*CI.getType(), *DL))
988  : getOrCreateVReg(CI);
989 
991  for (auto &Arg: CI.arg_operands())
992  Args.push_back(packRegs(*Arg, MIRBuilder));
993 
994  MF->getFrameInfo().setHasCalls(true);
995  bool Success = CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() {
996  return getOrCreateVReg(*CI.getCalledValue());
997  });
998 
999  if (IsSplitType)
1000  unpackRegs(CI, Res, MIRBuilder);
1001  return Success;
1002  }
1003 
1004  assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic");
1005 
1006  if (translateKnownIntrinsic(CI, ID, MIRBuilder))
1007  return true;
1008 
1009  unsigned Res = 0;
1010  if (!CI.getType()->isVoidTy()) {
1011  if (IsSplitType)
1012  Res =
1014  else
1015  Res = getOrCreateVReg(CI);
1016  }
1017  MachineInstrBuilder MIB =
1018  MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory());
1019 
1020  for (auto &Arg : CI.arg_operands()) {
1021  // Some intrinsics take metadata parameters. Reject them.
1022  if (isa<MetadataAsValue>(Arg))
1023  return false;
1024  MIB.addUse(packRegs(*Arg, MIRBuilder));
1025  }
1026 
1027  if (IsSplitType)
1028  unpackRegs(CI, Res, MIRBuilder);
1029 
1030  // Add a MachineMemOperand if it is a target mem intrinsic.
1031  const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering();
1032  TargetLowering::IntrinsicInfo Info;
1033  // TODO: Add a GlobalISel version of getTgtMemIntrinsic.
1034  if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) {
1035  uint64_t Size = Info.memVT.getStoreSize();
1037  Info.flags, Size, Info.align));
1038  }
1039 
1040  return true;
1041 }
1042 
1043 bool IRTranslator::translateInvoke(const User &U,
1044  MachineIRBuilder &MIRBuilder) {
1045  const InvokeInst &I = cast<InvokeInst>(U);
1046  MCContext &Context = MF->getContext();
1047 
1048  const BasicBlock *ReturnBB = I.getSuccessor(0);
1049  const BasicBlock *EHPadBB = I.getSuccessor(1);
1050 
1051  const Value *Callee = I.getCalledValue();
1052  const Function *Fn = dyn_cast<Function>(Callee);
1053  if (isa<InlineAsm>(Callee))
1054  return false;
1055 
1056  // FIXME: support invoking patchpoint and statepoint intrinsics.
1057  if (Fn && Fn->isIntrinsic())
1058  return false;
1059 
1060  // FIXME: support whatever these are.
1062  return false;
1063 
1064  // FIXME: support Windows exception handling.
1065  if (!isa<LandingPadInst>(EHPadBB->front()))
1066  return false;
1067 
1068  // Emit the actual call, bracketed by EH_LABELs so that the MF knows about
1069  // the region covered by the try.
1070  MCSymbol *BeginSymbol = Context.createTempSymbol();
1071  MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol);
1072 
1073  unsigned Res =
1076  for (auto &Arg: I.arg_operands())
1077  Args.push_back(packRegs(*Arg, MIRBuilder));
1078 
1079  if (!CLI->lowerCall(MIRBuilder, &I, Res, Args,
1080  [&]() { return getOrCreateVReg(*I.getCalledValue()); }))
1081  return false;
1082 
1083  unpackRegs(I, Res, MIRBuilder);
1084 
1085  MCSymbol *EndSymbol = Context.createTempSymbol();
1086  MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol);
1087 
1088  // FIXME: track probabilities.
1089  MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB),
1090  &ReturnMBB = getMBB(*ReturnBB);
1091  MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol);
1092  MIRBuilder.getMBB().addSuccessor(&ReturnMBB);
1093  MIRBuilder.getMBB().addSuccessor(&EHPadMBB);
1094  MIRBuilder.buildBr(ReturnMBB);
1095 
1096  return true;
1097 }
1098 
1099 bool IRTranslator::translateLandingPad(const User &U,
1100  MachineIRBuilder &MIRBuilder) {
1101  const LandingPadInst &LP = cast<LandingPadInst>(U);
1102 
1103  MachineBasicBlock &MBB = MIRBuilder.getMBB();
1104  addLandingPadInfo(LP, MBB);
1105 
1106  MBB.setIsEHPad();
1107 
1108  // If there aren't registers to copy the values into (e.g., during SjLj
1109  // exceptions), then don't bother.
1110  auto &TLI = *MF->getSubtarget().getTargetLowering();
1111  const Constant *PersonalityFn = MF->getFunction().getPersonalityFn();
1112  if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
1113  TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
1114  return true;
1115 
1116  // If landingpad's return type is token type, we don't create DAG nodes
1117  // for its exception pointer and selector value. The extraction of exception
1118  // pointer or selector value from token type landingpads is not currently
1119  // supported.
1120  if (LP.getType()->isTokenTy())
1121  return true;
1122 
1123  // Add a label to mark the beginning of the landing pad. Deletion of the
1124  // landing pad can thus be detected via the MachineModuleInfo.
1126  .addSym(MF->addLandingPad(&MBB));
1127 
1128  LLT Ty = getLLTForType(*LP.getType(), *DL);
1129  unsigned Undef = MRI->createGenericVirtualRegister(Ty);
1130  MIRBuilder.buildUndef(Undef);
1131 
1132  SmallVector<LLT, 2> Tys;
1133  for (Type *Ty : cast<StructType>(LP.getType())->elements())
1134  Tys.push_back(getLLTForType(*Ty, *DL));
1135  assert(Tys.size() == 2 && "Only two-valued landingpads are supported");
1136 
1137  // Mark exception register as live in.
1138  unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn);
1139  if (!ExceptionReg)
1140  return false;
1141 
1142  MBB.addLiveIn(ExceptionReg);
1143  ArrayRef<unsigned> ResRegs = getOrCreateVRegs(LP);
1144  MIRBuilder.buildCopy(ResRegs[0], ExceptionReg);
1145 
1146  unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn);
1147  if (!SelectorReg)
1148  return false;
1149 
1150  MBB.addLiveIn(SelectorReg);
1151  unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]);
1152  MIRBuilder.buildCopy(PtrVReg, SelectorReg);
1153  MIRBuilder.buildCast(ResRegs[1], PtrVReg);
1154 
1155  return true;
1156 }
1157 
1158 bool IRTranslator::translateAlloca(const User &U,
1159  MachineIRBuilder &MIRBuilder) {
1160  auto &AI = cast<AllocaInst>(U);
1161 
1162  if (AI.isSwiftError())
1163  return false;
1164 
1165  if (AI.isStaticAlloca()) {
1166  unsigned Res = getOrCreateVReg(AI);
1167  int FI = getOrCreateFrameIndex(AI);
1168  MIRBuilder.buildFrameIndex(Res, FI);
1169  return true;
1170  }
1171 
1172  // FIXME: support stack probing for Windows.
1173  if (MF->getTarget().getTargetTriple().isOSWindows())
1174  return false;
1175 
1176  // Now we're in the harder dynamic case.
1177  Type *Ty = AI.getAllocatedType();
1178  unsigned Align =
1179  std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment());
1180 
1181  unsigned NumElts = getOrCreateVReg(*AI.getArraySize());
1182 
1183  Type *IntPtrIRTy = DL->getIntPtrType(AI.getType());
1184  LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL);
1185  if (MRI->getType(NumElts) != IntPtrTy) {
1186  unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy);
1187  MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts);
1188  NumElts = ExtElts;
1189  }
1190 
1191  unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy);
1192  unsigned TySize =
1193  getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty)));
1194  MIRBuilder.buildMul(AllocSize, NumElts, TySize);
1195 
1196  LLT PtrTy = getLLTForType(*AI.getType(), *DL);
1197  auto &TLI = *MF->getSubtarget().getTargetLowering();
1198  unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1199 
1200  unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy);
1201  MIRBuilder.buildCopy(SPTmp, SPReg);
1202 
1203  unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy);
1204  MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize);
1205 
1206  // Handle alignment. We have to realign if the allocation granule was smaller
1207  // than stack alignment, or the specific alloca requires more than stack
1208  // alignment.
1209  unsigned StackAlign =
1211  Align = std::max(Align, StackAlign);
1212  if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) {
1213  // Round the size of the allocation up to the stack alignment size
1214  // by add SA-1 to the size. This doesn't overflow because we're computing
1215  // an address inside an alloca.
1216  unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy);
1217  MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align));
1218  AllocTmp = AlignedAlloc;
1219  }
1220 
1221  MIRBuilder.buildCopy(SPReg, AllocTmp);
1222  MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp);
1223 
1224  MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI);
1226  return true;
1227 }
1228 
1229 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) {
1230  // FIXME: We may need more info about the type. Because of how LLT works,
1231  // we're completely discarding the i64/double distinction here (amongst
1232  // others). Fortunately the ABIs I know of where that matters don't use va_arg
1233  // anyway but that's not guaranteed.
1234  MIRBuilder.buildInstr(TargetOpcode::G_VAARG)
1235  .addDef(getOrCreateVReg(U))
1236  .addUse(getOrCreateVReg(*U.getOperand(0)))
1237  .addImm(DL->getABITypeAlignment(U.getType()));
1238  return true;
1239 }
1240 
1241 bool IRTranslator::translateInsertElement(const User &U,
1242  MachineIRBuilder &MIRBuilder) {
1243  // If it is a <1 x Ty> vector, use the scalar as it is
1244  // not a legal vector type in LLT.
1245  if (U.getType()->getVectorNumElements() == 1) {
1246  unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1247  auto &Regs = *VMap.getVRegs(U);
1248  if (Regs.empty()) {
1249  Regs.push_back(Elt);
1250  VMap.getOffsets(U)->push_back(0);
1251  } else {
1252  MIRBuilder.buildCopy(Regs[0], Elt);
1253  }
1254  return true;
1255  }
1256 
1257  unsigned Res = getOrCreateVReg(U);
1258  unsigned Val = getOrCreateVReg(*U.getOperand(0));
1259  unsigned Elt = getOrCreateVReg(*U.getOperand(1));
1260  unsigned Idx = getOrCreateVReg(*U.getOperand(2));
1261  MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx);
1262  return true;
1263 }
1264 
1265 bool IRTranslator::translateExtractElement(const User &U,
1266  MachineIRBuilder &MIRBuilder) {
1267  // If it is a <1 x Ty> vector, use the scalar as it is
1268  // not a legal vector type in LLT.
1269  if (U.getOperand(0)->getType()->getVectorNumElements() == 1) {
1270  unsigned Elt = getOrCreateVReg(*U.getOperand(0));
1271  auto &Regs = *VMap.getVRegs(U);
1272  if (Regs.empty()) {
1273  Regs.push_back(Elt);
1274  VMap.getOffsets(U)->push_back(0);
1275  } else {
1276  MIRBuilder.buildCopy(Regs[0], Elt);
1277  }
1278  return true;
1279  }
1280  unsigned Res = getOrCreateVReg(U);
1281  unsigned Val = getOrCreateVReg(*U.getOperand(0));
1282  unsigned Idx = getOrCreateVReg(*U.getOperand(1));
1283  MIRBuilder.buildExtractVectorElement(Res, Val, Idx);
1284  return true;
1285 }
1286 
1287 bool IRTranslator::translateShuffleVector(const User &U,
1288  MachineIRBuilder &MIRBuilder) {
1289  MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR)
1290  .addDef(getOrCreateVReg(U))
1291  .addUse(getOrCreateVReg(*U.getOperand(0)))
1292  .addUse(getOrCreateVReg(*U.getOperand(1)))
1293  .addUse(getOrCreateVReg(*U.getOperand(2)));
1294  return true;
1295 }
1296 
1297 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) {
1298  const PHINode &PI = cast<PHINode>(U);
1299 
1301  for (auto Reg : getOrCreateVRegs(PI)) {
1302  auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, Reg);
1303  Insts.push_back(MIB.getInstr());
1304  }
1305 
1306  PendingPHIs.emplace_back(&PI, std::move(Insts));
1307  return true;
1308 }
1309 
1310 bool IRTranslator::translateAtomicCmpXchg(const User &U,
1311  MachineIRBuilder &MIRBuilder) {
1312  const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U);
1313 
1314  if (I.isWeak())
1315  return false;
1316 
1317  auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1320 
1321  Type *ResType = I.getType();
1322  Type *ValType = ResType->Type::getStructElementType(0);
1323 
1324  auto Res = getOrCreateVRegs(I);
1325  unsigned OldValRes = Res[0];
1326  unsigned SuccessRes = Res[1];
1327  unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1328  unsigned Cmp = getOrCreateVReg(*I.getCompareOperand());
1329  unsigned NewVal = getOrCreateVReg(*I.getNewValOperand());
1330 
1331  MIRBuilder.buildAtomicCmpXchgWithSuccess(
1332  OldValRes, SuccessRes, Addr, Cmp, NewVal,
1334  Flags, DL->getTypeStoreSize(ValType),
1335  getMemOpAlignment(I), AAMDNodes(), nullptr,
1337  I.getFailureOrdering()));
1338  return true;
1339 }
1340 
1341 bool IRTranslator::translateAtomicRMW(const User &U,
1342  MachineIRBuilder &MIRBuilder) {
1343  const AtomicRMWInst &I = cast<AtomicRMWInst>(U);
1344 
1345  auto Flags = I.isVolatile() ? MachineMemOperand::MOVolatile
1348 
1349  Type *ResType = I.getType();
1350 
1351  unsigned Res = getOrCreateVReg(I);
1352  unsigned Addr = getOrCreateVReg(*I.getPointerOperand());
1353  unsigned Val = getOrCreateVReg(*I.getValOperand());
1354 
1355  unsigned Opcode = 0;
1356  switch (I.getOperation()) {
1357  default:
1358  llvm_unreachable("Unknown atomicrmw op");
1359  return false;
1360  case AtomicRMWInst::Xchg:
1361  Opcode = TargetOpcode::G_ATOMICRMW_XCHG;
1362  break;
1363  case AtomicRMWInst::Add:
1364  Opcode = TargetOpcode::G_ATOMICRMW_ADD;
1365  break;
1366  case AtomicRMWInst::Sub:
1367  Opcode = TargetOpcode::G_ATOMICRMW_SUB;
1368  break;
1369  case AtomicRMWInst::And:
1370  Opcode = TargetOpcode::G_ATOMICRMW_AND;
1371  break;
1372  case AtomicRMWInst::Nand:
1373  Opcode = TargetOpcode::G_ATOMICRMW_NAND;
1374  break;
1375  case AtomicRMWInst::Or:
1376  Opcode = TargetOpcode::G_ATOMICRMW_OR;
1377  break;
1378  case AtomicRMWInst::Xor:
1379  Opcode = TargetOpcode::G_ATOMICRMW_XOR;
1380  break;
1381  case AtomicRMWInst::Max:
1382  Opcode = TargetOpcode::G_ATOMICRMW_MAX;
1383  break;
1384  case AtomicRMWInst::Min:
1385  Opcode = TargetOpcode::G_ATOMICRMW_MIN;
1386  break;
1387  case AtomicRMWInst::UMax:
1388  Opcode = TargetOpcode::G_ATOMICRMW_UMAX;
1389  break;
1390  case AtomicRMWInst::UMin:
1391  Opcode = TargetOpcode::G_ATOMICRMW_UMIN;
1392  break;
1393  }
1394 
1395  MIRBuilder.buildAtomicRMW(
1396  Opcode, Res, Addr, Val,
1398  Flags, DL->getTypeStoreSize(ResType),
1399  getMemOpAlignment(I), AAMDNodes(), nullptr,
1400  I.getSyncScopeID(), I.getOrdering()));
1401  return true;
1402 }
1403 
1404 void IRTranslator::finishPendingPhis() {
1405  for (auto &Phi : PendingPHIs) {
1406  const PHINode *PI = Phi.first;
1407  ArrayRef<MachineInstr *> ComponentPHIs = Phi.second;
1408 
1409  // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator
1410  // won't create extra control flow here, otherwise we need to find the
1411  // dominating predecessor here (or perhaps force the weirder IRTranslators
1412  // to provide a simple boundary).
1413  SmallSet<const BasicBlock *, 4> HandledPreds;
1414 
1415  for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) {
1416  auto IRPred = PI->getIncomingBlock(i);
1417  if (HandledPreds.count(IRPred))
1418  continue;
1419 
1420  HandledPreds.insert(IRPred);
1421  ArrayRef<unsigned> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i));
1422  for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) {
1423  assert(Pred->isSuccessor(ComponentPHIs[0]->getParent()) &&
1424  "incorrect CFG at MachineBasicBlock level");
1425  for (unsigned j = 0; j < ValRegs.size(); ++j) {
1426  MachineInstrBuilder MIB(*MF, ComponentPHIs[j]);
1427  MIB.addUse(ValRegs[j]);
1428  MIB.addMBB(Pred);
1429  }
1430  }
1431  }
1432  }
1433 }
1434 
1435 bool IRTranslator::valueIsSplit(const Value &V,
1437  SmallVector<LLT, 4> SplitTys;
1438  if (Offsets && !Offsets->empty())
1439  Offsets->clear();
1440  computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets);
1441  return SplitTys.size() > 1;
1442 }
1443 
1444 bool IRTranslator::translate(const Instruction &Inst) {
1445  CurBuilder.setDebugLoc(Inst.getDebugLoc());
1446  switch(Inst.getOpcode()) {
1447 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1448  case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder);
1449 #include "llvm/IR/Instruction.def"
1450  default:
1451  return false;
1452  }
1453 }
1454 
1455 bool IRTranslator::translate(const Constant &C, unsigned Reg) {
1456  if (auto CI = dyn_cast<ConstantInt>(&C))
1457  EntryBuilder.buildConstant(Reg, *CI);
1458  else if (auto CF = dyn_cast<ConstantFP>(&C))
1459  EntryBuilder.buildFConstant(Reg, *CF);
1460  else if (isa<UndefValue>(C))
1461  EntryBuilder.buildUndef(Reg);
1462  else if (isa<ConstantPointerNull>(C)) {
1463  // As we are trying to build a constant val of 0 into a pointer,
1464  // insert a cast to make them correct with respect to types.
1465  unsigned NullSize = DL->getTypeSizeInBits(C.getType());
1466  auto *ZeroTy = Type::getIntNTy(C.getContext(), NullSize);
1467  auto *ZeroVal = ConstantInt::get(ZeroTy, 0);
1468  unsigned ZeroReg = getOrCreateVReg(*ZeroVal);
1469  EntryBuilder.buildCast(Reg, ZeroReg);
1470  } else if (auto GV = dyn_cast<GlobalValue>(&C))
1471  EntryBuilder.buildGlobalValue(Reg, GV);
1472  else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) {
1473  if (!CAZ->getType()->isVectorTy())
1474  return false;
1475  // Return the scalar if it is a <1 x Ty> vector.
1476  if (CAZ->getNumElements() == 1)
1477  return translate(*CAZ->getElementValue(0u), Reg);
1478  std::vector<unsigned> Ops;
1479  for (unsigned i = 0; i < CAZ->getNumElements(); ++i) {
1480  Constant &Elt = *CAZ->getElementValue(i);
1481  Ops.push_back(getOrCreateVReg(Elt));
1482  }
1483  EntryBuilder.buildMerge(Reg, Ops);
1484  } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) {
1485  // Return the scalar if it is a <1 x Ty> vector.
1486  if (CV->getNumElements() == 1)
1487  return translate(*CV->getElementAsConstant(0), Reg);
1488  std::vector<unsigned> Ops;
1489  for (unsigned i = 0; i < CV->getNumElements(); ++i) {
1490  Constant &Elt = *CV->getElementAsConstant(i);
1491  Ops.push_back(getOrCreateVReg(Elt));
1492  }
1493  EntryBuilder.buildMerge(Reg, Ops);
1494  } else if (auto CE = dyn_cast<ConstantExpr>(&C)) {
1495  switch(CE->getOpcode()) {
1496 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1497  case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder);
1498 #include "llvm/IR/Instruction.def"
1499  default:
1500  return false;
1501  }
1502  } else if (auto CV = dyn_cast<ConstantVector>(&C)) {
1503  if (CV->getNumOperands() == 1)
1504  return translate(*CV->getOperand(0), Reg);
1506  for (unsigned i = 0; i < CV->getNumOperands(); ++i) {
1507  Ops.push_back(getOrCreateVReg(*CV->getOperand(i)));
1508  }
1509  EntryBuilder.buildMerge(Reg, Ops);
1510  } else if (auto *BA = dyn_cast<BlockAddress>(&C)) {
1511  EntryBuilder.buildBlockAddress(Reg, BA);
1512  } else
1513  return false;
1514 
1515  return true;
1516 }
1517 
1518 void IRTranslator::finalizeFunction() {
1519  // Release the memory used by the different maps we
1520  // needed during the translation.
1521  PendingPHIs.clear();
1522  VMap.reset();
1523  FrameIndices.clear();
1524  MachinePreds.clear();
1525  // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it
1526  // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid
1527  // destroying it twice (in ~IRTranslator() and ~LLVMContext())
1528  EntryBuilder = MachineIRBuilder();
1529  CurBuilder = MachineIRBuilder();
1530 }
1531 
1533  MF = &CurMF;
1534  const Function &F = MF->getFunction();
1535  if (F.empty())
1536  return false;
1537  CLI = MF->getSubtarget().getCallLowering();
1538  CurBuilder.setMF(*MF);
1539  EntryBuilder.setMF(*MF);
1540  MRI = &MF->getRegInfo();
1541  DL = &F.getParent()->getDataLayout();
1542  TPC = &getAnalysis<TargetPassConfig>();
1543  ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F);
1544 
1545  assert(PendingPHIs.empty() && "stale PHIs");
1546 
1547  if (!DL->isLittleEndian()) {
1548  // Currently we don't properly handle big endian code.
1549  OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1550  F.getSubprogram(), &F.getEntryBlock());
1551  R << "unable to translate in big endian mode";
1552  reportTranslationError(*MF, *TPC, *ORE, R);
1553  }
1554 
1555  // Release the per-function state when we return, whether we succeeded or not.
1556  auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); });
1557 
1558  // Setup a separate basic-block for the arguments and constants
1559  MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock();
1560  MF->push_back(EntryBB);
1561  EntryBuilder.setMBB(*EntryBB);
1562 
1563  // Create all blocks, in IR order, to preserve the layout.
1564  for (const BasicBlock &BB: F) {
1565  auto *&MBB = BBToMBB[&BB];
1566 
1567  MBB = MF->CreateMachineBasicBlock(&BB);
1568  MF->push_back(MBB);
1569 
1570  if (BB.hasAddressTaken())
1571  MBB->setHasAddressTaken();
1572  }
1573 
1574  // Make our arguments/constants entry block fallthrough to the IR entry block.
1575  EntryBB->addSuccessor(&getMBB(F.front()));
1576 
1577  // Lower the actual args into this basic block.
1578  SmallVector<unsigned, 8> VRegArgs;
1579  for (const Argument &Arg: F.args()) {
1580  if (DL->getTypeStoreSize(Arg.getType()) == 0)
1581  continue; // Don't handle zero sized types.
1582  VRegArgs.push_back(
1584  }
1585 
1586  // We don't currently support translating swifterror or swiftself functions.
1587  for (auto &Arg : F.args()) {
1588  if (Arg.hasSwiftErrorAttr() || Arg.hasSwiftSelfAttr()) {
1589  OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1590  F.getSubprogram(), &F.getEntryBlock());
1591  R << "unable to lower arguments due to swifterror/swiftself: "
1592  << ore::NV("Prototype", F.getType());
1593  reportTranslationError(*MF, *TPC, *ORE, R);
1594  return false;
1595  }
1596  }
1597 
1598  if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) {
1599  OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1600  F.getSubprogram(), &F.getEntryBlock());
1601  R << "unable to lower arguments: " << ore::NV("Prototype", F.getType());
1602  reportTranslationError(*MF, *TPC, *ORE, R);
1603  return false;
1604  }
1605 
1606  auto ArgIt = F.arg_begin();
1607  for (auto &VArg : VRegArgs) {
1608  // If the argument is an unsplit scalar then don't use unpackRegs to avoid
1609  // creating redundant copies.
1610  if (!valueIsSplit(*ArgIt, VMap.getOffsets(*ArgIt))) {
1611  auto &VRegs = *VMap.getVRegs(cast<Value>(*ArgIt));
1612  assert(VRegs.empty() && "VRegs already populated?");
1613  VRegs.push_back(VArg);
1614  } else {
1615  unpackRegs(*ArgIt, VArg, EntryBuilder);
1616  }
1617  ArgIt++;
1618  }
1619 
1620  // Need to visit defs before uses when translating instructions.
1622  for (const BasicBlock *BB : RPOT) {
1623  MachineBasicBlock &MBB = getMBB(*BB);
1624  // Set the insertion point of all the following translations to
1625  // the end of this basic block.
1626  CurBuilder.setMBB(MBB);
1627 
1628  for (const Instruction &Inst : *BB) {
1629  if (translate(Inst))
1630  continue;
1631 
1632  OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure",
1633  Inst.getDebugLoc(), BB);
1634  R << "unable to translate instruction: " << ore::NV("Opcode", &Inst);
1635 
1636  if (ORE->allowExtraAnalysis("gisel-irtranslator")) {
1637  std::string InstStrStorage;
1638  raw_string_ostream InstStr(InstStrStorage);
1639  InstStr << Inst;
1640 
1641  R << ": '" << InstStr.str() << "'";
1642  }
1643 
1644  reportTranslationError(*MF, *TPC, *ORE, R);
1645  return false;
1646  }
1647  }
1648 
1649  finishPendingPhis();
1650 
1651  // Merge the argument lowering and constants block with its single
1652  // successor, the LLVM-IR entry block. We want the basic block to
1653  // be maximal.
1654  assert(EntryBB->succ_size() == 1 &&
1655  "Custom BB used for lowering should have only one successor");
1656  // Get the successor of the current entry block.
1657  MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin();
1658  assert(NewEntryBB.pred_size() == 1 &&
1659  "LLVM-IR entry block has a predecessor!?");
1660  // Move all the instruction from the current entry block to the
1661  // new entry block.
1662  NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(),
1663  EntryBB->end());
1664 
1665  // Update the live-in information for the new entry block.
1666  for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins())
1667  NewEntryBB.addLiveIn(LiveIn);
1668  NewEntryBB.sortUniqueLiveIns();
1669 
1670  // Get rid of the now empty basic block.
1671  EntryBB->removeSuccessor(&NewEntryBB);
1672  MF->remove(EntryBB);
1673  MF->DeleteMachineBasicBlock(EntryBB);
1674 
1675  assert(&MF->front() == &NewEntryBB &&
1676  "New entry wasn't next in the list of basic block!");
1677 
1678  // Initialize stack protector information.
1679  StackProtector &SP = getAnalysis<StackProtector>();
1680  SP.copyToMachineFrameInfo(MF->getFrameInfo());
1681 
1682  return false;
1683 }
MachineInstrBuilder buildCopy(unsigned Res, unsigned Op)
Build and insert Res = COPY Op.
uint64_t CallInst * C
void initializeIRTranslatorPass(PassRegistry &)
Return a value (possibly void), from a function.
Value * getValueOperand()
Definition: Instructions.h:399
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:185
void push_back(const T &Elt)
Definition: SmallVector.h:218
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:875
bool empty() const
Definition: Function.h:648
MachineInstrBuilder buildIndirectDbgValue(unsigned Reg, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in me...
static IntegerType * getInt1Ty(LLVMContext &C)
Definition: Type.cpp:173
Diagnostic information for missed-optimization remarks.
This instruction extracts a struct member or array element value from an aggregate value...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
*p = old <signed v ? old : v
Definition: Instructions.h:711
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
This class represents an incoming formal argument to a Function.
Definition: Argument.h:30
LLVMContext & Context
DiagnosticInfoOptimizationBase::Argument NV
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:119
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
MachineInstrBuilder buildGEP(unsigned Res, unsigned Op0, unsigned Op1)
Build and insert Res = G_GEP Op0, Op1.
unsigned countOperandBundlesOfType(StringRef Name) const
Return the number of operand bundles with the tag Name attached to this instruction.
Definition: InstrTypes.h:1399
void getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU)
Modify analysis usage so it preserves passes required for the SelectionDAG fallback.
Definition: Utils.cpp:238
MCSymbol * addLandingPad(MachineBasicBlock *LandingPad)
Add a new panding pad. Returns the label ID for the landing pad entry.
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
bool isSized(SmallPtrSetImpl< Type *> *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:265
iterator begin() const
Definition: ArrayRef.h:137
MachineInstrBuilder buildInsertVectorElement(unsigned Res, unsigned Val, unsigned Elt, unsigned Idx)
Build and insert Res = G_INSERT_VECTOR_ELT Val, Elt, Idx.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:518
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
MachineInstrBuilder buildStore(unsigned Val, unsigned Addr, MachineMemOperand &MMO)
Build and insert G_STORE Val, Addr, MMO.
void addLandingPadInfo(const LandingPadInst &I, MachineBasicBlock &MBB)
Extract the exception handling information from the landingpad instruction and add them to the specif...
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:588
MachineInstrBuilder buildFConstant(DstType &&Res, const ConstantFP &Val)
Build and insert Res = G_FCONSTANT Val.
MachineInstrBuilder buildUndef(DstType &&Res)
Build and insert Res = IMPLICIT_DEF.
IRTranslator LLVM IR static false void reportTranslationError(MachineFunction &MF, const TargetPassConfig &TPC, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R)
This class represents a function call, abstracting a target machine&#39;s calling convention.
unsigned Reg
This file contains the declarations for metadata subclasses.
Value * getCondition() const
virtual const TargetLowering * getTargetLowering() const
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this store instruction.
Definition: Instructions.h:374
gep_type_iterator gep_type_end(const User *GEP)
const std::string & getAsmString() const
Definition: InlineAsm.h:81
*p = old <unsigned v ? old : v
Definition: Instructions.h:715
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:136
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
Definition: Instructions.h:237
Offsets
Offsets in bytes from the start of the input buffer.
Definition: SIInstrInfo.h:943
*p = old >unsigned v ? old : v
Definition: Instructions.h:713
LLT getType(unsigned Reg) const
Get the low-level type of Reg or LLT{} if Reg is not a generic (target independent) virtual register...
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
static const MCPhysReg VRegs[32]
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:714
bool hasDLLImportStorageClass() const
Definition: GlobalValue.h:261
BasicBlock * getSuccessor(unsigned i) const
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:360
unsigned const TargetRegisterInfo * TRI
F(f)
An instruction for reading from memory.
Definition: Instructions.h:168
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:681
Value * getCondition() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:230
CallingConv::ID getCallingConv() const
getCallingConv/setCallingConv - Get or set the calling convention of this function call...
void setMBB(MachineBasicBlock &MBB)
Set the insertion point to the end of MBB.
unsigned getTypeIDFor(const GlobalValue *TI)
Return the type id for the specified typeinfo. This is function wide.
MachineInstrBuilder buildBrCond(unsigned Tst, MachineBasicBlock &Dest)
Build and insert G_BRCOND Tst, Dest.
GlobalValue * ExtractTypeInfo(Value *V)
ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Definition: Analysis.cpp:118
*p = old >signed v ? old : v
Definition: Instructions.h:709
void DeleteMachineBasicBlock(MachineBasicBlock *MBB)
DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
unsigned getPointerABIAlignment(unsigned AS) const
Layout pointer alignment.
Definition: DataLayout.cpp:611
virtual bool getTgtMemIntrinsic(IntrinsicInfo &, const CallInst &, MachineFunction &, unsigned) const
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it...
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:268
AtomicOrdering getFailureOrdering() const
Returns the failure ordering constraint of this cmpxchg instruction.
Definition: Instructions.h:585
bool hasSideEffects() const
Definition: InlineAsm.h:67
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:521
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Definition: Instructions.h:221
A description of a memory reference used in the backend.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
#define DEBUG_TYPE
virtual bool lowerFormalArguments(MachineIRBuilder &MIRBuilder, const Function &F, ArrayRef< unsigned > VRegs) const
This hook must be implemented to lower the incoming (formal) arguments, described by Args...
Definition: CallLowering.h:159
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:113
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:97
Class to represent struct types.
Definition: DerivedTypes.h:201
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
void setMF(MachineFunction &)
BinOp getOperation() const
Definition: Instructions.h:734
const MachineInstrBuilder & addUse(unsigned RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register use operand.
bool isWeak() const
Return true if this cmpxchg may spuriously fail.
Definition: Instructions.h:559
MachineInstrBuilder buildBrIndirect(unsigned Tgt)
Build and insert G_BRINDIRECT Tgt.
The memory access is dereferenceable (i.e., doesn&#39;t trap).
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
bool isVolatile() const
Return true if this is a cmpxchg from a volatile memory location.
Definition: Instructions.h:547
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, unsigned base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Target-Independent Code Generator Pass Configuration Options.
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:630
MachineInstrBuilder buildConstDbgValue(const Constant &C, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instructions specifying that Variable is given by C (suitably modified b...
Context object for machine code objects.
Definition: MCContext.h:63
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
MachineInstrBuilder buildPtrMask(unsigned Res, unsigned Op0, uint32_t NumBits)
Build and insert Res = G_PTR_MASK Op0, NumBits.
AtomicOrdering getSuccessOrdering() const
Returns the success ordering constraint of this cmpxchg instruction.
Definition: Instructions.h:572
const RegList & Regs
Class to represent array types.
Definition: DerivedTypes.h:369
bool isLittleEndian() const
Layout endianness...
Definition: DataLayout.h:221
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:126
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1017
An instruction for storing to memory.
Definition: Instructions.h:310
static LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
MachineInstrBuilder buildGlobalValue(unsigned Res, const GlobalValue *GV)
Build and insert Res = G_GLOBAL_VALUE GV.
amdgpu Simplify well known AMD library false Value * Callee
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
Value * getOperand(unsigned i) const
Definition: User.h:170
bool doesNotAccessMemory() const
Determine if the call does not access memory.
Value * getOperand(unsigned i_nocapture) const
MCContext & getContext() const
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:562
bool isVoidTy() const
Return true if this is &#39;void&#39;.
Definition: Type.h:141
The memory access is volatile.
const BasicBlock & getEntryBlock() const
Definition: Function.h:626
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:610
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
Definition: DataLayout.cpp:742
MachineInstrBuilder buildIntrinsic(Intrinsic::ID ID, unsigned Res, bool HasSideEffects)
Build and insert either a G_INTRINSIC (if HasSideEffects is false) or G_INTRINSIC_W_SIDE_EFFECTS inst...
succ_range successors()
Definition: InstrTypes.h:268
FPOpFusion::FPOpFusionMode AllowFPOpFusion
AllowFPOpFusion - This flag is set by the -fuse-fp-ops=xxx option.
The landingpad instruction holds all of the information necessary to generate correct exception handl...
MachineInstrBuilder buildZExtOrTrunc(DstTy &&Dst, UseArgTy &&Use)
Build and insert Res = G_ZEXT Op, Res = G_TRUNC Op, or Res = COPY Op depending on the differing sizes...
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this rmw instruction.
Definition: Instructions.h:774
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
void addInvoke(MachineBasicBlock *LandingPad, MCSymbol *BeginLabel, MCSymbol *EndLabel)
Provide the begin and end labels of an invoke style call and associate it with a try landing pad bloc...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool lowerCall(MachineIRBuilder &MIRBuilder, CallingConv::ID CallConv, const MachineOperand &Callee, const ArgInfo &OrigRet, ArrayRef< ArgInfo > OrigArgs) const
This hook must be implemented to lower the given call instruction, including argument and return valu...
Definition: CallLowering.h:185
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1508
Conditional or Unconditional Branch instruction.
Value * getAddress() const
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
MachineInstrBuilder buildBr(MachineBasicBlock &Dest)
Build and insert G_BR Dest.
Value * getValue() const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Definition: BasicBlock.h:276
Indirect Branch Instruction.
BasicBlock * getDefaultDest() const
unsigned getPrefTypeAlignment(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:732
MachineInstrBuilder buildExtract(unsigned Res, unsigned Src, uint64_t Index)
Build and insert `Res0, ...
bool isValidLocationForIntrinsic(const DILocation *DL) const
Check that a location is valid for this variable.
Represent the analysis usage information of a pass.
DILocalVariable * getVariable() const
Definition: IntrinsicInst.h:80
Type::TypeID TypeID
MachineInstrBuilder buildDirectDbgValue(unsigned Reg, const MDNode *Variable, const MDNode *Expr)
Build and insert a DBG_VALUE instruction expressing the fact that the associated Variable lives in Re...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:885
virtual const CallLowering * getCallLowering() const
const Triple & getTargetTriple() const
DIExpression * getExpression() const
Definition: IntrinsicInst.h:84
Value * getPointerOperand()
Definition: Instructions.h:274
MachineInstrBuilder buildExtractVectorElement(unsigned Res, unsigned Val, unsigned Idx)
Build and insert Res = G_EXTRACT_VECTOR_ELT Val, Idx.
void remove(iterator MBBI)
self_iterator getIterator()
Definition: ilist_node.h:82
DebugLoc getDebugLoc()
Get the current instruction&#39;s debug location.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn&#39;t already there.
Definition: SmallSet.h:181
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
static double log2(double V)
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:322
1 1 1 1 Always true (always folded)
Definition: InstrTypes.h:902
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this cmpxchg instruction.
Definition: Instructions.h:598
iterator_range< User::op_iterator > arg_operands()
Iteration adapter for range-for loops.
BasicBlock * getSuccessor(unsigned i) const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
const MachineBasicBlock & front() const
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:93
size_t size() const
Definition: SmallVector.h:53
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this rmw instruction.
Definition: Instructions.h:761
This class contains a discriminated union of information about pointers in memory operands...
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:493
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
const std::string & getConstraintString() const
Definition: InlineAsm.h:82
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:106
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:635
LLT getLLTForType(Type &Ty, const DataLayout &DL)
Construct a low-level type based on an LLVM type.
The memory access writes data.
unsigned createGenericVirtualRegister(LLT Ty, StringRef Name="")
Create and return a new generic virtual register with low-level type Ty.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:387
Value * getValOperand()
Definition: Instructions.h:787
MachineInstrBuilder buildSExtOrTrunc(DstTy &&Dst, UseArgTy &&Use)
Build and insert Res = G_SEXT Op, Res = G_TRUNC Op, or Res = COPY Op depending on the differing sizes...
Predicate getPredicate(unsigned Condition, unsigned Hint)
Return predicate consisting of specified condition and hint bits.
Definition: PPCPredicates.h:88
unsigned getNumOperands() const
Definition: User.h:192
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
This is the shared class of boolean and integer constants.
Definition: Constants.h:84
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
iterator end() const
Definition: ArrayRef.h:138
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:722
bool isAggregateType() const
Return true if the type is an aggregate type.
Definition: Type.h:258
unsigned getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL)
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:642
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:180
MachineInstrBuilder buildFrameIndex(unsigned Res, int Idx)
Build and insert Res = G_FRAME_INDEX Idx.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:621
unsigned getNumIncomingValues() const
Return the number of incoming edges.
MachineInstrBuilder buildSelect(unsigned Res, unsigned Tst, unsigned Op0, unsigned Op1)
Build and insert a Res = G_SELECT Tst, Op0, Op1.
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:180
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:539
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:462
bool isIntPredicate() const
Definition: InstrTypes.h:977
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:56
static MachineOperand CreateES(const char *SymName, unsigned char TargetFlags=0)
static char ID
Definition: IRTranslator.h:61
virtual bool isFMAFasterThanFMulAndFAdd(EVT) const
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
MachineInstrBuilder buildConstant(unsigned Res, const ConstantInt &Val)
Build and insert Res = G_CONSTANT Val.
amdgpu Simplify well known AMD library false Value Value * Arg
MachineInstrBuilder buildAtomicRMW(unsigned Opcode, unsigned OldValRes, unsigned Addr, unsigned Val, MachineMemOperand &MMO)
Build and insert OldValRes<def> = G_ATOMICRMW_<Opcode> Addr, Val, MMO.
The memory access reads data.
#define Success
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:560
static MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
MachineInstrBuilder buildMerge(unsigned Res, ArrayRef< unsigned > Ops)
Build and insert Res = G_MERGE_VALUES Op0, ...
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:428
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:959
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Definition: Instructions.h:343
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:290
bool isInlineAsm() const
Check if this call is an inline asm statement.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:543
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:652
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
AtomicOrdering getOrdering() const
Returns the ordering constraint of this store instruction.
Definition: Instructions.h:362
This represents the llvm.dbg.value instruction.
bool isTokenTy() const
Return true if this is &#39;token&#39;.
Definition: Type.h:194
Value * getPointerOperand()
Definition: Instructions.h:783
virtual const TargetIntrinsicInfo * getIntrinsicInfo() const
If intrinsic information is available, return it. If not, return null.
TargetOptions Options
Definition: TargetMachine.h:98
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
Definition: Instructions.h:249
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned char TargetFlags=0) const
#define I(x, y, z)
Definition: MD5.cpp:58
MachineInstrBuilder buildLoad(unsigned Res, unsigned Addr, MachineMemOperand &MMO)
Build and insert Res = G_LOAD Addr, MMO.
static Constant * getZeroValueForNegation(Type *Ty)
Floating point negation must be implemented with f(x) = -0.0 - x.
Definition: Constants.cpp:748
Pair of physical register and lane mask.
virtual const TargetFrameLowering * getFrameLowering() const
The memory access always returns the same value (or traps).
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:193
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void setDebugLoc(const DebugLoc &DL)
Set the debug location to DL for all the next build instructions.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Optional< MachineInstrBuilder > materializeGEP(unsigned &Res, unsigned Op0, const LLT &ValueTy, uint64_t Value)
Materialize and insert Res = G_GEP Op0, (G_CONSTANT Value)
bool isUnconditional() const
MachineInstrBuilder buildCast(DstType &&Res, ArgType &&Arg)
Build and insert an appropriate cast between two registers of equal size.
static void computeValueLLTs(const DataLayout &DL, Type &Ty, SmallVectorImpl< LLT > &ValueTys, SmallVectorImpl< uint64_t > *Offsets=nullptr, uint64_t StartingOffset=0)
AsmDialect getDialect() const
Definition: InlineAsm.h:69
Multiway switch.
MachineInstrBuilder buildAtomicCmpXchgWithSuccess(unsigned OldValRes, unsigned SuccessRes, unsigned Addr, unsigned CmpVal, unsigned NewVal, MachineMemOperand &MMO)
Build and insert OldValRes<def>, SuccessRes<def> = G_ATOMIC_CMPXCHG_WITH_SUCCESS Addr, CmpVal, NewVal, MMO.
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
This file declares the IRTranslator pass.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:477
aarch64 promote const
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1288
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:411
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
This file describes how to lower LLVM calls to machine code calls.
void push_back(MachineBasicBlock *MBB)
unsigned getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", false, false) INITIALIZE_PASS_END(IRTranslator
MachineBasicBlock & getMBB()
Getter for the basic block we currently build.
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
Invoke instruction.
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:59
MachineInstrBuilder buildInstr(unsigned Opc, DstTy &&Ty, UseArgsTy &&... Args)
DAG like Generic method for building arbitrary instructions as above.
IRTranslator LLVM IR MI
MachineInstrBuilder buildFCmp(CmpInst::Predicate Pred, unsigned Res, unsigned Op0, unsigned Op1)
Build and insert a Res = G_FCMP PredOp0, Op1.
MachineInstrBuilder buildMul(unsigned Dst, unsigned Src0, unsigned Src1)
Build and insert Res = G_MUL Op0, Op1.
void setRegClass(unsigned Reg, const TargetRegisterClass *RC)
setRegClass - Set the register class of the specified virtual register.
const MachineInstrBuilder & addDef(unsigned RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a virtual register definition operand.
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
MachineInstrBuilder buildInsert(unsigned Res, unsigned Src, unsigned Op, unsigned Index)
#define LLVM_DEBUG(X)
Definition: Debug.h:119
MachineInstrBuilder buildBlockAddress(unsigned Res, const BlockAddress *BA)
Build and insert Res = G_BLOCK_ADDR BA.
virtual bool lowerReturn(MachineIRBuilder &MIRBuilder, const Value *Val, unsigned VReg) const
This hook must be implemented to lower outgoing return values, described by Val, into the specified v...
Definition: CallLowering.h:145
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:973
void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, int Slot, const DILocation *Loc)
Collect information used to emit debugging information of a variable.
int CreateVariableSizedObject(unsigned Alignment, const AllocaInst *Alloca)
Notify the MachineFrameInfo object that a variable sized object has been created. ...
This represents the llvm.dbg.declare instruction.
Value * getPointerOperand()
Definition: Instructions.h:402
MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num)
allocateMemRefsArray - Allocate an array to hold MachineMemOperand pointers.
The optimization diagnostic interface.
Statically lint checks LLVM IR
Definition: Lint.cpp:193
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
MachineInstrBuilder buildICmp(CmpInst::Predicate Pred, unsigned Res, unsigned Op0, unsigned Op1)
Build and insert a Res = G_ICMP Pred, Op0, Op1.
int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef< Value *> Indices) const
Returns the offset from the beginning of the type for the specified indices.
Definition: DataLayout.cpp:779
bool isVolatile() const
Return true if this is a RMW on a volatile memory location.
Definition: Instructions.h:746
0 0 0 0 Always false (always folded)
Definition: InstrTypes.h:887
IntegerType * Int32Ty
This file describes how to lower LLVM code to machine code.
const BasicBlock * getParent() const
Definition: Instruction.h:67
virtual const TargetRegisterClass * getPointerRegClass(const MachineFunction &MF, unsigned Kind=0) const
Returns a TargetRegisterClass used for pointer values.
an instruction to allocate memory on the stack
Definition: Instructions.h:60
This instruction inserts a struct field of array element value into an aggregate value.
gep_type_iterator gep_type_begin(const User *GEP)
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition: SmallSet.h:165