1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #if V8_TARGET_ARCH_IA32
33 #include "deoptimizer.h"
34 #include "full-codegen.h"
35 #include "safepoint-table.h"
40 const int Deoptimizer::table_entry_size_ = 10;
43 int Deoptimizer::patch_size() {
44 return Assembler::kCallInstructionLength;
48 void Deoptimizer::EnsureRelocSpaceForLazyDeoptimization(Handle<Code> code) {
49 Isolate* isolate = code->GetIsolate();
50 HandleScope scope(isolate);
52 // Compute the size of relocation information needed for the code
53 // patching in Deoptimizer::DeoptimizeFunction.
54 int min_reloc_size = 0;
55 int prev_pc_offset = 0;
56 DeoptimizationInputData* deopt_data =
57 DeoptimizationInputData::cast(code->deoptimization_data());
58 for (int i = 0; i < deopt_data->DeoptCount(); i++) {
59 int pc_offset = deopt_data->Pc(i)->value();
60 if (pc_offset == -1) continue;
61 ASSERT_GE(pc_offset, prev_pc_offset);
62 int pc_delta = pc_offset - prev_pc_offset;
63 // We use RUNTIME_ENTRY reloc info which has a size of 2 bytes
64 // if encodable with small pc delta encoding and up to 6 bytes
66 if (pc_delta <= RelocInfo::kMaxSmallPCDelta) {
71 prev_pc_offset = pc_offset;
74 // If the relocation information is not big enough we create a new
75 // relocation info object that is padded with comments to make it
76 // big enough for lazy doptimization.
77 int reloc_length = code->relocation_info()->length();
78 if (min_reloc_size > reloc_length) {
79 int comment_reloc_size = RelocInfo::kMinRelocCommentSize;
81 int min_padding = min_reloc_size - reloc_length;
82 // Number of comments needed to take up at least that much space.
83 int additional_comments =
84 (min_padding + comment_reloc_size - 1) / comment_reloc_size;
85 // Actual padding size.
86 int padding = additional_comments * comment_reloc_size;
87 // Allocate new relocation info and copy old relocation to the end
88 // of the new relocation info array because relocation info is
89 // written and read backwards.
90 Factory* factory = isolate->factory();
91 Handle<ByteArray> new_reloc =
92 factory->NewByteArray(reloc_length + padding, TENURED);
93 OS::MemCopy(new_reloc->GetDataStartAddress() + padding,
94 code->relocation_info()->GetDataStartAddress(),
96 // Create a relocation writer to write the comments in the padding
97 // space. Use position 0 for everything to ensure short encoding.
98 RelocInfoWriter reloc_info_writer(
99 new_reloc->GetDataStartAddress() + padding, 0);
100 intptr_t comment_string
101 = reinterpret_cast<intptr_t>(RelocInfo::kFillerCommentString);
102 RelocInfo rinfo(0, RelocInfo::COMMENT, comment_string, NULL);
103 for (int i = 0; i < additional_comments; ++i) {
105 byte* pos_before = reloc_info_writer.pos();
107 reloc_info_writer.Write(&rinfo);
108 ASSERT(RelocInfo::kMinRelocCommentSize ==
109 pos_before - reloc_info_writer.pos());
111 // Replace relocation information on the code object.
112 code->set_relocation_info(*new_reloc);
117 void Deoptimizer::PatchCodeForDeoptimization(Isolate* isolate, Code* code) {
118 Address code_start_address = code->instruction_start();
120 if (FLAG_zap_code_space) {
121 // Fail hard and early if we enter this code object again.
122 byte* pointer = code->FindCodeAgeSequence();
123 if (pointer != NULL) {
124 pointer += kNoCodeAgeSequenceLength;
126 pointer = code->instruction_start();
128 CodePatcher patcher(pointer, 1);
129 patcher.masm()->int3();
131 DeoptimizationInputData* data =
132 DeoptimizationInputData::cast(code->deoptimization_data());
133 int osr_offset = data->OsrPcOffset()->value();
134 if (osr_offset > 0) {
135 CodePatcher osr_patcher(code->instruction_start() + osr_offset, 1);
136 osr_patcher.masm()->int3();
140 // We will overwrite the code's relocation info in-place. Relocation info
141 // is written backward. The relocation info is the payload of a byte
142 // array. Later on we will slide this to the start of the byte array and
143 // create a filler object in the remaining space.
144 ByteArray* reloc_info = code->relocation_info();
145 Address reloc_end_address = reloc_info->address() + reloc_info->Size();
146 RelocInfoWriter reloc_info_writer(reloc_end_address, code_start_address);
148 // Since the call is a relative encoding, write new
149 // reloc info. We do not need any of the existing reloc info because the
150 // existing code will not be used again (we zap it in debug builds).
152 // Emit call to lazy deoptimization at all lazy deopt points.
153 DeoptimizationInputData* deopt_data =
154 DeoptimizationInputData::cast(code->deoptimization_data());
155 SharedFunctionInfo* shared =
156 SharedFunctionInfo::cast(deopt_data->SharedFunctionInfo());
157 shared->EvictFromOptimizedCodeMap(code, "deoptimized code");
159 Address prev_call_address = NULL;
161 // For each LLazyBailout instruction insert a call to the corresponding
162 // deoptimization entry.
163 for (int i = 0; i < deopt_data->DeoptCount(); i++) {
164 if (deopt_data->Pc(i)->value() == -1) continue;
165 // Patch lazy deoptimization entry.
166 Address call_address = code_start_address + deopt_data->Pc(i)->value();
167 CodePatcher patcher(call_address, patch_size());
168 Address deopt_entry = GetDeoptimizationEntry(isolate, i, LAZY);
169 patcher.masm()->call(deopt_entry, RelocInfo::NONE32);
170 // We use RUNTIME_ENTRY for deoptimization bailouts.
171 RelocInfo rinfo(call_address + 1, // 1 after the call opcode.
172 RelocInfo::RUNTIME_ENTRY,
173 reinterpret_cast<intptr_t>(deopt_entry),
175 reloc_info_writer.Write(&rinfo);
176 ASSERT_GE(reloc_info_writer.pos(),
177 reloc_info->address() + ByteArray::kHeaderSize);
178 ASSERT(prev_call_address == NULL ||
179 call_address >= prev_call_address + patch_size());
180 ASSERT(call_address + patch_size() <= code->instruction_end());
182 prev_call_address = call_address;
186 // Move the relocation info to the beginning of the byte array.
187 int new_reloc_size = reloc_end_address - reloc_info_writer.pos();
189 code->relocation_start(), reloc_info_writer.pos(), new_reloc_size);
191 // The relocation info is in place, update the size.
192 reloc_info->set_length(new_reloc_size);
194 // Handle the junk part after the new relocation info. We will create
195 // a non-live object in the extra space at the end of the former reloc info.
196 Address junk_address = reloc_info->address() + reloc_info->Size();
197 ASSERT(junk_address <= reloc_end_address);
198 isolate->heap()->CreateFillerObjectAt(junk_address,
199 reloc_end_address - junk_address);
203 void Deoptimizer::FillInputFrame(Address tos, JavaScriptFrame* frame) {
204 // Set the register values. The values are not important as there are no
205 // callee saved registers in JavaScript frames, so all registers are
206 // spilled. Registers ebp and esp are set to the correct values though.
208 for (int i = 0; i < Register::kNumRegisters; i++) {
209 input_->SetRegister(i, i * 4);
211 input_->SetRegister(esp.code(), reinterpret_cast<intptr_t>(frame->sp()));
212 input_->SetRegister(ebp.code(), reinterpret_cast<intptr_t>(frame->fp()));
213 simd128_value_t zero = {{0.0, 0.0}};
214 for (int i = 0; i < DoubleRegister::NumAllocatableRegisters(); i++) {
215 input_->SetSIMD128Register(i, zero);
218 // Fill the frame content from the actual data on the frame.
219 for (unsigned i = 0; i < input_->GetFrameSize(); i += kPointerSize) {
220 input_->SetFrameSlot(i, Memory::uint32_at(tos + i));
225 void Deoptimizer::SetPlatformCompiledStubRegisters(
226 FrameDescription* output_frame, CodeStubInterfaceDescriptor* descriptor) {
228 reinterpret_cast<intptr_t>(descriptor->deoptimization_handler_);
229 int params = descriptor->GetHandlerParameterCount();
230 output_frame->SetRegister(eax.code(), params);
231 output_frame->SetRegister(ebx.code(), handler);
235 void Deoptimizer::CopySIMD128Registers(FrameDescription* output_frame) {
236 if (!CpuFeatures::IsSupported(SSE2)) return;
237 for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
238 simd128_value_t xmm_value = input_->GetSIMD128Register(i);
239 output_frame->SetSIMD128Register(i, xmm_value);
244 bool Deoptimizer::HasAlignmentPadding(JSFunction* function) {
245 int parameter_count = function->shared()->formal_parameter_count() + 1;
246 unsigned input_frame_size = input_->GetFrameSize();
247 unsigned alignment_state_offset =
248 input_frame_size - parameter_count * kPointerSize -
249 StandardFrameConstants::kFixedFrameSize -
251 ASSERT(JavaScriptFrameConstants::kDynamicAlignmentStateOffset ==
252 JavaScriptFrameConstants::kLocal0Offset);
253 int32_t alignment_state = input_->GetFrameSlot(alignment_state_offset);
254 return (alignment_state == kAlignmentPaddingPushed);
258 Code* Deoptimizer::NotifyStubFailureBuiltin() {
259 Builtins::Name name = CpuFeatures::IsSupported(SSE2) ?
260 Builtins::kNotifyStubFailureSaveDoubles : Builtins::kNotifyStubFailure;
261 return isolate_->builtins()->builtin(name);
267 void Deoptimizer::EntryGenerator::Generate() {
270 // Save all general purpose registers before messing with them.
271 const int kNumberOfRegisters = Register::kNumRegisters;
273 const int kXMMRegsSize = kSIMD128Size *
274 XMMRegister::kNumAllocatableRegisters;
275 __ sub(esp, Immediate(kXMMRegsSize));
276 if (CpuFeatures::IsSupported(SSE2)) {
277 CpuFeatureScope scope(masm(), SSE2);
278 for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
279 XMMRegister xmm_reg = XMMRegister::FromAllocationIndex(i);
280 int offset = i * kSIMD128Size;
281 __ movups(Operand(esp, offset), xmm_reg);
287 const int kSavedRegistersAreaSize = kNumberOfRegisters * kPointerSize +
290 // Get the bailout id from the stack.
291 __ mov(ebx, Operand(esp, kSavedRegistersAreaSize));
293 // Get the address of the location in the code object
294 // and compute the fp-to-sp delta in register edx.
295 __ mov(ecx, Operand(esp, kSavedRegistersAreaSize + 1 * kPointerSize));
296 __ lea(edx, Operand(esp, kSavedRegistersAreaSize + 2 * kPointerSize));
301 // Allocate a new deoptimizer object.
302 __ PrepareCallCFunction(6, eax);
303 __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
304 __ mov(Operand(esp, 0 * kPointerSize), eax); // Function.
305 __ mov(Operand(esp, 1 * kPointerSize), Immediate(type())); // Bailout type.
306 __ mov(Operand(esp, 2 * kPointerSize), ebx); // Bailout id.
307 __ mov(Operand(esp, 3 * kPointerSize), ecx); // Code address or 0.
308 __ mov(Operand(esp, 4 * kPointerSize), edx); // Fp-to-sp delta.
309 __ mov(Operand(esp, 5 * kPointerSize),
310 Immediate(ExternalReference::isolate_address(isolate())));
312 AllowExternalCallThatCantCauseGC scope(masm());
313 __ CallCFunction(ExternalReference::new_deoptimizer_function(isolate()), 6);
316 // Preserve deoptimizer object in register eax and get the input
317 // frame descriptor pointer.
318 __ mov(ebx, Operand(eax, Deoptimizer::input_offset()));
320 // Fill in the input registers.
321 for (int i = kNumberOfRegisters - 1; i >= 0; i--) {
322 int offset = (i * kPointerSize) + FrameDescription::registers_offset();
323 __ pop(Operand(ebx, offset));
326 int xmm_regs_offset = FrameDescription::simd128_registers_offset();
327 if (CpuFeatures::IsSupported(SSE2)) {
328 CpuFeatureScope scope(masm(), SSE2);
329 // Fill in the xmm input registers.
330 for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
331 int dst_offset = i * kSIMD128Size + xmm_regs_offset;
332 int src_offset = i * kSIMD128Size;
333 __ movups(xmm0, Operand(esp, src_offset));
334 __ movups(Operand(ebx, dst_offset), xmm0);
338 // Clear FPU all exceptions.
339 // TODO(ulan): Find out why the TOP register is not zero here in some cases,
340 // and check that the generated code never deoptimizes with unbalanced stack.
343 // Remove the bailout id, return address and the double registers.
344 __ add(esp, Immediate(kXMMRegsSize + 2 * kPointerSize));
346 // Compute a pointer to the unwinding limit in register ecx; that is
347 // the first stack slot not part of the input frame.
348 __ mov(ecx, Operand(ebx, FrameDescription::frame_size_offset()));
351 // Unwind the stack down to - but not including - the unwinding
352 // limit and copy the contents of the activation frame to the input
353 // frame description.
354 __ lea(edx, Operand(ebx, FrameDescription::frame_content_offset()));
355 Label pop_loop_header;
356 __ jmp(&pop_loop_header);
359 __ pop(Operand(edx, 0));
360 __ add(edx, Immediate(sizeof(uint32_t)));
361 __ bind(&pop_loop_header);
363 __ j(not_equal, &pop_loop);
365 // Compute the output frame in the deoptimizer.
367 __ PrepareCallCFunction(1, ebx);
368 __ mov(Operand(esp, 0 * kPointerSize), eax);
370 AllowExternalCallThatCantCauseGC scope(masm());
372 ExternalReference::compute_output_frames_function(isolate()), 1);
376 // If frame was dynamically aligned, pop padding.
378 __ cmp(Operand(eax, Deoptimizer::has_alignment_padding_offset()),
380 __ j(equal, &no_padding);
382 if (FLAG_debug_code) {
383 __ cmp(ecx, Immediate(kAlignmentZapValue));
384 __ Assert(equal, kAlignmentMarkerExpected);
386 __ bind(&no_padding);
388 // Replace the current frame with the output frames.
389 Label outer_push_loop, inner_push_loop,
390 outer_loop_header, inner_loop_header;
391 // Outer loop state: eax = current FrameDescription**, edx = one past the
392 // last FrameDescription**.
393 __ mov(edx, Operand(eax, Deoptimizer::output_count_offset()));
394 __ mov(eax, Operand(eax, Deoptimizer::output_offset()));
395 __ lea(edx, Operand(eax, edx, times_4, 0));
396 __ jmp(&outer_loop_header);
397 __ bind(&outer_push_loop);
398 // Inner loop state: ebx = current FrameDescription*, ecx = loop index.
399 __ mov(ebx, Operand(eax, 0));
400 __ mov(ecx, Operand(ebx, FrameDescription::frame_size_offset()));
401 __ jmp(&inner_loop_header);
402 __ bind(&inner_push_loop);
403 __ sub(ecx, Immediate(sizeof(uint32_t)));
404 __ push(Operand(ebx, ecx, times_1, FrameDescription::frame_content_offset()));
405 __ bind(&inner_loop_header);
407 __ j(not_zero, &inner_push_loop);
408 __ add(eax, Immediate(kPointerSize));
409 __ bind(&outer_loop_header);
411 __ j(below, &outer_push_loop);
413 // In case of a failed STUB, we have to restore the XMM registers.
414 if (CpuFeatures::IsSupported(SSE2)) {
415 CpuFeatureScope scope(masm(), SSE2);
416 for (int i = 0; i < XMMRegister::kNumAllocatableRegisters; ++i) {
417 XMMRegister xmm_reg = XMMRegister::FromAllocationIndex(i);
418 int src_offset = i * kSIMD128Size + xmm_regs_offset;
419 __ movups(xmm_reg, Operand(ebx, src_offset));
423 // Push state, pc, and continuation from the last output frame.
424 __ push(Operand(ebx, FrameDescription::state_offset()));
425 __ push(Operand(ebx, FrameDescription::pc_offset()));
426 __ push(Operand(ebx, FrameDescription::continuation_offset()));
429 // Push the registers from the last output frame.
430 for (int i = 0; i < kNumberOfRegisters; i++) {
431 int offset = (i * kPointerSize) + FrameDescription::registers_offset();
432 __ push(Operand(ebx, offset));
435 // Restore the registers from the stack.
438 // Return to the continuation point.
443 void Deoptimizer::TableEntryGenerator::GeneratePrologue() {
444 // Create a sequence of deoptimization entries.
446 for (int i = 0; i < count(); i++) {
447 int start = masm()->pc_offset();
451 ASSERT(masm()->pc_offset() - start == table_entry_size_);
457 void FrameDescription::SetCallerPc(unsigned offset, intptr_t value) {
458 SetFrameSlot(offset, value);
462 void FrameDescription::SetCallerFp(unsigned offset, intptr_t value) {
463 SetFrameSlot(offset, value);
467 void FrameDescription::SetCallerConstantPool(unsigned offset, intptr_t value) {
468 // No out-of-line constant pool support.
473 double FrameDescription::GetDoubleRegister(unsigned n) const {
474 ASSERT(n < ARRAY_SIZE(simd128_registers_));
475 return simd128_registers_[n].d[0];
479 void FrameDescription::SetDoubleRegister(unsigned n, double value) {
480 ASSERT(n < ARRAY_SIZE(simd128_registers_));
481 simd128_registers_[n].d[0] = value;
488 } } // namespace v8::internal
490 #endif // V8_TARGET_ARCH_IA32