Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / v8 / src / lithium.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "src/v8.h"
6
7 #include "src/lithium.h"
8 #include "src/scopes.h"
9 #include "src/serialize.h"
10
11 #if V8_TARGET_ARCH_IA32
12 #include "src/ia32/lithium-ia32.h"  // NOLINT
13 #include "src/ia32/lithium-codegen-ia32.h"  // NOLINT
14 #elif V8_TARGET_ARCH_X64
15 #include "src/x64/lithium-x64.h"  // NOLINT
16 #include "src/x64/lithium-codegen-x64.h"  // NOLINT
17 #elif V8_TARGET_ARCH_ARM
18 #include "src/arm/lithium-arm.h"  // NOLINT
19 #include "src/arm/lithium-codegen-arm.h"  // NOLINT
20 #elif V8_TARGET_ARCH_MIPS
21 #include "src/mips/lithium-mips.h"  // NOLINT
22 #include "src/mips/lithium-codegen-mips.h"  // NOLINT
23 #elif V8_TARGET_ARCH_ARM64
24 #include "src/arm64/lithium-arm64.h"  // NOLINT
25 #include "src/arm64/lithium-codegen-arm64.h"  // NOLINT
26 #elif V8_TARGET_ARCH_MIPS64
27 #include "src/mips64/lithium-mips64.h"  // NOLINT
28 #include "src/mips64/lithium-codegen-mips64.h"  // NOLINT
29 #elif V8_TARGET_ARCH_X87
30 #include "src/x87/lithium-x87.h"  // NOLINT
31 #include "src/x87/lithium-codegen-x87.h"  // NOLINT
32 #else
33 #error "Unknown architecture."
34 #endif
35
36 namespace v8 {
37 namespace internal {
38
39
40 void LOperand::PrintTo(StringStream* stream) {
41   LUnallocated* unalloc = NULL;
42   switch (kind()) {
43     case INVALID:
44       stream->Add("(0)");
45       break;
46     case UNALLOCATED:
47       unalloc = LUnallocated::cast(this);
48       stream->Add("v%d", unalloc->virtual_register());
49       if (unalloc->basic_policy() == LUnallocated::FIXED_SLOT) {
50         stream->Add("(=%dS)", unalloc->fixed_slot_index());
51         break;
52       }
53       switch (unalloc->extended_policy()) {
54         case LUnallocated::NONE:
55           break;
56         case LUnallocated::FIXED_REGISTER: {
57           int reg_index = unalloc->fixed_register_index();
58           if (reg_index < 0 ||
59               reg_index >= Register::kMaxNumAllocatableRegisters) {
60             stream->Add("(=invalid_reg#%d)", reg_index);
61           } else {
62             const char* register_name =
63                 Register::AllocationIndexToString(reg_index);
64             stream->Add("(=%s)", register_name);
65           }
66           break;
67         }
68         case LUnallocated::FIXED_DOUBLE_REGISTER: {
69           int reg_index = unalloc->fixed_register_index();
70           if (reg_index < 0 ||
71               reg_index >= DoubleRegister::kMaxNumAllocatableRegisters) {
72             stream->Add("(=invalid_double_reg#%d)", reg_index);
73           } else {
74             const char* double_register_name =
75                 DoubleRegister::AllocationIndexToString(reg_index);
76             stream->Add("(=%s)", double_register_name);
77           }
78           break;
79         }
80         case LUnallocated::MUST_HAVE_REGISTER:
81           stream->Add("(R)");
82           break;
83         case LUnallocated::MUST_HAVE_DOUBLE_REGISTER:
84           stream->Add("(D)");
85           break;
86         case LUnallocated::WRITABLE_REGISTER:
87           stream->Add("(WR)");
88           break;
89         case LUnallocated::SAME_AS_FIRST_INPUT:
90           stream->Add("(1)");
91           break;
92         case LUnallocated::ANY:
93           stream->Add("(-)");
94           break;
95       }
96       break;
97     case CONSTANT_OPERAND:
98       stream->Add("[constant:%d]", index());
99       break;
100     case STACK_SLOT:
101       stream->Add("[stack:%d]", index());
102       break;
103     case DOUBLE_STACK_SLOT:
104       stream->Add("[double_stack:%d]", index());
105       break;
106     case REGISTER: {
107       int reg_index = index();
108       if (reg_index < 0 || reg_index >= Register::kMaxNumAllocatableRegisters) {
109         stream->Add("(=invalid_reg#%d|R)", reg_index);
110       } else {
111         stream->Add("[%s|R]", Register::AllocationIndexToString(reg_index));
112       }
113       break;
114     }
115     case DOUBLE_REGISTER: {
116       int reg_index = index();
117       if (reg_index < 0 ||
118           reg_index >= DoubleRegister::kMaxNumAllocatableRegisters) {
119         stream->Add("(=invalid_double_reg#%d|R)", reg_index);
120       } else {
121         stream->Add("[%s|R]",
122                     DoubleRegister::AllocationIndexToString(reg_index));
123       }
124       break;
125     }
126   }
127 }
128
129
130 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
131 LSubKindOperand<kOperandKind, kNumCachedOperands>*
132 LSubKindOperand<kOperandKind, kNumCachedOperands>::cache = NULL;
133
134
135 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
136 void LSubKindOperand<kOperandKind, kNumCachedOperands>::SetUpCache() {
137   if (cache) return;
138   cache = new LSubKindOperand[kNumCachedOperands];
139   for (int i = 0; i < kNumCachedOperands; i++) {
140     cache[i].ConvertTo(kOperandKind, i);
141   }
142 }
143
144
145 template<LOperand::Kind kOperandKind, int kNumCachedOperands>
146 void LSubKindOperand<kOperandKind, kNumCachedOperands>::TearDownCache() {
147   delete[] cache;
148 }
149
150
151 void LOperand::SetUpCaches() {
152 #define LITHIUM_OPERAND_SETUP(name, type, number) L##name::SetUpCache();
153   LITHIUM_OPERAND_LIST(LITHIUM_OPERAND_SETUP)
154 #undef LITHIUM_OPERAND_SETUP
155 }
156
157
158 void LOperand::TearDownCaches() {
159 #define LITHIUM_OPERAND_TEARDOWN(name, type, number) L##name::TearDownCache();
160   LITHIUM_OPERAND_LIST(LITHIUM_OPERAND_TEARDOWN)
161 #undef LITHIUM_OPERAND_TEARDOWN
162 }
163
164
165 bool LParallelMove::IsRedundant() const {
166   for (int i = 0; i < move_operands_.length(); ++i) {
167     if (!move_operands_[i].IsRedundant()) return false;
168   }
169   return true;
170 }
171
172
173 void LParallelMove::PrintDataTo(StringStream* stream) const {
174   bool first = true;
175   for (int i = 0; i < move_operands_.length(); ++i) {
176     if (!move_operands_[i].IsEliminated()) {
177       LOperand* source = move_operands_[i].source();
178       LOperand* destination = move_operands_[i].destination();
179       if (!first) stream->Add(" ");
180       first = false;
181       if (source->Equals(destination)) {
182         destination->PrintTo(stream);
183       } else {
184         destination->PrintTo(stream);
185         stream->Add(" = ");
186         source->PrintTo(stream);
187       }
188       stream->Add(";");
189     }
190   }
191 }
192
193
194 void LEnvironment::PrintTo(StringStream* stream) {
195   stream->Add("[id=%d|", ast_id().ToInt());
196   if (deoptimization_index() != Safepoint::kNoDeoptimizationIndex) {
197     stream->Add("deopt_id=%d|", deoptimization_index());
198   }
199   stream->Add("parameters=%d|", parameter_count());
200   stream->Add("arguments_stack_height=%d|", arguments_stack_height());
201   for (int i = 0; i < values_.length(); ++i) {
202     if (i != 0) stream->Add(";");
203     if (values_[i] == NULL) {
204       stream->Add("[hole]");
205     } else {
206       values_[i]->PrintTo(stream);
207     }
208   }
209   stream->Add("]");
210 }
211
212
213 void LPointerMap::RecordPointer(LOperand* op, Zone* zone) {
214   // Do not record arguments as pointers.
215   if (op->IsStackSlot() && op->index() < 0) return;
216   DCHECK(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
217   pointer_operands_.Add(op, zone);
218 }
219
220
221 void LPointerMap::RemovePointer(LOperand* op) {
222   // Do not record arguments as pointers.
223   if (op->IsStackSlot() && op->index() < 0) return;
224   DCHECK(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
225   for (int i = 0; i < pointer_operands_.length(); ++i) {
226     if (pointer_operands_[i]->Equals(op)) {
227       pointer_operands_.Remove(i);
228       --i;
229     }
230   }
231 }
232
233
234 void LPointerMap::RecordUntagged(LOperand* op, Zone* zone) {
235   // Do not record arguments as pointers.
236   if (op->IsStackSlot() && op->index() < 0) return;
237   DCHECK(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
238   untagged_operands_.Add(op, zone);
239 }
240
241
242 void LPointerMap::PrintTo(StringStream* stream) {
243   stream->Add("{");
244   for (int i = 0; i < pointer_operands_.length(); ++i) {
245     if (i != 0) stream->Add(";");
246     pointer_operands_[i]->PrintTo(stream);
247   }
248   stream->Add("}");
249 }
250
251
252 int StackSlotOffset(int index) {
253   if (index >= 0) {
254     // Local or spill slot. Skip the frame pointer, function, and
255     // context in the fixed part of the frame.
256     return -(index + 1) * kPointerSize -
257         StandardFrameConstants::kFixedFrameSizeFromFp;
258   } else {
259     // Incoming parameter. Skip the return address.
260     return -(index + 1) * kPointerSize + kFPOnStackSize + kPCOnStackSize;
261   }
262 }
263
264
265 LChunk::LChunk(CompilationInfo* info, HGraph* graph)
266     : spill_slot_count_(0),
267       info_(info),
268       graph_(graph),
269       instructions_(32, info->zone()),
270       pointer_maps_(8, info->zone()),
271       inlined_closures_(1, info->zone()),
272       deprecation_dependencies_(MapLess(), MapAllocator(info->zone())),
273       stability_dependencies_(MapLess(), MapAllocator(info->zone())) {}
274
275
276 LLabel* LChunk::GetLabel(int block_id) const {
277   HBasicBlock* block = graph_->blocks()->at(block_id);
278   int first_instruction = block->first_instruction_index();
279   return LLabel::cast(instructions_[first_instruction]);
280 }
281
282
283 int LChunk::LookupDestination(int block_id) const {
284   LLabel* cur = GetLabel(block_id);
285   while (cur->replacement() != NULL) {
286     cur = cur->replacement();
287   }
288   return cur->block_id();
289 }
290
291 Label* LChunk::GetAssemblyLabel(int block_id) const {
292   LLabel* label = GetLabel(block_id);
293   DCHECK(!label->HasReplacement());
294   return label->label();
295 }
296
297
298 void LChunk::MarkEmptyBlocks() {
299   LPhase phase("L_Mark empty blocks", this);
300   for (int i = 0; i < graph()->blocks()->length(); ++i) {
301     HBasicBlock* block = graph()->blocks()->at(i);
302     int first = block->first_instruction_index();
303     int last = block->last_instruction_index();
304     LInstruction* first_instr = instructions()->at(first);
305     LInstruction* last_instr = instructions()->at(last);
306
307     LLabel* label = LLabel::cast(first_instr);
308     if (last_instr->IsGoto()) {
309       LGoto* goto_instr = LGoto::cast(last_instr);
310       if (label->IsRedundant() &&
311           !label->is_loop_header()) {
312         bool can_eliminate = true;
313         for (int i = first + 1; i < last && can_eliminate; ++i) {
314           LInstruction* cur = instructions()->at(i);
315           if (cur->IsGap()) {
316             LGap* gap = LGap::cast(cur);
317             if (!gap->IsRedundant()) {
318               can_eliminate = false;
319             }
320           } else {
321             can_eliminate = false;
322           }
323         }
324         if (can_eliminate) {
325           label->set_replacement(GetLabel(goto_instr->block_id()));
326         }
327       }
328     }
329   }
330 }
331
332
333 void LChunk::AddInstruction(LInstruction* instr, HBasicBlock* block) {
334   LInstructionGap* gap = new (zone()) LInstructionGap(block);
335   gap->set_hydrogen_value(instr->hydrogen_value());
336   int index = -1;
337   if (instr->IsControl()) {
338     instructions_.Add(gap, zone());
339     index = instructions_.length();
340     instructions_.Add(instr, zone());
341   } else {
342     index = instructions_.length();
343     instructions_.Add(instr, zone());
344     instructions_.Add(gap, zone());
345   }
346   if (instr->HasPointerMap()) {
347     pointer_maps_.Add(instr->pointer_map(), zone());
348     instr->pointer_map()->set_lithium_position(index);
349   }
350 }
351
352
353 LConstantOperand* LChunk::DefineConstantOperand(HConstant* constant) {
354   return LConstantOperand::Create(constant->id(), zone());
355 }
356
357
358 int LChunk::GetParameterStackSlot(int index) const {
359   // The receiver is at index 0, the first parameter at index 1, so we
360   // shift all parameter indexes down by the number of parameters, and
361   // make sure they end up negative so they are distinguishable from
362   // spill slots.
363   int result = index - info()->num_parameters() - 1;
364
365   DCHECK(result < 0);
366   return result;
367 }
368
369
370 // A parameter relative to ebp in the arguments stub.
371 int LChunk::ParameterAt(int index) {
372   DCHECK(-1 <= index);  // -1 is the receiver.
373   return (1 + info()->scope()->num_parameters() - index) *
374       kPointerSize;
375 }
376
377
378 LGap* LChunk::GetGapAt(int index) const {
379   return LGap::cast(instructions_[index]);
380 }
381
382
383 bool LChunk::IsGapAt(int index) const {
384   return instructions_[index]->IsGap();
385 }
386
387
388 int LChunk::NearestGapPos(int index) const {
389   while (!IsGapAt(index)) index--;
390   return index;
391 }
392
393
394 void LChunk::AddGapMove(int index, LOperand* from, LOperand* to) {
395   GetGapAt(index)->GetOrCreateParallelMove(
396       LGap::START, zone())->AddMove(from, to, zone());
397 }
398
399
400 HConstant* LChunk::LookupConstant(LConstantOperand* operand) const {
401   return HConstant::cast(graph_->LookupValue(operand->index()));
402 }
403
404
405 Representation LChunk::LookupLiteralRepresentation(
406     LConstantOperand* operand) const {
407   return graph_->LookupValue(operand->index())->representation();
408 }
409
410
411 void LChunk::CommitDependencies(Handle<Code> code) const {
412   for (MapSet::const_iterator it = deprecation_dependencies_.begin(),
413        iend = deprecation_dependencies_.end(); it != iend; ++it) {
414     Handle<Map> map = *it;
415     DCHECK(!map->is_deprecated());
416     DCHECK(map->CanBeDeprecated());
417     Map::AddDependentCode(map, DependentCode::kTransitionGroup, code);
418   }
419
420   for (MapSet::const_iterator it = stability_dependencies_.begin(),
421        iend = stability_dependencies_.end(); it != iend; ++it) {
422     Handle<Map> map = *it;
423     DCHECK(map->is_stable());
424     DCHECK(map->CanTransition());
425     Map::AddDependentCode(map, DependentCode::kPrototypeCheckGroup, code);
426   }
427
428   info_->CommitDependencies(code);
429 }
430
431
432 LChunk* LChunk::NewChunk(HGraph* graph) {
433   DisallowHandleAllocation no_handles;
434   DisallowHeapAllocation no_gc;
435   graph->DisallowAddingNewValues();
436   int values = graph->GetMaximumValueID();
437   CompilationInfo* info = graph->info();
438   if (values > LUnallocated::kMaxVirtualRegisters) {
439     info->set_bailout_reason(kNotEnoughVirtualRegistersForValues);
440     return NULL;
441   }
442   LAllocator allocator(values, graph);
443   LChunkBuilder builder(info, graph, &allocator);
444   LChunk* chunk = builder.Build();
445   if (chunk == NULL) return NULL;
446
447   if (!allocator.Allocate(chunk)) {
448     info->set_bailout_reason(kNotEnoughVirtualRegistersRegalloc);
449     return NULL;
450   }
451
452   chunk->set_allocated_double_registers(
453       allocator.assigned_double_registers());
454
455   return chunk;
456 }
457
458
459 Handle<Code> LChunk::Codegen() {
460   MacroAssembler assembler(info()->isolate(), NULL, 0);
461   LOG_CODE_EVENT(info()->isolate(),
462                  CodeStartLinePosInfoRecordEvent(
463                      assembler.positions_recorder()));
464   // TODO(yangguo) remove this once the code serializer handles code stubs.
465   if (info()->will_serialize()) assembler.enable_serializer();
466   LCodeGen generator(this, &assembler, info());
467
468   MarkEmptyBlocks();
469
470   if (generator.GenerateCode()) {
471     generator.CheckEnvironmentUsage();
472     CodeGenerator::MakeCodePrologue(info(), "optimized");
473     Code::Flags flags = info()->flags();
474     Handle<Code> code =
475         CodeGenerator::MakeCodeEpilogue(&assembler, flags, info());
476     generator.FinishCode(code);
477     CommitDependencies(code);
478     code->set_is_crankshafted(true);
479     void* jit_handler_data =
480         assembler.positions_recorder()->DetachJITHandlerData();
481     LOG_CODE_EVENT(info()->isolate(),
482                    CodeEndLinePosInfoRecordEvent(*code, jit_handler_data));
483
484     CodeGenerator::PrintCode(code, info());
485     DCHECK(!(info()->isolate()->serializer_enabled() &&
486              info()->GetMustNotHaveEagerFrame() &&
487              generator.NeedsEagerFrame()));
488     return code;
489   }
490   assembler.AbortedCodeGeneration();
491   return Handle<Code>::null();
492 }
493
494
495 void LChunk::set_allocated_double_registers(BitVector* allocated_registers) {
496   allocated_double_registers_ = allocated_registers;
497   BitVector* doubles = allocated_double_registers();
498   BitVector::Iterator iterator(doubles);
499   while (!iterator.Done()) {
500     if (info()->saves_caller_doubles()) {
501       if (kDoubleSize == kPointerSize * 2) {
502         spill_slot_count_ += 2;
503       } else {
504         spill_slot_count_++;
505       }
506     }
507     iterator.Advance();
508   }
509 }
510
511
512 LEnvironment* LChunkBuilderBase::CreateEnvironment(
513     HEnvironment* hydrogen_env,
514     int* argument_index_accumulator,
515     ZoneList<HValue*>* objects_to_materialize) {
516   if (hydrogen_env == NULL) return NULL;
517
518   LEnvironment* outer = CreateEnvironment(hydrogen_env->outer(),
519                                           argument_index_accumulator,
520                                           objects_to_materialize);
521   BailoutId ast_id = hydrogen_env->ast_id();
522   DCHECK(!ast_id.IsNone() ||
523          hydrogen_env->frame_type() != JS_FUNCTION);
524   int value_count = hydrogen_env->length() - hydrogen_env->specials_count();
525   LEnvironment* result =
526       new(zone()) LEnvironment(hydrogen_env->closure(),
527                                hydrogen_env->frame_type(),
528                                ast_id,
529                                hydrogen_env->parameter_count(),
530                                argument_count_,
531                                value_count,
532                                outer,
533                                hydrogen_env->entry(),
534                                zone());
535   int argument_index = *argument_index_accumulator;
536
537   // Store the environment description into the environment
538   // (with holes for nested objects)
539   for (int i = 0; i < hydrogen_env->length(); ++i) {
540     if (hydrogen_env->is_special_index(i)) continue;
541
542     LOperand* op;
543     HValue* value = hydrogen_env->values()->at(i);
544     CHECK(!value->IsPushArguments());  // Do not deopt outgoing arguments
545     if (value->IsArgumentsObject() || value->IsCapturedObject()) {
546       op = LEnvironment::materialization_marker();
547     } else {
548       op = UseAny(value);
549     }
550     result->AddValue(op,
551                      value->representation(),
552                      value->CheckFlag(HInstruction::kUint32));
553   }
554
555   // Recursively store the nested objects into the environment
556   for (int i = 0; i < hydrogen_env->length(); ++i) {
557     if (hydrogen_env->is_special_index(i)) continue;
558
559     HValue* value = hydrogen_env->values()->at(i);
560     if (value->IsArgumentsObject() || value->IsCapturedObject()) {
561       AddObjectToMaterialize(value, objects_to_materialize, result);
562     }
563   }
564
565   if (hydrogen_env->frame_type() == JS_FUNCTION) {
566     *argument_index_accumulator = argument_index;
567   }
568
569   return result;
570 }
571
572
573 // Add an object to the supplied environment and object materialization list.
574 //
575 // Notes:
576 //
577 // We are building three lists here:
578 //
579 // 1. In the result->object_mapping_ list (added to by the
580 //    LEnvironment::Add*Object methods), we store the lengths (number
581 //    of fields) of the captured objects in depth-first traversal order, or
582 //    in case of duplicated objects, we store the index to the duplicate object
583 //    (with a tag to differentiate between captured and duplicated objects).
584 //
585 // 2. The object fields are stored in the result->values_ list
586 //    (added to by the LEnvironment.AddValue method) sequentially as lists
587 //    of fields with holes for nested objects (the holes will be expanded
588 //    later by LCodegen::AddToTranslation according to the
589 //    LEnvironment.object_mapping_ list).
590 //
591 // 3. The auxiliary objects_to_materialize array stores the hydrogen values
592 //    in the same order as result->object_mapping_ list. This is used
593 //    to detect duplicate values and calculate the corresponding object index.
594 void LChunkBuilderBase::AddObjectToMaterialize(HValue* value,
595     ZoneList<HValue*>* objects_to_materialize, LEnvironment* result) {
596   int object_index = objects_to_materialize->length();
597   // Store the hydrogen value into the de-duplication array
598   objects_to_materialize->Add(value, zone());
599   // Find out whether we are storing a duplicated value
600   int previously_materialized_object = -1;
601   for (int prev = 0; prev < object_index; ++prev) {
602     if (objects_to_materialize->at(prev) == value) {
603       previously_materialized_object = prev;
604       break;
605     }
606   }
607   // Store the captured object length (or duplicated object index)
608   // into the environment. For duplicated objects, we stop here.
609   int length = value->OperandCount();
610   bool is_arguments = value->IsArgumentsObject();
611   if (previously_materialized_object >= 0) {
612     result->AddDuplicateObject(previously_materialized_object);
613     return;
614   } else {
615     result->AddNewObject(is_arguments ? length - 1 : length, is_arguments);
616   }
617   // Store the captured object's fields into the environment
618   for (int i = is_arguments ? 1 : 0; i < length; ++i) {
619     LOperand* op;
620     HValue* arg_value = value->OperandAt(i);
621     if (arg_value->IsArgumentsObject() || arg_value->IsCapturedObject()) {
622       // Insert a hole for nested objects
623       op = LEnvironment::materialization_marker();
624     } else {
625       DCHECK(!arg_value->IsPushArguments());
626       // For ordinary values, tell the register allocator we need the value
627       // to be alive here
628       op = UseAny(arg_value);
629     }
630     result->AddValue(op,
631                      arg_value->representation(),
632                      arg_value->CheckFlag(HInstruction::kUint32));
633   }
634   // Recursively store all the nested captured objects into the environment
635   for (int i = is_arguments ? 1 : 0; i < length; ++i) {
636     HValue* arg_value = value->OperandAt(i);
637     if (arg_value->IsArgumentsObject() || arg_value->IsCapturedObject()) {
638       AddObjectToMaterialize(arg_value, objects_to_materialize, result);
639     }
640   }
641 }
642
643
644 LPhase::~LPhase() {
645   if (ShouldProduceTraceOutput()) {
646     isolate()->GetHTracer()->TraceLithium(name(), chunk_);
647   }
648 }
649
650
651 } }  // namespace v8::internal