ByteCodeEmitter.cpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. //===--- ByteCodeEmitter.cpp - Instruction emitter for the VM ---*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "ByteCodeEmitter.h"
  9. #include "Context.h"
  10. #include "Opcode.h"
  11. #include "Program.h"
  12. #include "clang/AST/DeclCXX.h"
  13. using namespace clang;
  14. using namespace clang::interp;
  15. using APSInt = llvm::APSInt;
  16. using Error = llvm::Error;
  17. Expected<Function *> ByteCodeEmitter::compileFunc(const FunctionDecl *F) {
  18. // Do not try to compile undefined functions.
  19. if (!F->isDefined(F) || (!F->hasBody() && F->willHaveBody()))
  20. return nullptr;
  21. // Set up argument indices.
  22. unsigned ParamOffset = 0;
  23. SmallVector<PrimType, 8> ParamTypes;
  24. llvm::DenseMap<unsigned, Function::ParamDescriptor> ParamDescriptors;
  25. // If the return is not a primitive, a pointer to the storage where the value
  26. // is initialized in is passed as the first argument.
  27. QualType Ty = F->getReturnType();
  28. if (!Ty->isVoidType() && !Ctx.classify(Ty)) {
  29. ParamTypes.push_back(PT_Ptr);
  30. ParamOffset += align(primSize(PT_Ptr));
  31. }
  32. // Assign descriptors to all parameters.
  33. // Composite objects are lowered to pointers.
  34. for (const ParmVarDecl *PD : F->parameters()) {
  35. PrimType Ty;
  36. if (llvm::Optional<PrimType> T = Ctx.classify(PD->getType())) {
  37. Ty = *T;
  38. } else {
  39. Ty = PT_Ptr;
  40. }
  41. Descriptor *Desc = P.createDescriptor(PD, Ty);
  42. ParamDescriptors.insert({ParamOffset, {Ty, Desc}});
  43. Params.insert({PD, ParamOffset});
  44. ParamOffset += align(primSize(Ty));
  45. ParamTypes.push_back(Ty);
  46. }
  47. // Create a handle over the emitted code.
  48. Function *Func = P.createFunction(F, ParamOffset, std::move(ParamTypes),
  49. std::move(ParamDescriptors));
  50. // Compile the function body.
  51. if (!F->isConstexpr() || !visitFunc(F)) {
  52. // Return a dummy function if compilation failed.
  53. if (BailLocation)
  54. return llvm::make_error<ByteCodeGenError>(*BailLocation);
  55. else
  56. return Func;
  57. } else {
  58. // Create scopes from descriptors.
  59. llvm::SmallVector<Scope, 2> Scopes;
  60. for (auto &DS : Descriptors) {
  61. Scopes.emplace_back(std::move(DS));
  62. }
  63. // Set the function's code.
  64. Func->setCode(NextLocalOffset, std::move(Code), std::move(SrcMap),
  65. std::move(Scopes));
  66. return Func;
  67. }
  68. }
  69. Scope::Local ByteCodeEmitter::createLocal(Descriptor *D) {
  70. NextLocalOffset += sizeof(Block);
  71. unsigned Location = NextLocalOffset;
  72. NextLocalOffset += align(D->getAllocSize());
  73. return {Location, D};
  74. }
  75. void ByteCodeEmitter::emitLabel(LabelTy Label) {
  76. const size_t Target = Code.size();
  77. LabelOffsets.insert({Label, Target});
  78. auto It = LabelRelocs.find(Label);
  79. if (It != LabelRelocs.end()) {
  80. for (unsigned Reloc : It->second) {
  81. using namespace llvm::support;
  82. /// Rewrite the operand of all jumps to this label.
  83. void *Location = Code.data() + Reloc - sizeof(int32_t);
  84. const int32_t Offset = Target - static_cast<int64_t>(Reloc);
  85. endian::write<int32_t, endianness::native, 1>(Location, Offset);
  86. }
  87. LabelRelocs.erase(It);
  88. }
  89. }
  90. int32_t ByteCodeEmitter::getOffset(LabelTy Label) {
  91. // Compute the PC offset which the jump is relative to.
  92. const int64_t Position = Code.size() + sizeof(Opcode) + sizeof(int32_t);
  93. // If target is known, compute jump offset.
  94. auto It = LabelOffsets.find(Label);
  95. if (It != LabelOffsets.end()) {
  96. return It->second - Position;
  97. }
  98. // Otherwise, record relocation and return dummy offset.
  99. LabelRelocs[Label].push_back(Position);
  100. return 0ull;
  101. }
  102. bool ByteCodeEmitter::bail(const SourceLocation &Loc) {
  103. if (!BailLocation)
  104. BailLocation = Loc;
  105. return false;
  106. }
  107. template <typename... Tys>
  108. bool ByteCodeEmitter::emitOp(Opcode Op, const Tys &... Args, const SourceInfo &SI) {
  109. bool Success = true;
  110. /// Helper to write bytecode and bail out if 32-bit offsets become invalid.
  111. auto emit = [this, &Success](const char *Data, size_t Size) {
  112. if (Code.size() + Size > std::numeric_limits<unsigned>::max()) {
  113. Success = false;
  114. return;
  115. }
  116. Code.insert(Code.end(), Data, Data + Size);
  117. };
  118. /// The opcode is followed by arguments. The source info is
  119. /// attached to the address after the opcode.
  120. emit(reinterpret_cast<const char *>(&Op), sizeof(Opcode));
  121. if (SI)
  122. SrcMap.emplace_back(Code.size(), SI);
  123. /// The initializer list forces the expression to be evaluated
  124. /// for each argument in the variadic template, in order.
  125. (void)std::initializer_list<int>{
  126. (emit(reinterpret_cast<const char *>(&Args), sizeof(Args)), 0)...};
  127. return Success;
  128. }
  129. bool ByteCodeEmitter::jumpTrue(const LabelTy &Label) {
  130. return emitJt(getOffset(Label), SourceInfo{});
  131. }
  132. bool ByteCodeEmitter::jumpFalse(const LabelTy &Label) {
  133. return emitJf(getOffset(Label), SourceInfo{});
  134. }
  135. bool ByteCodeEmitter::jump(const LabelTy &Label) {
  136. return emitJmp(getOffset(Label), SourceInfo{});
  137. }
  138. bool ByteCodeEmitter::fallthrough(const LabelTy &Label) {
  139. emitLabel(Label);
  140. return true;
  141. }
  142. //===----------------------------------------------------------------------===//
  143. // Opcode emitters
  144. //===----------------------------------------------------------------------===//
  145. #define GET_LINK_IMPL
  146. #include "Opcodes.inc"
  147. #undef GET_LINK_IMPL