IRTranslator.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/CodeGen/GlobalISel/IRTranslator.h - IRTranslator ----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. /// \file
  14. /// This file declares the IRTranslator pass.
  15. /// This pass is responsible for translating LLVM IR into MachineInstr.
  16. /// It uses target hooks to lower the ABI but aside from that, the pass
  17. /// generated code is generic. This is the default translator used for
  18. /// GlobalISel.
  19. ///
  20. /// \todo Replace the comments with actual doxygen comments.
  21. //===----------------------------------------------------------------------===//
  22. #ifndef LLVM_CODEGEN_GLOBALISEL_IRTRANSLATOR_H
  23. #define LLVM_CODEGEN_GLOBALISEL_IRTRANSLATOR_H
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/ADT/SmallVector.h"
  26. #include "llvm/CodeGen/CodeGenCommonISel.h"
  27. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  28. #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
  29. #include "llvm/CodeGen/MachineFunctionPass.h"
  30. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  31. #include "llvm/CodeGen/SwitchLoweringUtils.h"
  32. #include "llvm/Support/Allocator.h"
  33. #include "llvm/Support/CodeGen.h"
  34. #include <memory>
  35. #include <utility>
  36. namespace llvm {
  37. class AllocaInst;
  38. class AssumptionCache;
  39. class BasicBlock;
  40. class CallInst;
  41. class CallLowering;
  42. class Constant;
  43. class ConstrainedFPIntrinsic;
  44. class DataLayout;
  45. class Instruction;
  46. class MachineBasicBlock;
  47. class MachineFunction;
  48. class MachineInstr;
  49. class MachineRegisterInfo;
  50. class OptimizationRemarkEmitter;
  51. class PHINode;
  52. class TargetLibraryInfo;
  53. class TargetPassConfig;
  54. class User;
  55. class Value;
  56. // Technically the pass should run on an hypothetical MachineModule,
  57. // since it should translate Global into some sort of MachineGlobal.
  58. // The MachineGlobal should ultimately just be a transfer of ownership of
  59. // the interesting bits that are relevant to represent a global value.
  60. // That being said, we could investigate what would it cost to just duplicate
  61. // the information from the LLVM IR.
  62. // The idea is that ultimately we would be able to free up the memory used
  63. // by the LLVM IR as soon as the translation is over.
  64. class IRTranslator : public MachineFunctionPass {
  65. public:
  66. static char ID;
  67. private:
  68. /// Interface used to lower the everything related to calls.
  69. const CallLowering *CLI;
  70. /// This class contains the mapping between the Values to vreg related data.
  71. class ValueToVRegInfo {
  72. public:
  73. ValueToVRegInfo() = default;
  74. using VRegListT = SmallVector<Register, 1>;
  75. using OffsetListT = SmallVector<uint64_t, 1>;
  76. using const_vreg_iterator =
  77. DenseMap<const Value *, VRegListT *>::const_iterator;
  78. using const_offset_iterator =
  79. DenseMap<const Value *, OffsetListT *>::const_iterator;
  80. inline const_vreg_iterator vregs_end() const { return ValToVRegs.end(); }
  81. VRegListT *getVRegs(const Value &V) {
  82. auto It = ValToVRegs.find(&V);
  83. if (It != ValToVRegs.end())
  84. return It->second;
  85. return insertVRegs(V);
  86. }
  87. OffsetListT *getOffsets(const Value &V) {
  88. auto It = TypeToOffsets.find(V.getType());
  89. if (It != TypeToOffsets.end())
  90. return It->second;
  91. return insertOffsets(V);
  92. }
  93. const_vreg_iterator findVRegs(const Value &V) const {
  94. return ValToVRegs.find(&V);
  95. }
  96. bool contains(const Value &V) const {
  97. return ValToVRegs.find(&V) != ValToVRegs.end();
  98. }
  99. void reset() {
  100. ValToVRegs.clear();
  101. TypeToOffsets.clear();
  102. VRegAlloc.DestroyAll();
  103. OffsetAlloc.DestroyAll();
  104. }
  105. private:
  106. VRegListT *insertVRegs(const Value &V) {
  107. assert(ValToVRegs.find(&V) == ValToVRegs.end() && "Value already exists");
  108. // We placement new using our fast allocator since we never try to free
  109. // the vectors until translation is finished.
  110. auto *VRegList = new (VRegAlloc.Allocate()) VRegListT();
  111. ValToVRegs[&V] = VRegList;
  112. return VRegList;
  113. }
  114. OffsetListT *insertOffsets(const Value &V) {
  115. assert(TypeToOffsets.find(V.getType()) == TypeToOffsets.end() &&
  116. "Type already exists");
  117. auto *OffsetList = new (OffsetAlloc.Allocate()) OffsetListT();
  118. TypeToOffsets[V.getType()] = OffsetList;
  119. return OffsetList;
  120. }
  121. SpecificBumpPtrAllocator<VRegListT> VRegAlloc;
  122. SpecificBumpPtrAllocator<OffsetListT> OffsetAlloc;
  123. // We store pointers to vectors here since references may be invalidated
  124. // while we hold them if we stored the vectors directly.
  125. DenseMap<const Value *, VRegListT*> ValToVRegs;
  126. DenseMap<const Type *, OffsetListT*> TypeToOffsets;
  127. };
  128. /// Mapping of the values of the current LLVM IR function to the related
  129. /// virtual registers and offsets.
  130. ValueToVRegInfo VMap;
  131. // N.b. it's not completely obvious that this will be sufficient for every
  132. // LLVM IR construct (with "invoke" being the obvious candidate to mess up our
  133. // lives.
  134. DenseMap<const BasicBlock *, MachineBasicBlock *> BBToMBB;
  135. // One BasicBlock can be translated to multiple MachineBasicBlocks. For such
  136. // BasicBlocks translated to multiple MachineBasicBlocks, MachinePreds retains
  137. // a mapping between the edges arriving at the BasicBlock to the corresponding
  138. // created MachineBasicBlocks. Some BasicBlocks that get translated to a
  139. // single MachineBasicBlock may also end up in this Map.
  140. using CFGEdge = std::pair<const BasicBlock *, const BasicBlock *>;
  141. DenseMap<CFGEdge, SmallVector<MachineBasicBlock *, 1>> MachinePreds;
  142. // List of stubbed PHI instructions, for values and basic blocks to be filled
  143. // in once all MachineBasicBlocks have been created.
  144. SmallVector<std::pair<const PHINode *, SmallVector<MachineInstr *, 1>>, 4>
  145. PendingPHIs;
  146. /// Record of what frame index has been allocated to specified allocas for
  147. /// this function.
  148. DenseMap<const AllocaInst *, int> FrameIndices;
  149. SwiftErrorValueTracking SwiftError;
  150. /// \name Methods for translating form LLVM IR to MachineInstr.
  151. /// \see ::translate for general information on the translate methods.
  152. /// @{
  153. /// Translate \p Inst into its corresponding MachineInstr instruction(s).
  154. /// Insert the newly translated instruction(s) right where the CurBuilder
  155. /// is set.
  156. ///
  157. /// The general algorithm is:
  158. /// 1. Look for a virtual register for each operand or
  159. /// create one.
  160. /// 2 Update the VMap accordingly.
  161. /// 2.alt. For constant arguments, if they are compile time constants,
  162. /// produce an immediate in the right operand and do not touch
  163. /// ValToReg. Actually we will go with a virtual register for each
  164. /// constants because it may be expensive to actually materialize the
  165. /// constant. Moreover, if the constant spans on several instructions,
  166. /// CSE may not catch them.
  167. /// => Update ValToVReg and remember that we saw a constant in Constants.
  168. /// We will materialize all the constants in finalize.
  169. /// Note: we would need to do something so that we can recognize such operand
  170. /// as constants.
  171. /// 3. Create the generic instruction.
  172. ///
  173. /// \return true if the translation succeeded.
  174. bool translate(const Instruction &Inst);
  175. /// Materialize \p C into virtual-register \p Reg. The generic instructions
  176. /// performing this materialization will be inserted into the entry block of
  177. /// the function.
  178. ///
  179. /// \return true if the materialization succeeded.
  180. bool translate(const Constant &C, Register Reg);
  181. // Translate U as a copy of V.
  182. bool translateCopy(const User &U, const Value &V,
  183. MachineIRBuilder &MIRBuilder);
  184. /// Translate an LLVM bitcast into generic IR. Either a COPY or a G_BITCAST is
  185. /// emitted.
  186. bool translateBitCast(const User &U, MachineIRBuilder &MIRBuilder);
  187. /// Translate an LLVM load instruction into generic IR.
  188. bool translateLoad(const User &U, MachineIRBuilder &MIRBuilder);
  189. /// Translate an LLVM store instruction into generic IR.
  190. bool translateStore(const User &U, MachineIRBuilder &MIRBuilder);
  191. /// Translate an LLVM string intrinsic (memcpy, memset, ...).
  192. bool translateMemFunc(const CallInst &CI, MachineIRBuilder &MIRBuilder,
  193. unsigned Opcode);
  194. void getStackGuard(Register DstReg, MachineIRBuilder &MIRBuilder);
  195. bool translateOverflowIntrinsic(const CallInst &CI, unsigned Op,
  196. MachineIRBuilder &MIRBuilder);
  197. bool translateFixedPointIntrinsic(unsigned Op, const CallInst &CI,
  198. MachineIRBuilder &MIRBuilder);
  199. /// Helper function for translateSimpleIntrinsic.
  200. /// \return The generic opcode for \p IntrinsicID if \p IntrinsicID is a
  201. /// simple intrinsic (ceil, fabs, etc.). Otherwise, returns
  202. /// Intrinsic::not_intrinsic.
  203. unsigned getSimpleIntrinsicOpcode(Intrinsic::ID ID);
  204. /// Translates the intrinsics defined in getSimpleIntrinsicOpcode.
  205. /// \return true if the translation succeeded.
  206. bool translateSimpleIntrinsic(const CallInst &CI, Intrinsic::ID ID,
  207. MachineIRBuilder &MIRBuilder);
  208. bool translateConstrainedFPIntrinsic(const ConstrainedFPIntrinsic &FPI,
  209. MachineIRBuilder &MIRBuilder);
  210. bool translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID,
  211. MachineIRBuilder &MIRBuilder);
  212. bool translateInlineAsm(const CallBase &CB, MachineIRBuilder &MIRBuilder);
  213. /// Common code for translating normal calls or invokes.
  214. bool translateCallBase(const CallBase &CB, MachineIRBuilder &MIRBuilder);
  215. /// Translate call instruction.
  216. /// \pre \p U is a call instruction.
  217. bool translateCall(const User &U, MachineIRBuilder &MIRBuilder);
  218. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  219. /// many places it could ultimately go. In the IR, we have a single unwind
  220. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  221. /// This function skips over imaginary basic blocks that hold catchswitch
  222. /// instructions, and finds all the "real" machine
  223. /// basic block destinations. As those destinations may not be successors of
  224. /// EHPadBB, here we also calculate the edge probability to those
  225. /// destinations. The passed-in Prob is the edge probability to EHPadBB.
  226. bool findUnwindDestinations(
  227. const BasicBlock *EHPadBB, BranchProbability Prob,
  228. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  229. &UnwindDests);
  230. bool translateInvoke(const User &U, MachineIRBuilder &MIRBuilder);
  231. bool translateCallBr(const User &U, MachineIRBuilder &MIRBuilder);
  232. bool translateLandingPad(const User &U, MachineIRBuilder &MIRBuilder);
  233. /// Translate one of LLVM's cast instructions into MachineInstrs, with the
  234. /// given generic Opcode.
  235. bool translateCast(unsigned Opcode, const User &U,
  236. MachineIRBuilder &MIRBuilder);
  237. /// Translate a phi instruction.
  238. bool translatePHI(const User &U, MachineIRBuilder &MIRBuilder);
  239. /// Translate a comparison (icmp or fcmp) instruction or constant.
  240. bool translateCompare(const User &U, MachineIRBuilder &MIRBuilder);
  241. /// Translate an integer compare instruction (or constant).
  242. bool translateICmp(const User &U, MachineIRBuilder &MIRBuilder) {
  243. return translateCompare(U, MIRBuilder);
  244. }
  245. /// Translate a floating-point compare instruction (or constant).
  246. bool translateFCmp(const User &U, MachineIRBuilder &MIRBuilder) {
  247. return translateCompare(U, MIRBuilder);
  248. }
  249. /// Add remaining operands onto phis we've translated. Executed after all
  250. /// MachineBasicBlocks for the function have been created.
  251. void finishPendingPhis();
  252. /// Translate \p Inst into a unary operation \p Opcode.
  253. /// \pre \p U is a unary operation.
  254. bool translateUnaryOp(unsigned Opcode, const User &U,
  255. MachineIRBuilder &MIRBuilder);
  256. /// Translate \p Inst into a binary operation \p Opcode.
  257. /// \pre \p U is a binary operation.
  258. bool translateBinaryOp(unsigned Opcode, const User &U,
  259. MachineIRBuilder &MIRBuilder);
  260. /// If the set of cases should be emitted as a series of branches, return
  261. /// true. If we should emit this as a bunch of and/or'd together conditions,
  262. /// return false.
  263. bool shouldEmitAsBranches(const std::vector<SwitchCG::CaseBlock> &Cases);
  264. /// Helper method for findMergedConditions.
  265. /// This function emits a branch and is used at the leaves of an OR or an
  266. /// AND operator tree.
  267. void emitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
  268. MachineBasicBlock *FBB,
  269. MachineBasicBlock *CurBB,
  270. MachineBasicBlock *SwitchBB,
  271. BranchProbability TProb,
  272. BranchProbability FProb, bool InvertCond);
  273. /// Used during condbr translation to find trees of conditions that can be
  274. /// optimized.
  275. void findMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
  276. MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
  277. MachineBasicBlock *SwitchBB,
  278. Instruction::BinaryOps Opc, BranchProbability TProb,
  279. BranchProbability FProb, bool InvertCond);
  280. /// Translate branch (br) instruction.
  281. /// \pre \p U is a branch instruction.
  282. bool translateBr(const User &U, MachineIRBuilder &MIRBuilder);
  283. // Begin switch lowering functions.
  284. bool emitJumpTableHeader(SwitchCG::JumpTable &JT,
  285. SwitchCG::JumpTableHeader &JTH,
  286. MachineBasicBlock *HeaderBB);
  287. void emitJumpTable(SwitchCG::JumpTable &JT, MachineBasicBlock *MBB);
  288. void emitSwitchCase(SwitchCG::CaseBlock &CB, MachineBasicBlock *SwitchBB,
  289. MachineIRBuilder &MIB);
  290. /// Generate for for the BitTest header block, which precedes each sequence of
  291. /// BitTestCases.
  292. void emitBitTestHeader(SwitchCG::BitTestBlock &BTB,
  293. MachineBasicBlock *SwitchMBB);
  294. /// Generate code to produces one "bit test" for a given BitTestCase \p B.
  295. void emitBitTestCase(SwitchCG::BitTestBlock &BB, MachineBasicBlock *NextMBB,
  296. BranchProbability BranchProbToNext, Register Reg,
  297. SwitchCG::BitTestCase &B, MachineBasicBlock *SwitchBB);
  298. bool lowerJumpTableWorkItem(
  299. SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB,
  300. MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
  301. MachineIRBuilder &MIB, MachineFunction::iterator BBI,
  302. BranchProbability UnhandledProbs, SwitchCG::CaseClusterIt I,
  303. MachineBasicBlock *Fallthrough, bool FallthroughUnreachable);
  304. bool lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I, Value *Cond,
  305. MachineBasicBlock *Fallthrough,
  306. bool FallthroughUnreachable,
  307. BranchProbability UnhandledProbs,
  308. MachineBasicBlock *CurMBB,
  309. MachineIRBuilder &MIB,
  310. MachineBasicBlock *SwitchMBB);
  311. bool lowerBitTestWorkItem(
  312. SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB,
  313. MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB,
  314. MachineIRBuilder &MIB, MachineFunction::iterator BBI,
  315. BranchProbability DefaultProb, BranchProbability UnhandledProbs,
  316. SwitchCG::CaseClusterIt I, MachineBasicBlock *Fallthrough,
  317. bool FallthroughUnreachable);
  318. bool lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W, Value *Cond,
  319. MachineBasicBlock *SwitchMBB,
  320. MachineBasicBlock *DefaultMBB,
  321. MachineIRBuilder &MIB);
  322. bool translateSwitch(const User &U, MachineIRBuilder &MIRBuilder);
  323. // End switch lowering section.
  324. bool translateIndirectBr(const User &U, MachineIRBuilder &MIRBuilder);
  325. bool translateExtractValue(const User &U, MachineIRBuilder &MIRBuilder);
  326. bool translateInsertValue(const User &U, MachineIRBuilder &MIRBuilder);
  327. bool translateSelect(const User &U, MachineIRBuilder &MIRBuilder);
  328. bool translateGetElementPtr(const User &U, MachineIRBuilder &MIRBuilder);
  329. bool translateAlloca(const User &U, MachineIRBuilder &MIRBuilder);
  330. /// Translate return (ret) instruction.
  331. /// The target needs to implement CallLowering::lowerReturn for
  332. /// this to succeed.
  333. /// \pre \p U is a return instruction.
  334. bool translateRet(const User &U, MachineIRBuilder &MIRBuilder);
  335. bool translateFNeg(const User &U, MachineIRBuilder &MIRBuilder);
  336. bool translateAdd(const User &U, MachineIRBuilder &MIRBuilder) {
  337. return translateBinaryOp(TargetOpcode::G_ADD, U, MIRBuilder);
  338. }
  339. bool translateSub(const User &U, MachineIRBuilder &MIRBuilder) {
  340. return translateBinaryOp(TargetOpcode::G_SUB, U, MIRBuilder);
  341. }
  342. bool translateAnd(const User &U, MachineIRBuilder &MIRBuilder) {
  343. return translateBinaryOp(TargetOpcode::G_AND, U, MIRBuilder);
  344. }
  345. bool translateMul(const User &U, MachineIRBuilder &MIRBuilder) {
  346. return translateBinaryOp(TargetOpcode::G_MUL, U, MIRBuilder);
  347. }
  348. bool translateOr(const User &U, MachineIRBuilder &MIRBuilder) {
  349. return translateBinaryOp(TargetOpcode::G_OR, U, MIRBuilder);
  350. }
  351. bool translateXor(const User &U, MachineIRBuilder &MIRBuilder) {
  352. return translateBinaryOp(TargetOpcode::G_XOR, U, MIRBuilder);
  353. }
  354. bool translateUDiv(const User &U, MachineIRBuilder &MIRBuilder) {
  355. return translateBinaryOp(TargetOpcode::G_UDIV, U, MIRBuilder);
  356. }
  357. bool translateSDiv(const User &U, MachineIRBuilder &MIRBuilder) {
  358. return translateBinaryOp(TargetOpcode::G_SDIV, U, MIRBuilder);
  359. }
  360. bool translateURem(const User &U, MachineIRBuilder &MIRBuilder) {
  361. return translateBinaryOp(TargetOpcode::G_UREM, U, MIRBuilder);
  362. }
  363. bool translateSRem(const User &U, MachineIRBuilder &MIRBuilder) {
  364. return translateBinaryOp(TargetOpcode::G_SREM, U, MIRBuilder);
  365. }
  366. bool translateIntToPtr(const User &U, MachineIRBuilder &MIRBuilder) {
  367. return translateCast(TargetOpcode::G_INTTOPTR, U, MIRBuilder);
  368. }
  369. bool translatePtrToInt(const User &U, MachineIRBuilder &MIRBuilder) {
  370. return translateCast(TargetOpcode::G_PTRTOINT, U, MIRBuilder);
  371. }
  372. bool translateTrunc(const User &U, MachineIRBuilder &MIRBuilder) {
  373. return translateCast(TargetOpcode::G_TRUNC, U, MIRBuilder);
  374. }
  375. bool translateFPTrunc(const User &U, MachineIRBuilder &MIRBuilder) {
  376. return translateCast(TargetOpcode::G_FPTRUNC, U, MIRBuilder);
  377. }
  378. bool translateFPExt(const User &U, MachineIRBuilder &MIRBuilder) {
  379. return translateCast(TargetOpcode::G_FPEXT, U, MIRBuilder);
  380. }
  381. bool translateFPToUI(const User &U, MachineIRBuilder &MIRBuilder) {
  382. return translateCast(TargetOpcode::G_FPTOUI, U, MIRBuilder);
  383. }
  384. bool translateFPToSI(const User &U, MachineIRBuilder &MIRBuilder) {
  385. return translateCast(TargetOpcode::G_FPTOSI, U, MIRBuilder);
  386. }
  387. bool translateUIToFP(const User &U, MachineIRBuilder &MIRBuilder) {
  388. return translateCast(TargetOpcode::G_UITOFP, U, MIRBuilder);
  389. }
  390. bool translateSIToFP(const User &U, MachineIRBuilder &MIRBuilder) {
  391. return translateCast(TargetOpcode::G_SITOFP, U, MIRBuilder);
  392. }
  393. bool translateUnreachable(const User &U, MachineIRBuilder &MIRBuilder);
  394. bool translateSExt(const User &U, MachineIRBuilder &MIRBuilder) {
  395. return translateCast(TargetOpcode::G_SEXT, U, MIRBuilder);
  396. }
  397. bool translateZExt(const User &U, MachineIRBuilder &MIRBuilder) {
  398. return translateCast(TargetOpcode::G_ZEXT, U, MIRBuilder);
  399. }
  400. bool translateShl(const User &U, MachineIRBuilder &MIRBuilder) {
  401. return translateBinaryOp(TargetOpcode::G_SHL, U, MIRBuilder);
  402. }
  403. bool translateLShr(const User &U, MachineIRBuilder &MIRBuilder) {
  404. return translateBinaryOp(TargetOpcode::G_LSHR, U, MIRBuilder);
  405. }
  406. bool translateAShr(const User &U, MachineIRBuilder &MIRBuilder) {
  407. return translateBinaryOp(TargetOpcode::G_ASHR, U, MIRBuilder);
  408. }
  409. bool translateFAdd(const User &U, MachineIRBuilder &MIRBuilder) {
  410. return translateBinaryOp(TargetOpcode::G_FADD, U, MIRBuilder);
  411. }
  412. bool translateFSub(const User &U, MachineIRBuilder &MIRBuilder) {
  413. return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder);
  414. }
  415. bool translateFMul(const User &U, MachineIRBuilder &MIRBuilder) {
  416. return translateBinaryOp(TargetOpcode::G_FMUL, U, MIRBuilder);
  417. }
  418. bool translateFDiv(const User &U, MachineIRBuilder &MIRBuilder) {
  419. return translateBinaryOp(TargetOpcode::G_FDIV, U, MIRBuilder);
  420. }
  421. bool translateFRem(const User &U, MachineIRBuilder &MIRBuilder) {
  422. return translateBinaryOp(TargetOpcode::G_FREM, U, MIRBuilder);
  423. }
  424. bool translateVAArg(const User &U, MachineIRBuilder &MIRBuilder);
  425. bool translateInsertElement(const User &U, MachineIRBuilder &MIRBuilder);
  426. bool translateExtractElement(const User &U, MachineIRBuilder &MIRBuilder);
  427. bool translateShuffleVector(const User &U, MachineIRBuilder &MIRBuilder);
  428. bool translateAtomicCmpXchg(const User &U, MachineIRBuilder &MIRBuilder);
  429. bool translateAtomicRMW(const User &U, MachineIRBuilder &MIRBuilder);
  430. bool translateFence(const User &U, MachineIRBuilder &MIRBuilder);
  431. bool translateFreeze(const User &U, MachineIRBuilder &MIRBuilder);
  432. // Stubs to keep the compiler happy while we implement the rest of the
  433. // translation.
  434. bool translateResume(const User &U, MachineIRBuilder &MIRBuilder) {
  435. return false;
  436. }
  437. bool translateCleanupRet(const User &U, MachineIRBuilder &MIRBuilder) {
  438. return false;
  439. }
  440. bool translateCatchRet(const User &U, MachineIRBuilder &MIRBuilder) {
  441. return false;
  442. }
  443. bool translateCatchSwitch(const User &U, MachineIRBuilder &MIRBuilder) {
  444. return false;
  445. }
  446. bool translateAddrSpaceCast(const User &U, MachineIRBuilder &MIRBuilder) {
  447. return translateCast(TargetOpcode::G_ADDRSPACE_CAST, U, MIRBuilder);
  448. }
  449. bool translateCleanupPad(const User &U, MachineIRBuilder &MIRBuilder) {
  450. return false;
  451. }
  452. bool translateCatchPad(const User &U, MachineIRBuilder &MIRBuilder) {
  453. return false;
  454. }
  455. bool translateUserOp1(const User &U, MachineIRBuilder &MIRBuilder) {
  456. return false;
  457. }
  458. bool translateUserOp2(const User &U, MachineIRBuilder &MIRBuilder) {
  459. return false;
  460. }
  461. /// @}
  462. // Builder for machine instruction a la IRBuilder.
  463. // I.e., compared to regular MIBuilder, this one also inserts the instruction
  464. // in the current block, it can creates block, etc., basically a kind of
  465. // IRBuilder, but for Machine IR.
  466. // CSEMIRBuilder CurBuilder;
  467. std::unique_ptr<MachineIRBuilder> CurBuilder;
  468. // Builder set to the entry block (just after ABI lowering instructions). Used
  469. // as a convenient location for Constants.
  470. // CSEMIRBuilder EntryBuilder;
  471. std::unique_ptr<MachineIRBuilder> EntryBuilder;
  472. // The MachineFunction currently being translated.
  473. MachineFunction *MF;
  474. /// MachineRegisterInfo used to create virtual registers.
  475. MachineRegisterInfo *MRI = nullptr;
  476. const DataLayout *DL;
  477. /// Current target configuration. Controls how the pass handles errors.
  478. const TargetPassConfig *TPC;
  479. CodeGenOpt::Level OptLevel;
  480. /// Current optimization remark emitter. Used to report failures.
  481. std::unique_ptr<OptimizationRemarkEmitter> ORE;
  482. AAResults *AA;
  483. AssumptionCache *AC;
  484. const TargetLibraryInfo *LibInfo;
  485. FunctionLoweringInfo FuncInfo;
  486. // True when either the Target Machine specifies no optimizations or the
  487. // function has the optnone attribute.
  488. bool EnableOpts = false;
  489. /// True when the block contains a tail call. This allows the IRTranslator to
  490. /// stop translating such blocks early.
  491. bool HasTailCall = false;
  492. StackProtectorDescriptor SPDescriptor;
  493. /// Switch analysis and optimization.
  494. class GISelSwitchLowering : public SwitchCG::SwitchLowering {
  495. public:
  496. GISelSwitchLowering(IRTranslator *irt, FunctionLoweringInfo &funcinfo)
  497. : SwitchLowering(funcinfo), IRT(irt) {
  498. assert(irt && "irt is null!");
  499. }
  500. void addSuccessorWithProb(
  501. MachineBasicBlock *Src, MachineBasicBlock *Dst,
  502. BranchProbability Prob = BranchProbability::getUnknown()) override {
  503. IRT->addSuccessorWithProb(Src, Dst, Prob);
  504. }
  505. virtual ~GISelSwitchLowering() = default;
  506. private:
  507. IRTranslator *IRT;
  508. };
  509. std::unique_ptr<GISelSwitchLowering> SL;
  510. // * Insert all the code needed to materialize the constants
  511. // at the proper place. E.g., Entry block or dominator block
  512. // of each constant depending on how fancy we want to be.
  513. // * Clear the different maps.
  514. void finalizeFunction();
  515. // Processing steps done per block. E.g. emitting jump tables, stack
  516. // protectors etc. Returns true if no errors, false if there was a problem
  517. // that caused an abort.
  518. bool finalizeBasicBlock(const BasicBlock &BB, MachineBasicBlock &MBB);
  519. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  520. /// tail spliced into a stack protector check success bb.
  521. ///
  522. /// For a high level explanation of how this fits into the stack protector
  523. /// generation see the comment on the declaration of class
  524. /// StackProtectorDescriptor.
  525. ///
  526. /// \return true if there were no problems.
  527. bool emitSPDescriptorParent(StackProtectorDescriptor &SPD,
  528. MachineBasicBlock *ParentBB);
  529. /// Codegen the failure basic block for a stack protector check.
  530. ///
  531. /// A failure stack protector machine basic block consists simply of a call to
  532. /// __stack_chk_fail().
  533. ///
  534. /// For a high level explanation of how this fits into the stack protector
  535. /// generation see the comment on the declaration of class
  536. /// StackProtectorDescriptor.
  537. ///
  538. /// \return true if there were no problems.
  539. bool emitSPDescriptorFailure(StackProtectorDescriptor &SPD,
  540. MachineBasicBlock *FailureBB);
  541. /// Get the VRegs that represent \p Val.
  542. /// Non-aggregate types have just one corresponding VReg and the list can be
  543. /// used as a single "unsigned". Aggregates get flattened. If such VRegs do
  544. /// not exist, they are created.
  545. ArrayRef<Register> getOrCreateVRegs(const Value &Val);
  546. Register getOrCreateVReg(const Value &Val) {
  547. auto Regs = getOrCreateVRegs(Val);
  548. if (Regs.empty())
  549. return 0;
  550. assert(Regs.size() == 1 &&
  551. "attempt to get single VReg for aggregate or void");
  552. return Regs[0];
  553. }
  554. /// Allocate some vregs and offsets in the VMap. Then populate just the
  555. /// offsets while leaving the vregs empty.
  556. ValueToVRegInfo::VRegListT &allocateVRegs(const Value &Val);
  557. /// Get the frame index that represents \p Val.
  558. /// If such VReg does not exist, it is created.
  559. int getOrCreateFrameIndex(const AllocaInst &AI);
  560. /// Get the alignment of the given memory operation instruction. This will
  561. /// either be the explicitly specified value or the ABI-required alignment for
  562. /// the type being accessed (according to the Module's DataLayout).
  563. Align getMemOpAlign(const Instruction &I);
  564. /// Get the MachineBasicBlock that represents \p BB. Specifically, the block
  565. /// returned will be the head of the translated block (suitable for branch
  566. /// destinations).
  567. MachineBasicBlock &getMBB(const BasicBlock &BB);
  568. /// Record \p NewPred as a Machine predecessor to `Edge.second`, corresponding
  569. /// to `Edge.first` at the IR level. This is used when IRTranslation creates
  570. /// multiple MachineBasicBlocks for a given IR block and the CFG is no longer
  571. /// represented simply by the IR-level CFG.
  572. void addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred);
  573. /// Returns the Machine IR predecessors for the given IR CFG edge. Usually
  574. /// this is just the single MachineBasicBlock corresponding to the predecessor
  575. /// in the IR. More complex lowering can result in multiple MachineBasicBlocks
  576. /// preceding the original though (e.g. switch instructions).
  577. SmallVector<MachineBasicBlock *, 1> getMachinePredBBs(CFGEdge Edge) {
  578. auto RemappedEdge = MachinePreds.find(Edge);
  579. if (RemappedEdge != MachinePreds.end())
  580. return RemappedEdge->second;
  581. return SmallVector<MachineBasicBlock *, 4>(1, &getMBB(*Edge.first));
  582. }
  583. /// Return branch probability calculated by BranchProbabilityInfo for IR
  584. /// blocks.
  585. BranchProbability getEdgeProbability(const MachineBasicBlock *Src,
  586. const MachineBasicBlock *Dst) const;
  587. void addSuccessorWithProb(
  588. MachineBasicBlock *Src, MachineBasicBlock *Dst,
  589. BranchProbability Prob = BranchProbability::getUnknown());
  590. public:
  591. IRTranslator(CodeGenOpt::Level OptLevel = CodeGenOpt::None);
  592. StringRef getPassName() const override { return "IRTranslator"; }
  593. void getAnalysisUsage(AnalysisUsage &AU) const override;
  594. // Algo:
  595. // CallLowering = MF.subtarget.getCallLowering()
  596. // F = MF.getParent()
  597. // MIRBuilder.reset(MF)
  598. // getMBB(F.getEntryBB())
  599. // CallLowering->translateArguments(MIRBuilder, F, ValToVReg)
  600. // for each bb in F
  601. // getMBB(bb)
  602. // for each inst in bb
  603. // if (!translate(MIRBuilder, inst, ValToVReg, ConstantToSequence))
  604. // report_fatal_error("Don't know how to translate input");
  605. // finalize()
  606. bool runOnMachineFunction(MachineFunction &MF) override;
  607. };
  608. } // end namespace llvm
  609. #endif // LLVM_CODEGEN_GLOBALISEL_IRTRANSLATOR_H
  610. #ifdef __GNUC__
  611. #pragma GCC diagnostic pop
  612. #endif