code-generator.h 13.5 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_COMPILER_CODE_GENERATOR_H_
#define V8_COMPILER_CODE_GENERATOR_H_

8
#include "src/base/optional.h"
9 10
#include "src/compiler/gap-resolver.h"
#include "src/compiler/instruction.h"
11
#include "src/compiler/osr.h"
12
#include "src/compiler/unwinding-info-writer.h"
13 14 15
#include "src/deoptimizer.h"
#include "src/macro-assembler.h"
#include "src/safepoint-table.h"
16
#include "src/source-position-table.h"
17
#include "src/trap-handler/trap-handler.h"
18 19 20

namespace v8 {
namespace internal {
21 22 23

class CompilationInfo;

24 25
namespace compiler {

26
// Forward declarations.
27
class DeoptimizationExit;
28
class FrameAccessState;
29
class Linkage;
30
class OutOfLineCode;
31

32 33 34 35 36 37 38 39
struct BranchInfo {
  FlagsCondition condition;
  Label* true_label;
  Label* false_label;
  bool fallthru;
};


40 41 42 43 44 45 46 47 48 49 50 51 52
class InstructionOperandIterator {
 public:
  InstructionOperandIterator(Instruction* instr, size_t pos)
      : instr_(instr), pos_(pos) {}

  Instruction* instruction() const { return instr_; }
  InstructionOperand* Advance() { return instr_->InputAt(pos_++); }

 private:
  Instruction* instr_;
  size_t pos_;
};

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
// Either a non-null Handle<Object> or a double.
class DeoptimizationLiteral {
 public:
  DeoptimizationLiteral() : object_(), number_(0) {}
  explicit DeoptimizationLiteral(Handle<Object> object)
      : object_(object), number_(0) {
    DCHECK(!object_.is_null());
  }
  explicit DeoptimizationLiteral(double number) : object_(), number_(number) {}

  Handle<Object> object() const { return object_; }

  bool operator==(const DeoptimizationLiteral& other) const {
    return object_.equals(other.object_) &&
           bit_cast<uint64_t>(number_) == bit_cast<uint64_t>(other.number_);
  }

  Handle<Object> Reify(Isolate* isolate) const {
    return object_.is_null() ? isolate->factory()->NewNumber(number_) : object_;
  }

 private:
  Handle<Object> object_;
  double number_;
};
78

79
// Generates native code for a sequence of instructions.
80
class CodeGenerator final : public GapResolver::Assembler {
81
 public:
82
  explicit CodeGenerator(Zone* codegen_zone, Frame* frame, Linkage* linkage,
83
                         InstructionSequence* code, CompilationInfo* info,
84
                         base::Optional<OsrHelper> osr_helper,
85 86
                         int start_source_position,
                         JumpOptimizationInfo* jump_opt);
87

88 89 90
  // Generate native code. After calling AssembleCode, call FinalizeCode to
  // produce the actual code object. If an error occurs during either phase,
  // FinalizeCode returns a null handle.
91
  void AssembleCode();  // Does not need to run on main thread.
92
  Handle<Code> FinalizeCode();
93 94

  InstructionSequence* code() const { return code_; }
95
  FrameAccessState* frame_access_state() const { return frame_access_state_; }
96
  const Frame* frame() const { return frame_access_state_->frame(); }
97
  Isolate* isolate() const;
98
  Linkage* linkage() const { return linkage_; }
99

100
  Label* GetLabel(RpoNumber rpo) { return &labels_[rpo.ToSize()]; }
101

102 103 104
  SourcePosition start_source_position() const {
    return start_source_position_;
  }
105

106
  void AssembleSourcePosition(Instruction* instr);
107 108
  void AssembleSourcePosition(SourcePosition source_position);

109 110 111 112
  // Record a safepoint with the given pointer map.
  void RecordSafepoint(ReferenceMap* references, Safepoint::Kind kind,
                       int arguments, Safepoint::DeoptMode deopt_mode);

113
  Zone* zone() const { return zone_; }
114

115
 private:
116
  TurboAssembler* tasm() { return &tasm_; }
117 118
  GapResolver* resolver() { return &resolver_; }
  SafepointTableBuilder* safepoints() { return &safepoints_; }
119
  CompilationInfo* info() const { return info_; }
120
  OsrHelper* osr_helper() { return &(*osr_helper_); }
121

122 123 124
  // Create the FrameAccessState object. The Frame is immutable from here on.
  void CreateFrameAccessState(Frame* frame);

125 126 127
  // Architecture - specific frame finalization.
  void FinishFrame(Frame* frame);

128 129
  // Checks if {block} will appear directly after {current_block_} when
  // assembling code, in which case, a fall-through can be used.
130
  bool IsNextInAssemblyOrder(RpoNumber block) const;
131

132 133 134 135 136 137
  // Check if a heap object can be materialized by loading from a heap root,
  // which is cheaper on some platforms than materializing the actual heap
  // object constant.
  bool IsMaterializableFromRoot(Handle<HeapObject> object,
                                Heap::RootListIndex* index_return);

138 139
  enum CodeGenResult { kSuccess, kTooManyDeoptimizationBailouts };

140
  // Assemble instructions for the specified block.
141
  CodeGenResult AssembleBlock(const InstructionBlock* block);
142

143
  // Assemble code for the specified instruction.
144 145
  CodeGenResult AssembleInstruction(Instruction* instr,
                                    const InstructionBlock* block);
146
  void AssembleGaps(Instruction* instr);
147

148 149 150 151 152
  // Returns true if a instruction is a tail call that needs to adjust the stack
  // pointer before execution. The stack slot index to the empty slot above the
  // adjusted stack pointer is returned in |slot|.
  bool GetSlotAboveSPBeforeTailCall(Instruction* instr, int* slot);

153 154
  CodeGenResult AssembleDeoptimizerCall(int deoptimization_id,
                                        SourcePosition pos);
155

156 157 158 159
  // ===========================================================================
  // ============= Architecture-specific code generation methods. ==============
  // ===========================================================================

160
  CodeGenResult AssembleArchInstruction(Instruction* instr);
161
  void AssembleArchJump(RpoNumber target);
162
  void AssembleArchBranch(Instruction* instr, BranchInfo* branch);
163
  void AssembleArchBoolean(Instruction* instr, FlagsCondition condition);
164
  void AssembleArchTrap(Instruction* instr, FlagsCondition condition);
165 166
  void AssembleArchLookupSwitch(Instruction* instr);
  void AssembleArchTableSwitch(Instruction* instr);
167

168 169 170 171 172 173
  // When entering a code that is marked for deoptimization, rather continuing
  // with its execution, we jump to a lazy compiled code. We need to do this
  // because this code has already been deoptimized and needs to be unlinked
  // from the JS functions referring it.
  void BailoutIfDeoptimized();

174 175
  // Generates an architecture-specific, descriptor-specific prologue
  // to set up a stack frame.
176
  void AssembleConstructFrame();
177

178 179
  // Generates an architecture-specific, descriptor-specific return sequence
  // to tear down a stack frame.
180
  void AssembleReturn(InstructionOperand* pop);
181

182 183
  void AssembleDeconstructFrame();

184
  // Generates code to manipulate the stack in preparation for a tail call.
185
  void AssemblePrepareTailCall();
186

187 188 189 190
  // Generates code to pop current frame if it is an arguments adaptor frame.
  void AssemblePopArgumentsAdaptorFrame(Register args_reg, Register scratch1,
                                        Register scratch2, Register scratch3);

191 192
  enum PushTypeFlag {
    kImmediatePush = 0x1,
193 194 195
    kRegisterPush = 0x2,
    kStackSlotPush = 0x4,
    kScalarPush = kRegisterPush | kStackSlotPush
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
  };

  typedef base::Flags<PushTypeFlag> PushTypeFlags;

  static bool IsValidPush(InstructionOperand source, PushTypeFlags push_type);

  // Generate a list moves from an instruction that are candidates to be turned
  // into push instructions on platforms that support them. In general, the list
  // of push candidates are moves to a set of contiguous destination
  // InstructionOperand locations on the stack that don't clobber values that
  // are needed for resolve the gap or use values generated by the gap,
  // i.e. moves that can be hoisted together before the actual gap and assembled
  // together.
  static void GetPushCompatibleMoves(Instruction* instr,
                                     PushTypeFlags push_type,
                                     ZoneVector<MoveOperands*>* pushes);

  // Called before a tail call |instr|'s gap moves are assembled and allows
  // gap-specific pre-processing, e.g. adjustment of the sp for tail calls that
  // need it before gap moves or conversion of certain gap moves into pushes.
  void AssembleTailCallBeforeGap(Instruction* instr,
                                 int first_unused_stack_slot);
  // Called after a tail call |instr|'s gap moves are assembled and allows
  // gap-specific post-processing, e.g. adjustment of the sp for tail calls that
  // need it after gap moves.
  void AssembleTailCallAfterGap(Instruction* instr,
                                int first_unused_stack_slot);

224 225
  void FinishCode();

226 227 228 229 230
  // ===========================================================================
  // ============== Architecture-specific gap resolver methods. ================
  // ===========================================================================

  // Interface used by the gap resolver to emit moves and swaps.
231
  void AssembleMove(InstructionOperand* source,
232
                    InstructionOperand* destination) final;
233
  void AssembleSwap(InstructionOperand* source,
234
                    InstructionOperand* destination) final;
235

236 237 238 239 240 241 242 243 244 245 246 247
  // ===========================================================================
  // =================== Jump table construction methods. ======================
  // ===========================================================================

  class JumpTable;
  // Adds a jump table that is emitted after the actual code.  Returns label
  // pointing to the beginning of the table.  {targets} is assumed to be static
  // or zone allocated.
  Label* AddJumpTable(Label** targets, size_t target_count);
  // Emits a jump table.
  void AssembleJumpTable(Label** targets, size_t target_count);

248
  // ===========================================================================
249 250 251 252
  // ================== Deoptimization table construction. =====================
  // ===========================================================================

  void RecordCallPosition(Instruction* instr);
253
  void PopulateDeoptimizationData(Handle<Code> code);
254
  int DefineDeoptimizationLiteral(DeoptimizationLiteral literal);
255 256
  DeoptimizationEntry const& GetDeoptimizationEntry(Instruction* instr,
                                                    size_t frame_state_offset);
257
  DeoptimizeKind GetDeoptimizationKind(int deoptimization_id) const;
258
  DeoptimizeReason GetDeoptimizationReason(int deoptimization_id) const;
259
  int BuildTranslation(Instruction* instr, int pc_offset,
260
                       size_t frame_state_offset,
261
                       OutputFrameStateCombine state_combine);
262
  void BuildTranslationForFrameStateDescriptor(
263 264 265
      FrameStateDescriptor* descriptor, InstructionOperandIterator* iter,
      Translation* translation, OutputFrameStateCombine state_combine);
  void TranslateStateValueDescriptor(StateValueDescriptor* desc,
266
                                     StateValueList* nested,
267 268 269 270 271 272
                                     Translation* translation,
                                     InstructionOperandIterator* iter);
  void TranslateFrameStateDescriptorOperands(FrameStateDescriptor* desc,
                                             InstructionOperandIterator* iter,
                                             OutputFrameStateCombine combine,
                                             Translation* translation);
273
  void AddTranslationForOperand(Translation* translation, Instruction* instr,
274
                                InstructionOperand* op, MachineType type);
275
  void MarkLazyDeoptSite();
276

277 278 279
  DeoptimizationExit* AddDeoptimizationExit(Instruction* instr,
                                            size_t frame_state_offset);

280
  // ===========================================================================
281

282
  class DeoptimizationState final : public ZoneObject {
283
   public:
284
    DeoptimizationState(BailoutId bailout_id, int translation_id, int pc_offset,
285
                        DeoptimizeKind kind, DeoptimizeReason reason)
286 287 288
        : bailout_id_(bailout_id),
          translation_id_(translation_id),
          pc_offset_(pc_offset),
289
          kind_(kind),
290
          reason_(reason) {}
291

292 293
    BailoutId bailout_id() const { return bailout_id_; }
    int translation_id() const { return translation_id_; }
294
    int pc_offset() const { return pc_offset_; }
295
    DeoptimizeKind kind() const { return kind_; }
296
    DeoptimizeReason reason() const { return reason_; }
297 298 299 300

   private:
    BailoutId bailout_id_;
    int translation_id_;
301
    int pc_offset_;
302
    DeoptimizeKind kind_;
303
    DeoptimizeReason reason_;
304 305
  };

306 307 308 309 310
  struct HandlerInfo {
    Label* handler;
    int pc_offset;
  };

311
  friend class OutOfLineCode;
312
  friend class CodeGeneratorTester;
313

314
  Zone* zone_;
315
  FrameAccessState* frame_access_state_;
316 317
  Linkage* const linkage_;
  InstructionSequence* const code_;
318
  UnwindingInfoWriter unwinding_info_writer_;
319
  CompilationInfo* const info_;
320
  Label* const labels_;
321
  Label return_label_;
322
  RpoNumber current_block_;
323
  SourcePosition start_source_position_;
324
  SourcePosition current_source_position_;
325
  TurboAssembler tasm_;
326 327
  GapResolver resolver_;
  SafepointTableBuilder safepoints_;
328
  ZoneVector<HandlerInfo> handlers_;
329
  ZoneDeque<DeoptimizationExit*> deoptimization_exits_;
330
  ZoneDeque<DeoptimizationState*> deoptimization_states_;
331
  ZoneDeque<DeoptimizationLiteral> deoptimization_literals_;
332
  size_t inlined_function_count_;
333
  TranslationBuffer translations_;
334
  int last_lazy_deopt_pc_;
335
  bool caller_registers_saved_;
336
  JumpTable* jump_tables_;
337
  OutOfLineCode* ools_;
338
  base::Optional<OsrHelper> osr_helper_;
339
  int osr_pc_offset_;
340
  int optimized_out_literal_id_;
341
  SourcePositionTableBuilder source_position_table_builder_;
342
  CodeGenResult result_;
343 344 345 346 347 348 349
};

}  // namespace compiler
}  // namespace internal
}  // namespace v8

#endif  // V8_COMPILER_CODE_GENERATOR_H