1 // Copyright 2010 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.
28 #ifndef V8_ARM_CODEGEN_ARM_H_
29 #define V8_ARM_CODEGEN_ARM_H_
34 // Forward declarations
35 class CompilationInfo;
37 class RegisterAllocator;
40 enum InitState { CONST_INIT, NOT_CONST_INIT };
41 enum TypeofState { INSIDE_TYPEOF, NOT_INSIDE_TYPEOF };
44 // -------------------------------------------------------------------------
47 // A reference is a C++ stack-allocated object that puts a
48 // reference on the virtual frame. The reference may be consumed
49 // by GetValue, TakeValue, SetValue, and Codegen::UnloadReference.
50 // When the lifetime (scope) of a valid reference ends, it must have
51 // been consumed, and be in state UNLOADED.
52 class Reference BASE_EMBEDDED {
54 // The values of the types is important, see size().
55 enum Type { UNLOADED = -2, ILLEGAL = -1, SLOT = 0, NAMED = 1, KEYED = 2 };
56 Reference(CodeGenerator* cgen,
57 Expression* expression,
58 bool persist_after_get = false);
61 Expression* expression() const { return expression_; }
62 Type type() const { return type_; }
63 void set_type(Type value) {
64 ASSERT_EQ(ILLEGAL, type_);
69 ASSERT_NE(ILLEGAL, type_);
70 ASSERT_NE(UNLOADED, type_);
73 // The size the reference takes up on the stack.
75 return (type_ < SLOT) ? 0 : type_;
78 bool is_illegal() const { return type_ == ILLEGAL; }
79 bool is_slot() const { return type_ == SLOT; }
80 bool is_property() const { return type_ == NAMED || type_ == KEYED; }
81 bool is_unloaded() const { return type_ == UNLOADED; }
83 // Return the name. Only valid for named property references.
84 Handle<String> GetName();
86 // Generate code to push the value of the reference on top of the
87 // expression stack. The reference is expected to be already on top of
88 // the expression stack, and it is consumed by the call unless the
89 // reference is for a compound assignment.
90 // If the reference is not consumed, it is left in place under its value.
93 // Generate code to pop a reference, push the value of the reference,
94 // and then spill the stack frame.
95 inline void GetValueAndSpill();
97 // Generate code to store the value on top of the expression stack in the
98 // reference. The reference is expected to be immediately below the value
99 // on the expression stack. The value is stored in the location specified
100 // by the reference, and is left on top of the stack, after the reference
101 // is popped from beneath it (unloaded).
102 void SetValue(InitState init_state);
105 CodeGenerator* cgen_;
106 Expression* expression_;
108 // Keep the reference on the stack after get, so it can be used by set later.
109 bool persist_after_get_;
113 // -------------------------------------------------------------------------
114 // Code generation state
116 // The state is passed down the AST by the code generator (and back up, in
117 // the form of the state of the label pair). It is threaded through the
118 // call stack. Constructing a state implicitly pushes it on the owning code
119 // generator's stack of states, and destroying one implicitly pops it.
121 class CodeGenState BASE_EMBEDDED {
123 // Create an initial code generator state. Destroying the initial state
124 // leaves the code generator with a NULL state.
125 explicit CodeGenState(CodeGenerator* owner);
127 // Create a code generator state based on a code generator's current
128 // state. The new state has its own pair of branch labels.
129 CodeGenState(CodeGenerator* owner,
130 JumpTarget* true_target,
131 JumpTarget* false_target);
133 // Destroy a code generator state and restore the owning code generator's
137 JumpTarget* true_target() const { return true_target_; }
138 JumpTarget* false_target() const { return false_target_; }
141 CodeGenerator* owner_;
142 JumpTarget* true_target_;
143 JumpTarget* false_target_;
144 CodeGenState* previous_;
148 // -------------------------------------------------------------------------
151 class CodeGenerator: public AstVisitor {
153 // Takes a function literal, generates code for it. This function should only
154 // be called by compiler.cc.
155 static Handle<Code> MakeCode(CompilationInfo* info);
157 // Printing of AST, etc. as requested by flags.
158 static void MakeCodePrologue(CompilationInfo* info);
160 // Allocate and install the code.
161 static Handle<Code> MakeCodeEpilogue(MacroAssembler* masm,
163 CompilationInfo* info);
165 #ifdef ENABLE_LOGGING_AND_PROFILING
166 static bool ShouldGenerateLog(Expression* type);
169 static void SetFunctionInfo(Handle<JSFunction> fun,
170 FunctionLiteral* lit,
172 Handle<Script> script);
174 static void RecordPositions(MacroAssembler* masm, int pos);
177 MacroAssembler* masm() { return masm_; }
178 VirtualFrame* frame() const { return frame_; }
179 inline Handle<Script> script();
181 bool has_valid_frame() const { return frame_ != NULL; }
183 // Set the virtual frame to be new_frame, with non-frame register
184 // reference counts given by non_frame_registers. The non-frame
185 // register reference counts of the old frame are returned in
186 // non_frame_registers.
187 void SetFrame(VirtualFrame* new_frame, RegisterFile* non_frame_registers);
191 RegisterAllocator* allocator() const { return allocator_; }
193 CodeGenState* state() { return state_; }
194 void set_state(CodeGenState* state) { state_ = state; }
196 void AddDeferred(DeferredCode* code) { deferred_.Add(code); }
198 static const int kUnknownIntValue = -1;
200 // If the name is an inline runtime function call return the number of
201 // expected arguments. Otherwise return -1.
202 static int InlineRuntimeCallArgumentsCount(Handle<String> name);
205 // Construction/Destruction
206 explicit CodeGenerator(MacroAssembler* masm);
209 inline bool is_eval();
210 inline Scope* scope();
212 // Generating deferred code.
213 void ProcessDeferred();
216 bool has_cc() const { return cc_reg_ != al; }
217 JumpTarget* true_target() const { return state_->true_target(); }
218 JumpTarget* false_target() const { return state_->false_target(); }
220 // We don't track loop nesting level on ARM yet.
221 int loop_nesting() const { return 0; }
224 void VisitStatements(ZoneList<Statement*>* statements);
226 #define DEF_VISIT(type) \
227 void Visit##type(type* node);
228 AST_NODE_LIST(DEF_VISIT)
231 // Visit a statement and then spill the virtual frame if control flow can
232 // reach the end of the statement (ie, it does not exit via break,
233 // continue, return, or throw). This function is used temporarily while
234 // the code generator is being transformed.
235 inline void VisitAndSpill(Statement* statement);
237 // Visit a list of statements and then spill the virtual frame if control
238 // flow can reach the end of the list.
239 inline void VisitStatementsAndSpill(ZoneList<Statement*>* statements);
241 // Main code generation function
242 void Generate(CompilationInfo* info);
244 // The following are used by class Reference.
245 void LoadReference(Reference* ref);
246 void UnloadReference(Reference* ref);
248 static MemOperand ContextOperand(Register context, int index) {
249 return MemOperand(context, Context::SlotOffset(index));
252 MemOperand SlotOperand(Slot* slot, Register tmp);
254 MemOperand ContextSlotOperandCheckExtensions(Slot* slot,
260 static MemOperand GlobalObject() {
261 return ContextOperand(cp, Context::GLOBAL_INDEX);
264 void LoadCondition(Expression* x,
265 JumpTarget* true_target,
266 JumpTarget* false_target,
268 void Load(Expression* expr);
270 void LoadGlobalReceiver(Register scratch);
272 // Generate code to push the value of an expression on top of the frame
273 // and then spill the frame fully to memory. This function is used
274 // temporarily while the code generator is being transformed.
275 inline void LoadAndSpill(Expression* expression);
277 // Call LoadCondition and then spill the virtual frame unless control flow
278 // cannot reach the end of the expression (ie, by emitting only
279 // unconditional jumps to the control targets).
280 inline void LoadConditionAndSpill(Expression* expression,
281 JumpTarget* true_target,
282 JumpTarget* false_target,
285 // Read a value from a slot and leave it on top of the expression stack.
286 void LoadFromSlot(Slot* slot, TypeofState typeof_state);
287 // Store the value on top of the stack to a slot.
288 void StoreToSlot(Slot* slot, InitState init_state);
289 // Load a keyed property, leaving it in r0. The receiver and key are
290 // passed on the stack, and remain there.
291 void EmitKeyedLoad(bool is_global);
293 void LoadFromGlobalSlotCheckExtensions(Slot* slot,
294 TypeofState typeof_state,
299 // Special code for typeof expressions: Unfortunately, we must
300 // be careful when loading the expression in 'typeof'
301 // expressions. We are not allowed to throw reference errors for
302 // non-existing properties of the global object, so we must make it
303 // look like an explicit property access, instead of an access
304 // through the context chain.
305 void LoadTypeofExpression(Expression* x);
307 void ToBoolean(JumpTarget* true_target, JumpTarget* false_target);
309 // Generate code that computes a shortcutting logical operation.
310 void GenerateLogicalBooleanOperation(BinaryOperation* node);
312 void GenericBinaryOperation(Token::Value op,
313 OverwriteMode overwrite_mode,
314 int known_rhs = kUnknownIntValue);
315 void Comparison(Condition cc,
318 bool strict = false);
320 void SmiOperation(Token::Value op,
321 Handle<Object> value,
325 void CallWithArguments(ZoneList<Expression*>* arguments,
326 CallFunctionFlags flags,
330 void Branch(bool if_true, JumpTarget* target);
333 struct InlineRuntimeLUT {
334 void (CodeGenerator::*method)(ZoneList<Expression*>*);
339 static InlineRuntimeLUT* FindInlineRuntimeLUT(Handle<String> name);
340 bool CheckForInlineRuntimeCall(CallRuntime* node);
341 static bool PatchInlineRuntimeEntry(Handle<String> name,
342 const InlineRuntimeLUT& new_entry,
343 InlineRuntimeLUT* old_entry);
345 static Handle<Code> ComputeLazyCompile(int argc);
346 void ProcessDeclarations(ZoneList<Declaration*>* declarations);
348 static Handle<Code> ComputeCallInitialize(int argc, InLoopFlag in_loop);
350 // Declare global variables and functions in the given array of
352 void DeclareGlobals(Handle<FixedArray> pairs);
354 // Instantiate the function based on the shared function info.
355 void InstantiateFunction(Handle<SharedFunctionInfo> function_info);
357 // Support for type checks.
358 void GenerateIsSmi(ZoneList<Expression*>* args);
359 void GenerateIsNonNegativeSmi(ZoneList<Expression*>* args);
360 void GenerateIsArray(ZoneList<Expression*>* args);
361 void GenerateIsRegExp(ZoneList<Expression*>* args);
362 void GenerateIsObject(ZoneList<Expression*>* args);
363 void GenerateIsFunction(ZoneList<Expression*>* args);
364 void GenerateIsUndetectableObject(ZoneList<Expression*>* args);
366 // Support for construct call checks.
367 void GenerateIsConstructCall(ZoneList<Expression*>* args);
369 // Support for arguments.length and arguments[?].
370 void GenerateArgumentsLength(ZoneList<Expression*>* args);
371 void GenerateArguments(ZoneList<Expression*>* args);
373 // Support for accessing the class and value fields of an object.
374 void GenerateClassOf(ZoneList<Expression*>* args);
375 void GenerateValueOf(ZoneList<Expression*>* args);
376 void GenerateSetValueOf(ZoneList<Expression*>* args);
378 // Fast support for charCodeAt(n).
379 void GenerateFastCharCodeAt(ZoneList<Expression*>* args);
381 // Fast support for string.charAt(n) and string[n].
382 void GenerateCharFromCode(ZoneList<Expression*>* args);
384 // Fast support for object equality testing.
385 void GenerateObjectEquals(ZoneList<Expression*>* args);
387 void GenerateLog(ZoneList<Expression*>* args);
389 // Fast support for Math.random().
390 void GenerateRandomPositiveSmi(ZoneList<Expression*>* args);
392 // Fast support for StringAdd.
393 void GenerateStringAdd(ZoneList<Expression*>* args);
395 // Fast support for SubString.
396 void GenerateSubString(ZoneList<Expression*>* args);
398 // Fast support for StringCompare.
399 void GenerateStringCompare(ZoneList<Expression*>* args);
401 // Support for direct calls from JavaScript to native RegExp code.
402 void GenerateRegExpExec(ZoneList<Expression*>* args);
404 // Fast support for number to string.
405 void GenerateNumberToString(ZoneList<Expression*>* args);
407 // Fast call to math functions.
408 void GenerateMathPow(ZoneList<Expression*>* args);
409 void GenerateMathSin(ZoneList<Expression*>* args);
410 void GenerateMathCos(ZoneList<Expression*>* args);
411 void GenerateMathSqrt(ZoneList<Expression*>* args);
413 // Simple condition analysis.
414 enum ConditionAnalysis {
419 ConditionAnalysis AnalyzeCondition(Expression* cond);
421 // Methods used to indicate which source code is generated for. Source
422 // positions are collected by the assembler and emitted with the relocation
424 void CodeForFunctionPosition(FunctionLiteral* fun);
425 void CodeForReturnPosition(FunctionLiteral* fun);
426 void CodeForStatementPosition(Statement* node);
427 void CodeForDoWhileConditionPosition(DoWhileStatement* stmt);
428 void CodeForSourcePosition(int pos);
431 // True if the registers are valid for entry to a block.
432 bool HasValidEntryRegisters();
435 List<DeferredCode*> deferred_;
438 MacroAssembler* masm_; // to generate code
440 CompilationInfo* info_;
442 // Code generation state
443 VirtualFrame* frame_;
444 RegisterAllocator* allocator_;
446 CodeGenState* state_;
449 BreakTarget function_return_;
451 // True if the function return is shadowed (ie, jumping to the target
452 // function_return_ does not jump to the true function return, but rather
453 // to some unlinking code).
454 bool function_return_is_shadowed_;
456 static InlineRuntimeLUT kInlineRuntimeLUT[];
458 friend class VirtualFrame;
459 friend class JumpTarget;
460 friend class Reference;
461 friend class FastCodeGenerator;
462 friend class FullCodeGenerator;
463 friend class FullCodeGenSyntaxChecker;
465 DISALLOW_COPY_AND_ASSIGN(CodeGenerator);
469 class GenericBinaryOpStub : public CodeStub {
471 GenericBinaryOpStub(Token::Value op,
473 int constant_rhs = CodeGenerator::kUnknownIntValue)
476 constant_rhs_(constant_rhs),
477 specialized_on_rhs_(RhsIsOneWeWantToOptimizeFor(op, constant_rhs)),
484 bool specialized_on_rhs_;
487 static const int kMaxKnownRhs = 0x40000000;
489 // Minor key encoding in 16 bits.
490 class ModeBits: public BitField<OverwriteMode, 0, 2> {};
491 class OpBits: public BitField<Token::Value, 2, 6> {};
492 class KnownIntBits: public BitField<int, 8, 8> {};
494 Major MajorKey() { return GenericBinaryOp; }
496 // Encode the parameters in a unique 16 bit value.
497 return OpBits::encode(op_)
498 | ModeBits::encode(mode_)
499 | KnownIntBits::encode(MinorKeyForKnownInt());
502 void Generate(MacroAssembler* masm);
503 void HandleNonSmiBitwiseOp(MacroAssembler* masm);
505 static bool RhsIsOneWeWantToOptimizeFor(Token::Value op, int constant_rhs) {
506 if (constant_rhs == CodeGenerator::kUnknownIntValue) return false;
507 if (op == Token::DIV) return constant_rhs >= 2 && constant_rhs <= 3;
508 if (op == Token::MOD) {
509 if (constant_rhs <= 1) return false;
510 if (constant_rhs <= 10) return true;
511 if (constant_rhs <= kMaxKnownRhs && IsPowerOf2(constant_rhs)) return true;
517 int MinorKeyForKnownInt() {
518 if (!specialized_on_rhs_) return 0;
519 if (constant_rhs_ <= 10) return constant_rhs_ + 1;
520 ASSERT(IsPowerOf2(constant_rhs_));
522 int d = constant_rhs_;
523 while ((d & 1) == 0) {
530 const char* GetName();
534 if (!specialized_on_rhs_) {
535 PrintF("GenericBinaryOpStub (%s)\n", Token::String(op_));
537 PrintF("GenericBinaryOpStub (%s by %d)\n",
546 class StringStubBase: public CodeStub {
548 // Generate code for copying characters using a simple loop. This should only
549 // be used in places where the number of characters is small and the
550 // additional setup and checking in GenerateCopyCharactersLong adds too much
551 // overhead. Copying of overlapping regions is not supported.
552 // Dest register ends at the position after the last character written.
553 void GenerateCopyCharacters(MacroAssembler* masm,
560 // Generate code for copying a large number of characters. This function
561 // is allowed to spend extra time setting up conditions to make copying
562 // faster. Copying of overlapping regions is not supported.
563 // Dest register ends at the position after the last character written.
564 void GenerateCopyCharactersLong(MacroAssembler* masm,
576 // Probe the symbol table for a two character string. If the string is
577 // not found by probing a jump to the label not_found is performed. This jump
578 // does not guarantee that the string is not in the symbol table. If the
579 // string is found the code falls through with the string in register r0.
580 // Contents of both c1 and c2 registers are modified. At the exit c1 is
581 // guaranteed to contain halfword with low and high bytes equal to
582 // initial contents of c1 and c2 respectively.
583 void GenerateTwoCharacterSymbolTableProbe(MacroAssembler* masm,
593 // Generate string hash.
594 void GenerateHashInit(MacroAssembler* masm,
598 void GenerateHashAddCharacter(MacroAssembler* masm,
602 void GenerateHashGetHash(MacroAssembler* masm,
607 // Flag that indicates how to generate code for the stub StringAddStub.
608 enum StringAddFlags {
609 NO_STRING_ADD_FLAGS = 0,
610 NO_STRING_CHECK_IN_STUB = 1 << 0 // Omit string check in stub.
614 class StringAddStub: public StringStubBase {
616 explicit StringAddStub(StringAddFlags flags) {
617 string_check_ = ((flags & NO_STRING_CHECK_IN_STUB) == 0);
621 Major MajorKey() { return StringAdd; }
622 int MinorKey() { return string_check_ ? 0 : 1; }
624 void Generate(MacroAssembler* masm);
626 // Should the stub check whether arguments are strings?
631 class SubStringStub: public StringStubBase {
636 Major MajorKey() { return SubString; }
637 int MinorKey() { return 0; }
639 void Generate(MacroAssembler* masm);
644 class StringCompareStub: public CodeStub {
646 StringCompareStub() { }
648 // Compare two flat ASCII strings and returns result in r0.
649 // Does not use the stack.
650 static void GenerateCompareFlatAsciiStrings(MacroAssembler* masm,
659 Major MajorKey() { return StringCompare; }
660 int MinorKey() { return 0; }
662 void Generate(MacroAssembler* masm);
666 // This stub can convert a signed int32 to a heap number (double). It does
667 // not work for int32s that are in Smi range! No GC occurs during this stub
668 // so you don't have to set up the frame.
669 class WriteInt32ToHeapNumberStub : public CodeStub {
671 WriteInt32ToHeapNumberStub(Register the_int,
672 Register the_heap_number,
675 the_heap_number_(the_heap_number),
676 scratch_(scratch) { }
680 Register the_heap_number_;
683 // Minor key encoding in 16 bits.
684 class IntRegisterBits: public BitField<int, 0, 4> {};
685 class HeapNumberRegisterBits: public BitField<int, 4, 4> {};
686 class ScratchRegisterBits: public BitField<int, 8, 4> {};
688 Major MajorKey() { return WriteInt32ToHeapNumber; }
690 // Encode the parameters in a unique 16 bit value.
691 return IntRegisterBits::encode(the_int_.code())
692 | HeapNumberRegisterBits::encode(the_heap_number_.code())
693 | ScratchRegisterBits::encode(scratch_.code());
696 void Generate(MacroAssembler* masm);
698 const char* GetName() { return "WriteInt32ToHeapNumberStub"; }
701 void Print() { PrintF("WriteInt32ToHeapNumberStub\n"); }
706 class NumberToStringStub: public CodeStub {
708 NumberToStringStub() { }
710 // Generate code to do a lookup in the number string cache. If the number in
711 // the register object is found in the cache the generated code falls through
712 // with the result in the result register. The object and the result register
713 // can be the same. If the number is not found in the cache the code jumps to
714 // the label not_found with only the content of register object unchanged.
715 static void GenerateLookupNumberStringCache(MacroAssembler* masm,
724 Major MajorKey() { return NumberToString; }
725 int MinorKey() { return 0; }
727 void Generate(MacroAssembler* masm);
729 const char* GetName() { return "NumberToStringStub"; }
733 PrintF("NumberToStringStub\n");
739 } } // namespace v8::internal
741 #endif // V8_ARM_CODEGEN_ARM_H_