ByteCodeEmitter.cpp 6.0 KB

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