1 /*
  2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "c1/c1_MacroAssembler.hpp"
 26 #include "c1/c1_Runtime1.hpp"
 27 #include "code/compiledIC.hpp"
 28 #include "compiler/compilerDefinitions.inline.hpp"
 29 #include "gc/shared/barrierSet.hpp"
 30 #include "gc/shared/barrierSetAssembler.hpp"
 31 #include "gc/shared/collectedHeap.hpp"
 32 #include "gc/shared/tlab_globals.hpp"
 33 #include "interpreter/interpreter.hpp"
 34 #include "oops/arrayOop.hpp"
 35 #include "oops/markWord.hpp"
 36 #include "runtime/arguments.hpp"
 37 #include "runtime/basicLock.hpp"
 38 #include "runtime/frame.inline.hpp"
 39 #include "runtime/globals.hpp"
 40 #include "runtime/os.hpp"
 41 #include "runtime/sharedRuntime.hpp"
 42 #include "runtime/stubRoutines.hpp"
 43 #include "utilities/checkedCast.hpp"
 44 #include "utilities/globalDefinitions.hpp"
 45 
 46 int C1_MacroAssembler::lock_object(Register hdr, Register obj, Register basic_lock, Register tmp, Label& slow_case) {
 47   assert(hdr == rax, "hdr must be rax, for the cmpxchg instruction");
 48   assert_different_registers(hdr, obj, basic_lock, tmp);
 49   int null_check_offset = -1;
 50 
 51   verify_oop(obj);
 52 
 53   // save object being locked into the BasicObjectLock
 54   movptr(Address(basic_lock, BasicObjectLock::obj_offset()), obj);
 55 
 56   null_check_offset = offset();
 57 
 58   fast_lock(basic_lock, obj, hdr, tmp, slow_case);
 59 
 60   return null_check_offset;
 61 }
 62 
 63 void C1_MacroAssembler::unlock_object(Register hdr, Register obj, Register basic_lock, Label& slow_case) {
 64   assert(basic_lock == rax, "basic_lock must be rax, for the cmpxchg instruction");
 65   assert(hdr != obj && hdr != basic_lock && obj != basic_lock, "registers must be different");
 66 
 67   // load object
 68   movptr(obj, Address(basic_lock, BasicObjectLock::obj_offset()));
 69   verify_oop(obj);
 70 
 71   fast_unlock(obj, rax, hdr, slow_case);
 72 }
 73 
 74 
 75 // Defines obj, preserves var_size_in_bytes
 76 void C1_MacroAssembler::try_allocate(Register obj, Register var_size_in_bytes, int con_size_in_bytes, Register t1, Register t2, Label& slow_case) {
 77   if (UseTLAB) {
 78     tlab_allocate(obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
 79   } else {
 80     jmp(slow_case);
 81   }
 82 }
 83 
 84 
 85 void C1_MacroAssembler::initialize_header(Register obj, Register klass, Register len, Register t1, Register t2) {
 86   assert_different_registers(obj, klass, len, t1, t2);
 87   if (UseCompactObjectHeaders || Arguments::is_valhalla_enabled()) {
 88     // COH: Markword contains class pointer which is only known at runtime.
 89     // Valhalla: Could have value class which has a different prototype header to a normal object.
 90     // In both cases, we need to fetch dynamically.
 91     movptr(t1, Address(klass, Klass::prototype_header_offset()));
 92     movptr(Address(obj, oopDesc::mark_offset_in_bytes()), t1);
 93   } else {
 94     // Otherwise: Can use the statically computed prototype header which is the same for every object.
 95     movptr(Address(obj, oopDesc::mark_offset_in_bytes()), checked_cast<int32_t>(markWord::prototype().value()));
 96   }
 97   if (!UseCompactObjectHeaders) {
 98     // COH: Markword already contains class pointer. Nothing else to do.
 99     // Otherwise: Fetch klass pointer following the markword
100     if (UseCompressedClassPointers) { // Take care not to kill klass
101       movptr(t1, klass);
102       encode_klass_not_null(t1, rscratch1);
103       movl(Address(obj, oopDesc::klass_offset_in_bytes()), t1);
104     } else {
105       movptr(Address(obj, oopDesc::klass_offset_in_bytes()), klass);
106     }
107   }
108 
109   if (len->is_valid()) {
110     movl(Address(obj, arrayOopDesc::length_offset_in_bytes()), len);
111     int base_offset = arrayOopDesc::length_offset_in_bytes() + BytesPerInt;
112     if (!is_aligned(base_offset, BytesPerWord)) {
113       assert(is_aligned(base_offset, BytesPerInt), "must be 4-byte aligned");
114       // Clear gap/first 4 bytes following the length field.
115       xorl(t1, t1);
116       movl(Address(obj, base_offset), t1);
117     }
118   } else if (UseCompressedClassPointers && !UseCompactObjectHeaders) {
119     xorptr(t1, t1);
120     store_klass_gap(obj, t1);
121   }
122 }
123 
124 
125 // preserves obj, destroys len_in_bytes
126 void C1_MacroAssembler::initialize_body(Register obj, Register len_in_bytes, int hdr_size_in_bytes, Register t1) {
127   assert(hdr_size_in_bytes >= 0, "header size must be positive or 0");
128   Label done;
129 
130   // len_in_bytes is positive and ptr sized
131   subptr(len_in_bytes, hdr_size_in_bytes);
132   zero_memory(obj, len_in_bytes, hdr_size_in_bytes, t1);
133   bind(done);
134 }
135 
136 
137 void C1_MacroAssembler::allocate_object(Register obj, Register t1, Register t2, int header_size, int object_size, Register klass, Label& slow_case) {
138   assert(obj == rax, "obj must be in rax, for cmpxchg");
139   assert_different_registers(obj, t1, t2); // XXX really?
140   assert(header_size >= 0 && object_size >= header_size, "illegal sizes");
141 
142   try_allocate(obj, noreg, object_size * BytesPerWord, t1, t2, slow_case);
143 
144   initialize_object(obj, klass, noreg, object_size * HeapWordSize, t1, t2, UseTLAB);
145 }
146 
147 void C1_MacroAssembler::initialize_object(Register obj, Register klass, Register var_size_in_bytes, int con_size_in_bytes, Register t1, Register t2, bool is_tlab_allocated) {
148   assert((con_size_in_bytes & MinObjAlignmentInBytesMask) == 0,
149          "con_size_in_bytes is not multiple of alignment");
150   const int hdr_size_in_bytes = instanceOopDesc::header_size() * HeapWordSize;
151   if (UseCompactObjectHeaders) {
152     assert(hdr_size_in_bytes == 8, "check object headers size");
153   }
154   initialize_header(obj, klass, noreg, t1, t2);
155 
156   if (!(UseTLAB && ZeroTLAB && is_tlab_allocated)) {
157     // clear rest of allocated space
158     const Register t1_zero = t1;
159     const Register index = t2;
160     const int threshold = 6 * BytesPerWord;   // approximate break even point for code size (see comments below)
161     if (var_size_in_bytes != noreg) {
162       mov(index, var_size_in_bytes);
163       initialize_body(obj, index, hdr_size_in_bytes, t1_zero);
164     } else if (con_size_in_bytes <= threshold) {
165       // use explicit null stores
166       // code size = 2 + 3*n bytes (n = number of fields to clear)
167       xorptr(t1_zero, t1_zero); // use t1_zero reg to clear memory (shorter code)
168       for (int i = hdr_size_in_bytes; i < con_size_in_bytes; i += BytesPerWord)
169         movptr(Address(obj, i), t1_zero);
170     } else if (con_size_in_bytes > hdr_size_in_bytes) {
171       // use loop to null out the fields
172       // code size = 16 bytes for even n (n = number of fields to clear)
173       // initialize last object field first if odd number of fields
174       xorptr(t1_zero, t1_zero); // use t1_zero reg to clear memory (shorter code)
175       movptr(index, (con_size_in_bytes - hdr_size_in_bytes) >> 3);
176       // initialize last object field if constant size is odd
177       if (((con_size_in_bytes - hdr_size_in_bytes) & 4) != 0)
178         movptr(Address(obj, con_size_in_bytes - (1*BytesPerWord)), t1_zero);
179       // initialize remaining object fields: rdx is a multiple of 2
180       { Label loop;
181         bind(loop);
182         movptr(Address(obj, index, Address::times_8, hdr_size_in_bytes - (1*BytesPerWord)),
183                t1_zero);
184         decrement(index);
185         jcc(Assembler::notZero, loop);
186       }
187     }
188   }
189 
190   if (CURRENT_ENV->dtrace_alloc_probes()) {
191     assert(obj == rax, "must be");
192     call(RuntimeAddress(Runtime1::entry_for(StubId::c1_dtrace_object_alloc_id)));
193   }
194 
195   verify_oop(obj);
196 }
197 
198 void C1_MacroAssembler::allocate_array(Register obj, Register len, Register t1, Register t2, int base_offset_in_bytes, Address::ScaleFactor f, Register klass, Label& slow_case, bool zero_array) {
199   assert(obj == rax, "obj must be in rax, for cmpxchg");
200   assert_different_registers(obj, len, t1, t2, klass);
201 
202   // determine alignment mask
203   assert(!(BytesPerWord & 1), "must be a multiple of 2 for masking code to work");
204 
205   // check for negative or excessive length
206   cmpptr(len, checked_cast<int32_t>(max_array_allocation_length));
207   jcc(Assembler::above, slow_case);
208 
209   const Register arr_size = t2; // okay to be the same
210   // align object end
211   movptr(arr_size, base_offset_in_bytes + MinObjAlignmentInBytesMask);
212   lea(arr_size, Address(arr_size, len, f));
213   andptr(arr_size, ~MinObjAlignmentInBytesMask);
214 
215   try_allocate(obj, arr_size, 0, t1, t2, slow_case);
216 
217   initialize_header(obj, klass, len, t1, t2);
218 
219   // clear rest of allocated space
220   if (zero_array) {
221     const Register len_zero = len;
222     // Align-up to word boundary, because we clear the 4 bytes potentially
223     // following the length field in initialize_header().
224     int base_offset = align_up(base_offset_in_bytes, BytesPerWord);
225     initialize_body(obj, arr_size, base_offset, len_zero);
226   }
227 
228   if (CURRENT_ENV->dtrace_alloc_probes()) {
229     assert(obj == rax, "must be");
230     call(RuntimeAddress(Runtime1::entry_for(StubId::c1_dtrace_object_alloc_id)));
231   }
232 
233   verify_oop(obj);
234 }
235 
236 void C1_MacroAssembler::build_frame_helper(int frame_size_in_bytes, int sp_offset_for_orig_pc, int sp_inc, bool reset_orig_pc, bool needs_stack_repair) {
237   push(rbp);
238 #ifdef ASSERT
239   if (sp_inc > 0) {
240     movl(Address(rsp, 0), badRegWordVal);
241     movl(Address(rsp, VMRegImpl::stack_slot_size), badRegWordVal);
242   }
243 #endif
244   if (PreserveFramePointer) {
245     mov(rbp, rsp);
246   }
247   decrement(rsp, frame_size_in_bytes);
248 
249   if (needs_stack_repair) {
250     // Save stack increment (also account for fixed framesize and rbp)
251     assert((sp_inc & (StackAlignmentInBytes-1)) == 0, "stack increment not aligned");
252     int real_frame_size = sp_inc + frame_size_in_bytes;
253     movptr(Address(rsp, frame_size_in_bytes - wordSize), real_frame_size);
254   }
255   if (reset_orig_pc) {
256     // Zero orig_pc to detect deoptimization during buffering in the entry points
257     movptr(Address(rsp, sp_offset_for_orig_pc), 0);
258   }
259 }
260 
261 void C1_MacroAssembler::build_frame(int frame_size_in_bytes, int bang_size_in_bytes, int sp_offset_for_orig_pc, bool needs_stack_repair, bool has_scalarized_args, Label* verified_inline_entry_label) {
262   // Make sure there is enough stack space for this method's activation.
263   // Note that we do this before doing an enter(). This matches the
264   // ordering of C2's stack overflow check / rsp decrement and allows
265   // the SharedRuntime stack overflow handling to be consistent
266   // between the two compilers.
267   assert(bang_size_in_bytes >= frame_size_in_bytes, "stack bang size incorrect");
268   generate_stack_overflow_check(bang_size_in_bytes);
269 
270   build_frame_helper(frame_size_in_bytes, sp_offset_for_orig_pc, 0, has_scalarized_args, needs_stack_repair);
271 
272   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
273   // C1 code is not hot enough to micro optimize the nmethod entry barrier with an out-of-line stub
274   bs->nmethod_entry_barrier(this, nullptr /* slow_path */, nullptr /* continuation */);
275 
276   if (verified_inline_entry_label != nullptr) {
277     // Jump here from the scalarized entry points that already created the frame.
278     bind(*verified_inline_entry_label);
279   }
280 }
281 
282 void C1_MacroAssembler::verified_entry(bool breakAtEntry) {
283   if (breakAtEntry) int3();
284   // build frame
285 }
286 
287 int C1_MacroAssembler::scalarized_entry(const CompiledEntrySignature* ces, int frame_size_in_bytes, int bang_size_in_bytes, int sp_offset_for_orig_pc, Label& verified_inline_entry_label, bool is_inline_ro_entry) {
288   assert(InlineTypePassFieldsAsArgs, "sanity");
289   // Make sure there is enough stack space for this method's activation.
290   assert(bang_size_in_bytes >= frame_size_in_bytes, "stack bang size incorrect");
291   generate_stack_overflow_check(bang_size_in_bytes);
292 
293   GrowableArray<SigEntry>* sig    = ces->sig();
294   GrowableArray<SigEntry>* sig_cc = is_inline_ro_entry ? ces->sig_cc_ro() : ces->sig_cc();
295   VMRegPair* regs      = ces->regs();
296   VMRegPair* regs_cc   = is_inline_ro_entry ? ces->regs_cc_ro() : ces->regs_cc();
297   int args_on_stack    = ces->args_on_stack();
298   int args_on_stack_cc = is_inline_ro_entry ? ces->args_on_stack_cc_ro() : ces->args_on_stack_cc();
299 
300   assert(sig->length() <= sig_cc->length(), "Zero-sized inline class not allowed!");
301   BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sig_cc->length());
302   int args_passed = sig->length();
303   int args_passed_cc = SigEntry::fill_sig_bt(sig_cc, sig_bt);
304 
305   // Create a temp frame so we can call into the runtime. It must be properly set up to accommodate GC.
306   build_frame_helper(frame_size_in_bytes, sp_offset_for_orig_pc, 0, true, ces->c1_needs_stack_repair());
307 
308   // The runtime call might safepoint, make sure nmethod entry barrier is executed
309   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
310   // C1 code is not hot enough to micro optimize the nmethod entry barrier with an out-of-line stub
311   bs->nmethod_entry_barrier(this, nullptr /* slow_path */, nullptr /* continuation */);
312 
313   // FIXME -- call runtime only if we cannot in-line allocate all the incoming inline type args.
314   movptr(rbx, (intptr_t)(ces->method()));
315   if (is_inline_ro_entry) {
316     call(RuntimeAddress(Runtime1::entry_for(StubId::c1_buffer_inline_args_no_receiver_id)));
317   } else {
318     call(RuntimeAddress(Runtime1::entry_for(StubId::c1_buffer_inline_args_id)));
319   }
320   int rt_call_offset = offset();
321 
322   // Remove the temp frame
323   addptr(rsp, frame_size_in_bytes);
324   pop(rbp);
325 
326   // Check if we need to extend the stack for packing
327   int sp_inc = 0;
328   if (args_on_stack > args_on_stack_cc) {
329     sp_inc = extend_stack_for_inline_args(args_on_stack);
330   }
331 
332   shuffle_inline_args(true, is_inline_ro_entry, sig_cc,
333                       args_passed_cc, args_on_stack_cc, regs_cc, // from
334                       args_passed, args_on_stack, regs,          // to
335                       sp_inc, rax);
336 
337   // Create the real frame. Below jump will then skip over the stack banging and frame
338   // setup code in the verified_inline_entry (which has a different real_frame_size).
339   build_frame_helper(frame_size_in_bytes, sp_offset_for_orig_pc, sp_inc, false, ces->c1_needs_stack_repair());
340 
341   jmp(verified_inline_entry_label);
342   return rt_call_offset;
343 }
344 
345 void C1_MacroAssembler::load_parameter(int offset_in_words, Register reg) {
346   // rbp, + 0: link
347   //     + 1: return address
348   //     + 2: argument with offset 0
349   //     + 3: argument with offset 1
350   //     + 4: ...
351 
352   movptr(reg, Address(rbp, (offset_in_words + 2) * BytesPerWord));
353 }
354 
355 #ifndef PRODUCT
356 
357 void C1_MacroAssembler::verify_stack_oop(int stack_offset) {
358   if (!VerifyOops) return;
359   verify_oop_addr(Address(rsp, stack_offset));
360 }
361 
362 void C1_MacroAssembler::verify_not_null_oop(Register r) {
363   if (!VerifyOops) return;
364   Label not_null;
365   testptr(r, r);
366   jcc(Assembler::notZero, not_null);
367   stop("non-null oop required");
368   bind(not_null);
369   verify_oop(r);
370 }
371 
372 void C1_MacroAssembler::invalidate_registers(bool inv_rax, bool inv_rbx, bool inv_rcx, bool inv_rdx, bool inv_rsi, bool inv_rdi) {
373 #ifdef ASSERT
374   if (inv_rax) movptr(rax, 0xDEAD);
375   if (inv_rbx) movptr(rbx, 0xDEAD);
376   if (inv_rcx) movptr(rcx, 0xDEAD);
377   if (inv_rdx) movptr(rdx, 0xDEAD);
378   if (inv_rsi) movptr(rsi, 0xDEAD);
379   if (inv_rdi) movptr(rdi, 0xDEAD);
380 #endif
381 }
382 
383 #endif // ifndef PRODUCT