ReplaceConstant.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //===- ReplaceConstant.cpp - Replace LLVM constant expression--------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements a utility function for replacing LLVM constant
  10. // expressions by instructions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/ReplaceConstant.h"
  14. #include "llvm/IR/IRBuilder.h"
  15. #include "llvm/IR/Instructions.h"
  16. #include "llvm/IR/NoFolder.h"
  17. namespace llvm {
  18. // Replace a constant expression by instructions with equivalent operations at
  19. // a specified location.
  20. Instruction *createReplacementInstr(ConstantExpr *CE, Instruction *Instr) {
  21. IRBuilder<NoFolder> Builder(Instr);
  22. unsigned OpCode = CE->getOpcode();
  23. switch (OpCode) {
  24. case Instruction::GetElementPtr: {
  25. SmallVector<Value *, 4> CEOpVec(CE->operands());
  26. ArrayRef<Value *> CEOps(CEOpVec);
  27. return dyn_cast<Instruction>(
  28. Builder.CreateInBoundsGEP(cast<GEPOperator>(CE)->getSourceElementType(),
  29. CEOps[0], CEOps.slice(1)));
  30. }
  31. case Instruction::Add:
  32. case Instruction::Sub:
  33. case Instruction::Mul:
  34. case Instruction::UDiv:
  35. case Instruction::SDiv:
  36. case Instruction::FDiv:
  37. case Instruction::URem:
  38. case Instruction::SRem:
  39. case Instruction::FRem:
  40. case Instruction::Shl:
  41. case Instruction::LShr:
  42. case Instruction::AShr:
  43. case Instruction::And:
  44. case Instruction::Or:
  45. case Instruction::Xor:
  46. return dyn_cast<Instruction>(
  47. Builder.CreateBinOp((Instruction::BinaryOps)OpCode, CE->getOperand(0),
  48. CE->getOperand(1), CE->getName()));
  49. case Instruction::Trunc:
  50. case Instruction::ZExt:
  51. case Instruction::SExt:
  52. case Instruction::FPToUI:
  53. case Instruction::FPToSI:
  54. case Instruction::UIToFP:
  55. case Instruction::SIToFP:
  56. case Instruction::FPTrunc:
  57. case Instruction::FPExt:
  58. case Instruction::PtrToInt:
  59. case Instruction::IntToPtr:
  60. case Instruction::BitCast:
  61. return dyn_cast<Instruction>(
  62. Builder.CreateCast((Instruction::CastOps)OpCode, CE->getOperand(0),
  63. CE->getType(), CE->getName()));
  64. default:
  65. llvm_unreachable("Unhandled constant expression!\n");
  66. }
  67. }
  68. } // namespace llvm