1 /*
2 * Copyright (c) 2016, 2026, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2016, 2024 SAP SE. All rights reserved.
4 * Copyright 2024, 2026 IBM Corporation. All rights reserved.
5 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6 *
7 * This code is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License version 2 only, as
9 * published by the Free Software Foundation.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 *
25 */
26
27 #include "asm/codeBuffer.hpp"
28 #include "asm/macroAssembler.inline.hpp"
29 #include "code/compiledIC.hpp"
30 #include "compiler/disassembler.hpp"
31 #include "gc/shared/barrierSet.hpp"
32 #include "gc/shared/barrierSetAssembler.hpp"
33 #include "gc/shared/collectedHeap.inline.hpp"
34 #include "interpreter/interpreter.hpp"
35 #include "interpreter/interpreterRuntime.hpp"
36 #include "gc/shared/cardTableBarrierSet.hpp"
37 #include "memory/resourceArea.hpp"
38 #include "memory/universe.hpp"
39 #include "oops/accessDecorators.hpp"
40 #include "oops/compressedKlass.inline.hpp"
41 #include "oops/compressedOops.inline.hpp"
42 #include "oops/klass.inline.hpp"
43 #include "oops/methodData.hpp"
44 #include "prims/methodHandles.hpp"
45 #include "registerSaver_s390.hpp"
46 #include "runtime/icache.hpp"
47 #include "runtime/interfaceSupport.inline.hpp"
48 #include "runtime/objectMonitor.hpp"
49 #include "runtime/objectMonitorTable.hpp"
50 #include "runtime/os.hpp"
51 #include "runtime/safepoint.hpp"
52 #include "runtime/safepointMechanism.hpp"
53 #include "runtime/sharedRuntime.hpp"
54 #include "runtime/stubRoutines.hpp"
55 #include "utilities/events.hpp"
56 #include "utilities/macros.hpp"
57 #include "utilities/powerOfTwo.hpp"
58
59 #include <ucontext.h>
60
61 #define BLOCK_COMMENT(str) block_comment(str)
62 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
63
64 // Move 32-bit register if destination and source are different.
65 void MacroAssembler::lr_if_needed(Register rd, Register rs) {
66 if (rs != rd) { z_lr(rd, rs); }
67 }
68
69 // Move register if destination and source are different.
70 void MacroAssembler::lgr_if_needed(Register rd, Register rs) {
71 if (rs != rd) { z_lgr(rd, rs); }
72 }
73
74 // Zero-extend 32-bit register into 64-bit register if destination and source are different.
75 void MacroAssembler::llgfr_if_needed(Register rd, Register rs) {
76 if (rs != rd) { z_llgfr(rd, rs); }
77 }
78
79 // Move float register if destination and source are different.
80 void MacroAssembler::ldr_if_needed(FloatRegister rd, FloatRegister rs) {
81 if (rs != rd) { z_ldr(rd, rs); }
82 }
83
84 // Move integer register if destination and source are different.
85 // It is assumed that shorter-than-int types are already
86 // appropriately sign-extended.
87 void MacroAssembler::move_reg_if_needed(Register dst, BasicType dst_type, Register src,
88 BasicType src_type) {
89 assert((dst_type != T_FLOAT) && (dst_type != T_DOUBLE), "use move_freg for float types");
90 assert((src_type != T_FLOAT) && (src_type != T_DOUBLE), "use move_freg for float types");
91
92 if (dst_type == src_type) {
93 lgr_if_needed(dst, src); // Just move all 64 bits.
94 return;
95 }
96
97 switch (dst_type) {
98 // Do not support these types for now.
99 // case T_BOOLEAN:
100 case T_BYTE: // signed byte
101 switch (src_type) {
102 case T_INT:
103 z_lgbr(dst, src);
104 break;
105 default:
106 ShouldNotReachHere();
107 }
108 return;
109
110 case T_CHAR:
111 case T_SHORT:
112 switch (src_type) {
113 case T_INT:
114 if (dst_type == T_CHAR) {
115 z_llghr(dst, src);
116 } else {
117 z_lghr(dst, src);
118 }
119 break;
120 default:
121 ShouldNotReachHere();
122 }
123 return;
124
125 case T_INT:
126 switch (src_type) {
127 case T_BOOLEAN:
128 case T_BYTE:
129 case T_CHAR:
130 case T_SHORT:
131 case T_INT:
132 case T_LONG:
133 case T_OBJECT:
134 case T_ARRAY:
135 case T_VOID:
136 case T_ADDRESS:
137 lr_if_needed(dst, src);
138 // llgfr_if_needed(dst, src); // zero-extend (in case we need to find a bug).
139 return;
140
141 default:
142 assert(false, "non-integer src type");
143 return;
144 }
145 case T_LONG:
146 switch (src_type) {
147 case T_BOOLEAN:
148 case T_BYTE:
149 case T_CHAR:
150 case T_SHORT:
151 case T_INT:
152 z_lgfr(dst, src); // sign extension
153 return;
154
155 case T_LONG:
156 case T_OBJECT:
157 case T_ARRAY:
158 case T_VOID:
159 case T_ADDRESS:
160 lgr_if_needed(dst, src);
161 return;
162
163 default:
164 assert(false, "non-integer src type");
165 return;
166 }
167 return;
168 case T_OBJECT:
169 case T_ARRAY:
170 case T_VOID:
171 case T_ADDRESS:
172 switch (src_type) {
173 // These types don't make sense to be converted to pointers:
174 // case T_BOOLEAN:
175 // case T_BYTE:
176 // case T_CHAR:
177 // case T_SHORT:
178
179 case T_INT:
180 z_llgfr(dst, src); // zero extension
181 return;
182
183 case T_LONG:
184 case T_OBJECT:
185 case T_ARRAY:
186 case T_VOID:
187 case T_ADDRESS:
188 lgr_if_needed(dst, src);
189 return;
190
191 default:
192 assert(false, "non-integer src type");
193 return;
194 }
195 return;
196 default:
197 assert(false, "non-integer dst type");
198 return;
199 }
200 }
201
202 // Move float register if destination and source are different.
203 void MacroAssembler::move_freg_if_needed(FloatRegister dst, BasicType dst_type,
204 FloatRegister src, BasicType src_type) {
205 assert((dst_type == T_FLOAT) || (dst_type == T_DOUBLE), "use move_reg for int types");
206 assert((src_type == T_FLOAT) || (src_type == T_DOUBLE), "use move_reg for int types");
207 if (dst_type == src_type) {
208 ldr_if_needed(dst, src); // Just move all 64 bits.
209 } else {
210 switch (dst_type) {
211 case T_FLOAT:
212 assert(src_type == T_DOUBLE, "invalid float type combination");
213 z_ledbr(dst, src);
214 return;
215 case T_DOUBLE:
216 assert(src_type == T_FLOAT, "invalid float type combination");
217 z_ldebr(dst, src);
218 return;
219 default:
220 assert(false, "non-float dst type");
221 return;
222 }
223 }
224 }
225
226 // Optimized emitter for reg to mem operations.
227 // Uses modern instructions if running on modern hardware, classic instructions
228 // otherwise. Prefers (usually shorter) classic instructions if applicable.
229 // Data register (reg) cannot be used as work register.
230 //
231 // Don't rely on register locking, instead pass a scratch register (Z_R0 by default).
232 // CAUTION! Passing registers >= Z_R2 may produce bad results on old CPUs!
233 void MacroAssembler::freg2mem_opt(FloatRegister reg,
234 int64_t disp,
235 Register index,
236 Register base,
237 void (MacroAssembler::*modern) (FloatRegister, int64_t, Register, Register),
238 void (MacroAssembler::*classic)(FloatRegister, int64_t, Register, Register),
239 Register scratch) {
240 index = (index == noreg) ? Z_R0 : index;
241 if (Displacement::is_shortDisp(disp)) {
242 (this->*classic)(reg, disp, index, base);
243 } else {
244 if (Displacement::is_validDisp(disp)) {
245 (this->*modern)(reg, disp, index, base);
246 } else {
247 if (scratch != Z_R0 && scratch != Z_R1) {
248 (this->*modern)(reg, disp, index, base); // Will fail with disp out of range.
249 } else {
250 if (scratch != Z_R0) { // scratch == Z_R1
251 if ((scratch == index) || (index == base)) {
252 (this->*modern)(reg, disp, index, base); // Will fail with disp out of range.
253 } else {
254 add2reg(scratch, disp, base);
255 (this->*classic)(reg, 0, index, scratch);
256 if (base == scratch) {
257 add2reg(base, -disp); // Restore base.
258 }
259 }
260 } else { // scratch == Z_R0
261 z_lgr(scratch, base);
262 add2reg(base, disp);
263 (this->*classic)(reg, 0, index, base);
264 z_lgr(base, scratch); // Restore base.
265 }
266 }
267 }
268 }
269 }
270
271 void MacroAssembler::freg2mem_opt(FloatRegister reg, const Address &a, bool is_double) {
272 if (is_double) {
273 freg2mem_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_FFUN(z_stdy), CLASSIC_FFUN(z_std));
274 } else {
275 freg2mem_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_FFUN(z_stey), CLASSIC_FFUN(z_ste));
276 }
277 }
278
279 // Optimized emitter for mem to reg operations.
280 // Uses modern instructions if running on modern hardware, classic instructions
281 // otherwise. Prefers (usually shorter) classic instructions if applicable.
282 // data register (reg) cannot be used as work register.
283 //
284 // Don't rely on register locking, instead pass a scratch register (Z_R0 by default).
285 // CAUTION! Passing registers >= Z_R2 may produce bad results on old CPUs!
286 void MacroAssembler::mem2freg_opt(FloatRegister reg,
287 int64_t disp,
288 Register index,
289 Register base,
290 void (MacroAssembler::*modern) (FloatRegister, int64_t, Register, Register),
291 void (MacroAssembler::*classic)(FloatRegister, int64_t, Register, Register),
292 Register scratch) {
293 index = (index == noreg) ? Z_R0 : index;
294 if (Displacement::is_shortDisp(disp)) {
295 (this->*classic)(reg, disp, index, base);
296 } else {
297 if (Displacement::is_validDisp(disp)) {
298 (this->*modern)(reg, disp, index, base);
299 } else {
300 if (scratch != Z_R0 && scratch != Z_R1) {
301 (this->*modern)(reg, disp, index, base); // Will fail with disp out of range.
302 } else {
303 if (scratch != Z_R0) { // scratch == Z_R1
304 if ((scratch == index) || (index == base)) {
305 (this->*modern)(reg, disp, index, base); // Will fail with disp out of range.
306 } else {
307 add2reg(scratch, disp, base);
308 (this->*classic)(reg, 0, index, scratch);
309 if (base == scratch) {
310 add2reg(base, -disp); // Restore base.
311 }
312 }
313 } else { // scratch == Z_R0
314 z_lgr(scratch, base);
315 add2reg(base, disp);
316 (this->*classic)(reg, 0, index, base);
317 z_lgr(base, scratch); // Restore base.
318 }
319 }
320 }
321 }
322 }
323
324 void MacroAssembler::mem2freg_opt(FloatRegister reg, const Address &a, bool is_double) {
325 if (is_double) {
326 mem2freg_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_FFUN(z_ldy), CLASSIC_FFUN(z_ld));
327 } else {
328 mem2freg_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_FFUN(z_ley), CLASSIC_FFUN(z_le));
329 }
330 }
331
332 // Optimized emitter for reg to mem operations.
333 // Uses modern instructions if running on modern hardware, classic instructions
334 // otherwise. Prefers (usually shorter) classic instructions if applicable.
335 // Data register (reg) cannot be used as work register.
336 //
337 // Don't rely on register locking, instead pass a scratch register
338 // (Z_R0 by default)
339 // CAUTION! passing registers >= Z_R2 may produce bad results on old CPUs!
340 void MacroAssembler::reg2mem_opt(Register reg,
341 int64_t disp,
342 Register index,
343 Register base,
344 void (MacroAssembler::*modern) (Register, int64_t, Register, Register),
345 void (MacroAssembler::*classic)(Register, int64_t, Register, Register),
346 Register scratch) {
347 index = (index == noreg) ? Z_R0 : index;
348 if (Displacement::is_shortDisp(disp)) {
349 (this->*classic)(reg, disp, index, base);
350 } else {
351 if (Displacement::is_validDisp(disp)) {
352 (this->*modern)(reg, disp, index, base);
353 } else {
354 if (scratch != Z_R0 && scratch != Z_R1) {
355 (this->*modern)(reg, disp, index, base); // Will fail with disp out of range.
356 } else {
357 if (scratch != Z_R0) { // scratch == Z_R1
358 if ((scratch == index) || (index == base)) {
359 (this->*modern)(reg, disp, index, base); // Will fail with disp out of range.
360 } else {
361 add2reg(scratch, disp, base);
362 (this->*classic)(reg, 0, index, scratch);
363 if (base == scratch) {
364 add2reg(base, -disp); // Restore base.
365 }
366 }
367 } else { // scratch == Z_R0
368 if ((scratch == reg) || (scratch == base) || (reg == base)) {
369 (this->*modern)(reg, disp, index, base); // Will fail with disp out of range.
370 } else {
371 z_lgr(scratch, base);
372 add2reg(base, disp);
373 (this->*classic)(reg, 0, index, base);
374 z_lgr(base, scratch); // Restore base.
375 }
376 }
377 }
378 }
379 }
380 }
381
382 int MacroAssembler::reg2mem_opt(Register reg, const Address &a, bool is_double) {
383 int store_offset = offset();
384 if (is_double) {
385 reg2mem_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_IFUN(z_stg), CLASSIC_IFUN(z_stg));
386 } else {
387 reg2mem_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_IFUN(z_sty), CLASSIC_IFUN(z_st));
388 }
389 return store_offset;
390 }
391
392 // Optimized emitter for mem to reg operations.
393 // Uses modern instructions if running on modern hardware, classic instructions
394 // otherwise. Prefers (usually shorter) classic instructions if applicable.
395 // Data register (reg) will be used as work register where possible.
396 void MacroAssembler::mem2reg_opt(Register reg,
397 int64_t disp,
398 Register index,
399 Register base,
400 void (MacroAssembler::*modern) (Register, int64_t, Register, Register),
401 void (MacroAssembler::*classic)(Register, int64_t, Register, Register)) {
402 index = (index == noreg) ? Z_R0 : index;
403 if (Displacement::is_shortDisp(disp)) {
404 (this->*classic)(reg, disp, index, base);
405 } else {
406 if (Displacement::is_validDisp(disp)) {
407 (this->*modern)(reg, disp, index, base);
408 } else {
409 if ((reg == index) && (reg == base)) {
410 z_sllg(reg, reg, 1);
411 add2reg(reg, disp);
412 (this->*classic)(reg, 0, noreg, reg);
413 } else if ((reg == index) && (reg != Z_R0)) {
414 add2reg(reg, disp);
415 (this->*classic)(reg, 0, reg, base);
416 } else if (reg == base) {
417 add2reg(reg, disp);
418 (this->*classic)(reg, 0, index, reg);
419 } else if (reg != Z_R0) {
420 add2reg(reg, disp, base);
421 (this->*classic)(reg, 0, index, reg);
422 } else { // reg == Z_R0 && reg != base here
423 add2reg(base, disp);
424 (this->*classic)(reg, 0, index, base);
425 add2reg(base, -disp);
426 }
427 }
428 }
429 }
430
431 void MacroAssembler::mem2reg_opt(Register reg, const Address &a, bool is_double) {
432 if (is_double) {
433 z_lg(reg, a);
434 } else {
435 mem2reg_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_IFUN(z_ly), CLASSIC_IFUN(z_l));
436 }
437 }
438
439 void MacroAssembler::mem2reg_signed_opt(Register reg, const Address &a) {
440 mem2reg_opt(reg, a.disp20(), a.indexOrR0(), a.baseOrR0(), MODERN_IFUN(z_lgf), CLASSIC_IFUN(z_lgf));
441 }
442
443 void MacroAssembler::and_imm(Register r, long mask,
444 Register tmp /* = Z_R0 */,
445 bool wide /* = false */) {
446 assert(wide || Immediate::is_simm32(mask), "mask value too large");
447
448 if (!wide) {
449 z_nilf(r, mask);
450 return;
451 }
452
453 assert(r != tmp, " need a different temporary register !");
454 load_const_optimized(tmp, mask);
455 z_ngr(r, tmp);
456 }
457
458 // Calculate the 1's complement.
459 // Note: The condition code is neither preserved nor correctly set by this code!!!
460 // Note: (wide == false) does not protect the high order half of the target register
461 // from alteration. It only serves as optimization hint for 32-bit results.
462 void MacroAssembler::not_(Register r1, Register r2, bool wide) {
463
464 if ((r2 == noreg) || (r2 == r1)) { // Calc 1's complement in place.
465 z_xilf(r1, -1);
466 if (wide) {
467 z_xihf(r1, -1);
468 }
469 } else { // Distinct src and dst registers.
470 load_const_optimized(r1, -1);
471 z_xgr(r1, r2);
472 }
473 }
474
475 unsigned long MacroAssembler::create_mask(int lBitPos, int rBitPos) {
476 assert(lBitPos >= 0, "zero is leftmost bit position");
477 assert(rBitPos <= 63, "63 is rightmost bit position");
478 assert(lBitPos <= rBitPos, "inverted selection interval");
479 return (lBitPos == 0 ? (unsigned long)(-1L) : ((1UL<<(63-lBitPos+1))-1)) & (~((1UL<<(63-rBitPos))-1));
480 }
481
482 // Helper function for the "Rotate_then_<logicalOP>" emitters.
483 // Rotate src, then mask register contents such that only bits in range survive.
484 // For oneBits == false, all bits not in range are set to 0. Useful for deleting all bits outside range.
485 // For oneBits == true, all bits not in range are set to 1. Useful for preserving all bits outside range.
486 // The caller must ensure that the selected range only contains bits with defined value.
487 void MacroAssembler::rotate_then_mask(Register dst, Register src, int lBitPos, int rBitPos,
488 int nRotate, bool src32bit, bool dst32bit, bool oneBits) {
489 assert(!(dst32bit && lBitPos < 32), "selection interval out of range for int destination");
490 bool sll4rll = (nRotate >= 0) && (nRotate <= (63-rBitPos)); // Substitute SLL(G) for RLL(G).
491 bool srl4rll = (nRotate < 0) && (-nRotate <= lBitPos); // Substitute SRL(G) for RLL(G).
492 // Pre-determine which parts of dst will be zero after shift/rotate.
493 bool llZero = sll4rll && (nRotate >= 16);
494 bool lhZero = (sll4rll && (nRotate >= 32)) || (srl4rll && (nRotate <= -48));
495 bool lfZero = llZero && lhZero;
496 bool hlZero = (sll4rll && (nRotate >= 48)) || (srl4rll && (nRotate <= -32));
497 bool hhZero = (srl4rll && (nRotate <= -16));
498 bool hfZero = hlZero && hhZero;
499
500 // rotate then mask src operand.
501 // if oneBits == true, all bits outside selected range are 1s.
502 // if oneBits == false, all bits outside selected range are 0s.
503 if (src32bit) { // There might be garbage in the upper 32 bits which will get masked away.
504 if (dst32bit) {
505 z_rll(dst, src, nRotate); // Copy and rotate, upper half of reg remains undisturbed.
506 } else {
507 if (sll4rll) { z_sllg(dst, src, nRotate); }
508 else if (srl4rll) { z_srlg(dst, src, -nRotate); }
509 else { z_rllg(dst, src, nRotate); }
510 }
511 } else {
512 if (sll4rll) { z_sllg(dst, src, nRotate); }
513 else if (srl4rll) { z_srlg(dst, src, -nRotate); }
514 else { z_rllg(dst, src, nRotate); }
515 }
516
517 unsigned long range_mask = create_mask(lBitPos, rBitPos);
518 unsigned int range_mask_h = (unsigned int)(range_mask >> 32);
519 unsigned int range_mask_l = (unsigned int)range_mask;
520 unsigned short range_mask_hh = (unsigned short)(range_mask >> 48);
521 unsigned short range_mask_hl = (unsigned short)(range_mask >> 32);
522 unsigned short range_mask_lh = (unsigned short)(range_mask >> 16);
523 unsigned short range_mask_ll = (unsigned short)range_mask;
524 // Works for z9 and newer H/W.
525 if (oneBits) {
526 if ((~range_mask_l) != 0) { z_oilf(dst, ~range_mask_l); } // All bits outside range become 1s.
527 if (((~range_mask_h) != 0) && !dst32bit) { z_oihf(dst, ~range_mask_h); }
528 } else {
529 // All bits outside range become 0s
530 if (((~range_mask_l) != 0) && !lfZero) {
531 z_nilf(dst, range_mask_l);
532 }
533 if (((~range_mask_h) != 0) && !dst32bit && !hfZero) {
534 z_nihf(dst, range_mask_h);
535 }
536 }
537 }
538
539 // Rotate src, then insert selected range from rotated src into dst.
540 // Clear dst before, if requested.
541 void MacroAssembler::rotate_then_insert(Register dst, Register src, int lBitPos, int rBitPos,
542 int nRotate, bool clear_dst) {
543 // This version does not depend on src being zero-extended int2long.
544 nRotate &= 0x003f; // For risbg, pretend it's an unsigned value.
545 z_risbg(dst, src, lBitPos, rBitPos, nRotate, clear_dst); // Rotate, then insert selected, clear the rest.
546 }
547
548 // Rotate src, then and selected range from rotated src into dst.
549 // Set condition code only if so requested. Otherwise it is unpredictable.
550 // See performance note in macroAssembler_s390.hpp for important information.
551 void MacroAssembler::rotate_then_and(Register dst, Register src, int lBitPos, int rBitPos,
552 int nRotate, bool test_only) {
553 guarantee(!test_only, "Emitter not fit for test_only instruction variant.");
554 // This version does not depend on src being zero-extended int2long.
555 nRotate &= 0x003f; // For risbg, pretend it's an unsigned value.
556 z_rxsbg(dst, src, lBitPos, rBitPos, nRotate, test_only); // Rotate, then xor selected.
557 }
558
559 // Rotate src, then or selected range from rotated src into dst.
560 // Set condition code only if so requested. Otherwise it is unpredictable.
561 // See performance note in macroAssembler_s390.hpp for important information.
562 void MacroAssembler::rotate_then_or(Register dst, Register src, int lBitPos, int rBitPos,
563 int nRotate, bool test_only) {
564 guarantee(!test_only, "Emitter not fit for test_only instruction variant.");
565 // This version does not depend on src being zero-extended int2long.
566 nRotate &= 0x003f; // For risbg, pretend it's an unsigned value.
567 z_rosbg(dst, src, lBitPos, rBitPos, nRotate, test_only); // Rotate, then xor selected.
568 }
569
570 // Rotate src, then xor selected range from rotated src into dst.
571 // Set condition code only if so requested. Otherwise it is unpredictable.
572 // See performance note in macroAssembler_s390.hpp for important information.
573 void MacroAssembler::rotate_then_xor(Register dst, Register src, int lBitPos, int rBitPos,
574 int nRotate, bool test_only) {
575 guarantee(!test_only, "Emitter not fit for test_only instruction variant.");
576 // This version does not depend on src being zero-extended int2long.
577 nRotate &= 0x003f; // For risbg, pretend it's an unsigned value.
578 z_rxsbg(dst, src, lBitPos, rBitPos, nRotate, test_only); // Rotate, then xor selected.
579 }
580
581 void MacroAssembler::add64(Register r1, RegisterOrConstant inc) {
582 if (inc.is_register()) {
583 z_agr(r1, inc.as_register());
584 } else { // constant
585 intptr_t imm = inc.as_constant();
586 add2reg(r1, imm);
587 }
588 }
589 // Helper function to multiply the 64bit contents of a register by a 16bit constant.
590 // The optimization tries to avoid the mghi instruction, since it uses the FPU for
591 // calculation and is thus rather slow.
592 //
593 // There is no handling for special cases, e.g. cval==0 or cval==1.
594 //
595 // Returns len of generated code block.
596 unsigned int MacroAssembler::mul_reg64_const16(Register rval, Register work, int cval) {
597 int block_start = offset();
598
599 bool sign_flip = cval < 0;
600 cval = sign_flip ? -cval : cval;
601
602 BLOCK_COMMENT("Reg64*Con16 {");
603
604 int bit1 = cval & -cval;
605 if (bit1 == cval) {
606 z_sllg(rval, rval, exact_log2(bit1));
607 if (sign_flip) { z_lcgr(rval, rval); }
608 } else {
609 int bit2 = (cval-bit1) & -(cval-bit1);
610 if ((bit1+bit2) == cval) {
611 z_sllg(work, rval, exact_log2(bit1));
612 z_sllg(rval, rval, exact_log2(bit2));
613 z_agr(rval, work);
614 if (sign_flip) { z_lcgr(rval, rval); }
615 } else {
616 if (sign_flip) { z_mghi(rval, -cval); }
617 else { z_mghi(rval, cval); }
618 }
619 }
620 BLOCK_COMMENT("} Reg64*Con16");
621
622 int block_end = offset();
623 return block_end - block_start;
624 }
625
626 // Generic operation r1 := r2 + imm.
627 //
628 // Should produce the best code for each supported CPU version.
629 // r2 == noreg yields r1 := r1 + imm
630 // imm == 0 emits either no instruction or r1 := r2 !
631 // NOTES: 1) Don't use this function where fixed sized
632 // instruction sequences are required!!!
633 // 2) Don't use this function if condition code
634 // setting is required!
635 // 3) Despite being declared as int64_t, the parameter imm
636 // must be a simm_32 value (= signed 32-bit integer).
637 void MacroAssembler::add2reg(Register r1, int64_t imm, Register r2) {
638 assert(Immediate::is_simm32(imm), "probably an implicit conversion went wrong");
639
640 if (r2 == noreg) { r2 = r1; }
641
642 // Handle special case imm == 0.
643 if (imm == 0) {
644 lgr_if_needed(r1, r2);
645 // Nothing else to do.
646 return;
647 }
648
649 if (!PreferLAoverADD || (r2 == Z_R0)) {
650 bool distinctOpnds = VM_Version::has_DistinctOpnds();
651
652 // Can we encode imm in 16 bits signed?
653 if (Immediate::is_simm16(imm)) {
654 if (r1 == r2) {
655 z_aghi(r1, imm);
656 return;
657 }
658 if (distinctOpnds) {
659 z_aghik(r1, r2, imm);
660 return;
661 }
662 lgr_if_needed(r1, r2);
663 z_aghi(r1, imm);
664 return;
665 }
666 } else {
667 // Can we encode imm in 12 bits unsigned?
668 if (Displacement::is_shortDisp(imm)) {
669 z_la(r1, imm, r2);
670 return;
671 }
672 // Can we encode imm in 20 bits signed?
673 if (Displacement::is_validDisp(imm)) {
674 // Always use LAY instruction, so we don't need the tmp register.
675 z_lay(r1, imm, r2);
676 return;
677 }
678
679 }
680
681 // Can handle it (all possible values) with long immediates.
682 lgr_if_needed(r1, r2);
683 z_agfi(r1, imm);
684 }
685
686 void MacroAssembler::add2reg_32(Register r1, int64_t imm, Register r2) {
687 assert(Immediate::is_simm32(imm), "probably an implicit conversion went wrong");
688
689 if (r2 == noreg) { r2 = r1; }
690
691 // Handle special case imm == 0.
692 if (imm == 0) {
693 lr_if_needed(r1, r2);
694 // Nothing else to do.
695 return;
696 }
697
698 if (Immediate::is_simm16(imm)) {
699 if (r1 == r2){
700 z_ahi(r1, imm);
701 return;
702 }
703 if (VM_Version::has_DistinctOpnds()) {
704 z_ahik(r1, r2, imm);
705 return;
706 }
707 lr_if_needed(r1, r2);
708 z_ahi(r1, imm);
709 return;
710 }
711
712 // imm is simm32
713 lr_if_needed(r1, r2);
714 z_afi(r1, imm);
715 }
716
717 // Generic operation r := b + x + d
718 //
719 // Addition of several operands with address generation semantics - sort of:
720 // - no restriction on the registers. Any register will do for any operand.
721 // - x == noreg: operand will be disregarded.
722 // - b == noreg: will use (contents of) result reg as operand (r := r + d).
723 // - x == Z_R0: just disregard
724 // - b == Z_R0: use as operand. This is not address generation semantics!!!
725 //
726 // The same restrictions as on add2reg() are valid!!!
727 void MacroAssembler::add2reg_with_index(Register r, int64_t d, Register x, Register b) {
728 assert(Immediate::is_simm32(d), "probably an implicit conversion went wrong");
729
730 if (x == noreg) { x = Z_R0; }
731 if (b == noreg) { b = r; }
732
733 // Handle special case x == R0.
734 if (x == Z_R0) {
735 // Can simply add the immediate value to the base register.
736 add2reg(r, d, b);
737 return;
738 }
739
740 if (!PreferLAoverADD || (b == Z_R0)) {
741 bool distinctOpnds = VM_Version::has_DistinctOpnds();
742 // Handle special case d == 0.
743 if (d == 0) {
744 if (b == x) { z_sllg(r, b, 1); return; }
745 if (r == x) { z_agr(r, b); return; }
746 if (r == b) { z_agr(r, x); return; }
747 if (distinctOpnds) { z_agrk(r, x, b); return; }
748 z_lgr(r, b);
749 z_agr(r, x);
750 } else {
751 if (x == b) { z_sllg(r, x, 1); }
752 else if (r == x) { z_agr(r, b); }
753 else if (r == b) { z_agr(r, x); }
754 else if (distinctOpnds) { z_agrk(r, x, b); }
755 else {
756 z_lgr(r, b);
757 z_agr(r, x);
758 }
759 add2reg(r, d);
760 }
761 } else {
762 // Can we encode imm in 12 bits unsigned?
763 if (Displacement::is_shortDisp(d)) {
764 z_la(r, d, x, b);
765 return;
766 }
767 // Can we encode imm in 20 bits signed?
768 if (Displacement::is_validDisp(d)) {
769 z_lay(r, d, x, b);
770 return;
771 }
772 z_la(r, 0, x, b);
773 add2reg(r, d);
774 }
775 }
776
777 // Generic emitter (32bit) for direct memory increment.
778 // For optimal code, do not specify Z_R0 as temp register.
779 void MacroAssembler::add2mem_32(const Address &a, int64_t imm, Register tmp) {
780 if (VM_Version::has_MemWithImmALUOps() && Immediate::is_simm8(imm)) {
781 z_asi(a, imm);
782 } else {
783 z_lgf(tmp, a);
784 add2reg(tmp, imm);
785 z_st(tmp, a);
786 }
787 }
788
789 void MacroAssembler::add2mem_64(const Address &a, int64_t imm, Register tmp) {
790 if (VM_Version::has_MemWithImmALUOps() && Immediate::is_simm8(imm)) {
791 z_agsi(a, imm);
792 } else {
793 z_lg(tmp, a);
794 add2reg(tmp, imm);
795 z_stg(tmp, a);
796 }
797 }
798
799 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed) {
800 switch (size_in_bytes) {
801 case 8: z_lg(dst, src); break;
802 case 4: is_signed ? z_lgf(dst, src) : z_llgf(dst, src); break;
803 case 2: is_signed ? z_lgh(dst, src) : z_llgh(dst, src); break;
804 case 1: is_signed ? z_lgb(dst, src) : z_llgc(dst, src); break;
805 default: ShouldNotReachHere();
806 }
807 }
808
809 void MacroAssembler::store_sized_value(Register src, Address dst, size_t size_in_bytes) {
810 switch (size_in_bytes) {
811 case 8: z_stg(src, dst); break;
812 case 4: z_st(src, dst); break;
813 case 2: z_sth(src, dst); break;
814 case 1: z_stc(src, dst); break;
815 default: ShouldNotReachHere();
816 }
817 }
818
819 // Split a si20 offset (20bit, signed) into an ui12 offset (12bit, unsigned) and
820 // a high-order summand in register tmp.
821 //
822 // return value: < 0: No split required, si20 actually has property uimm12.
823 // >= 0: Split performed. Use return value as uimm12 displacement and
824 // tmp as index register.
825 int MacroAssembler::split_largeoffset(int64_t si20_offset, Register tmp, bool fixed_codelen, bool accumulate) {
826 assert(Immediate::is_simm20(si20_offset), "sanity");
827 int lg_off = (int)si20_offset & 0x0fff; // Punch out low-order 12 bits, always positive.
828 int ll_off = (int)si20_offset & ~0x0fff; // Force low-order 12 bits to zero.
829 assert((Displacement::is_shortDisp(si20_offset) && (ll_off == 0)) ||
830 !Displacement::is_shortDisp(si20_offset), "unexpected offset values");
831 assert((lg_off+ll_off) == si20_offset, "offset splitup error");
832
833 Register work = accumulate? Z_R0 : tmp;
834
835 if (fixed_codelen) { // Len of code = 10 = 4 + 6.
836 z_lghi(work, ll_off>>12); // Implicit sign extension.
837 z_slag(work, work, 12);
838 } else { // Len of code = 0..10.
839 if (ll_off == 0) { return -1; }
840 // ll_off has 8 significant bits (at most) plus sign.
841 if ((ll_off & 0x0000f000) == 0) { // Non-zero bits only in upper halfbyte.
842 z_llilh(work, ll_off >> 16);
843 if (ll_off < 0) { // Sign-extension required.
844 z_lgfr(work, work);
845 }
846 } else {
847 if ((ll_off & 0x000f0000) == 0) { // Non-zero bits only in lower halfbyte.
848 z_llill(work, ll_off);
849 } else { // Non-zero bits in both halfbytes.
850 z_lghi(work, ll_off>>12); // Implicit sign extension.
851 z_slag(work, work, 12);
852 }
853 }
854 }
855 if (accumulate) { z_algr(tmp, work); } // len of code += 4
856 return lg_off;
857 }
858
859 void MacroAssembler::load_float_largeoffset(FloatRegister t, int64_t si20, Register a, Register tmp) {
860 if (Displacement::is_validDisp(si20)) {
861 z_ley(t, si20, a);
862 } else {
863 // Fixed_codelen = true is a simple way to ensure that the size of load_float_largeoffset
864 // does not depend on si20 (scratch buffer emit size == code buffer emit size for constant
865 // pool loads).
866 bool accumulate = true;
867 bool fixed_codelen = true;
868 Register work;
869
870 if (fixed_codelen) {
871 z_lgr(tmp, a); // Lgr_if_needed not applicable due to fixed_codelen.
872 } else {
873 accumulate = (a == tmp);
874 }
875 work = tmp;
876
877 int disp12 = split_largeoffset(si20, work, fixed_codelen, accumulate);
878 if (disp12 < 0) {
879 z_le(t, si20, work);
880 } else {
881 if (accumulate) {
882 z_le(t, disp12, work);
883 } else {
884 z_le(t, disp12, work, a);
885 }
886 }
887 }
888 }
889
890 void MacroAssembler::load_double_largeoffset(FloatRegister t, int64_t si20, Register a, Register tmp) {
891 if (Displacement::is_validDisp(si20)) {
892 z_ldy(t, si20, a);
893 } else {
894 // Fixed_codelen = true is a simple way to ensure that the size of load_double_largeoffset
895 // does not depend on si20 (scratch buffer emit size == code buffer emit size for constant
896 // pool loads).
897 bool accumulate = true;
898 bool fixed_codelen = true;
899 Register work;
900
901 if (fixed_codelen) {
902 z_lgr(tmp, a); // Lgr_if_needed not applicable due to fixed_codelen.
903 } else {
904 accumulate = (a == tmp);
905 }
906 work = tmp;
907
908 int disp12 = split_largeoffset(si20, work, fixed_codelen, accumulate);
909 if (disp12 < 0) {
910 z_ld(t, si20, work);
911 } else {
912 if (accumulate) {
913 z_ld(t, disp12, work);
914 } else {
915 z_ld(t, disp12, work, a);
916 }
917 }
918 }
919 }
920
921 // PCrelative TOC access.
922 // Returns distance (in bytes) from current position to start of consts section.
923 // Returns 0 (zero) if no consts section exists or if it has size zero.
924 long MacroAssembler::toc_distance() {
925 CodeSection* cs = code()->consts();
926 return (long)((cs != nullptr) ? cs->start()-pc() : 0);
927 }
928
929 // Implementation on x86/sparc assumes that constant and instruction section are
930 // adjacent, but this doesn't hold. Two special situations may occur, that we must
931 // be able to handle:
932 // 1. const section may be located apart from the inst section.
933 // 2. const section may be empty
934 // In both cases, we use the const section's start address to compute the "TOC",
935 // this seems to occur only temporarily; in the final step we always seem to end up
936 // with the pc-relatice variant.
937 //
938 // PC-relative offset could be +/-2**32 -> use long for disp
939 // Furthermore: makes no sense to have special code for
940 // adjacent const and inst sections.
941 void MacroAssembler::load_toc(Register Rtoc) {
942 // Simply use distance from start of const section (should be patched in the end).
943 long disp = toc_distance();
944
945 RelocationHolder rspec = internal_word_Relocation::spec(pc() + disp);
946 relocate(rspec);
947 z_larl(Rtoc, RelAddr::pcrel_off32(disp)); // Offset is in halfwords.
948 }
949
950 // PCrelative TOC access.
951 // Load from anywhere pcrelative (with relocation of load instr)
952 void MacroAssembler::load_long_pcrelative(Register Rdst, address dataLocation) {
953 address pc = this->pc();
954 ptrdiff_t total_distance = dataLocation - pc;
955 RelocationHolder rspec = internal_word_Relocation::spec(dataLocation);
956
957 assert((total_distance & 0x01L) == 0, "halfword alignment is mandatory");
958 assert(total_distance != 0, "sanity");
959
960 // Some extra safety net.
961 if (!RelAddr::is_in_range_of_RelAddr32(total_distance)) {
962 guarantee(RelAddr::is_in_range_of_RelAddr32(total_distance), "load_long_pcrelative can't handle distance " INTPTR_FORMAT, total_distance);
963 }
964
965 (this)->relocate(rspec, relocInfo::pcrel_addr_format);
966 z_lgrl(Rdst, RelAddr::pcrel_off32(total_distance));
967 }
968
969
970 // PCrelative TOC access.
971 // Load from anywhere pcrelative (with relocation of load instr)
972 // loaded addr has to be relocated when added to constant pool.
973 void MacroAssembler::load_addr_pcrelative(Register Rdst, address addrLocation) {
974 address pc = this->pc();
975 ptrdiff_t total_distance = addrLocation - pc;
976 RelocationHolder rspec = internal_word_Relocation::spec(addrLocation);
977
978 assert((total_distance & 0x01L) == 0, "halfword alignment is mandatory");
979
980 // Some extra safety net.
981 if (!RelAddr::is_in_range_of_RelAddr32(total_distance)) {
982 guarantee(RelAddr::is_in_range_of_RelAddr32(total_distance), "load_long_pcrelative can't handle distance " INTPTR_FORMAT, total_distance);
983 }
984
985 (this)->relocate(rspec, relocInfo::pcrel_addr_format);
986 z_lgrl(Rdst, RelAddr::pcrel_off32(total_distance));
987 }
988
989 // Generic operation: load a value from memory and test.
990 // CondCode indicates the sign (<0, ==0, >0) of the loaded value.
991 void MacroAssembler::load_and_test_byte(Register dst, const Address &a) {
992 z_lb(dst, a);
993 z_ltr(dst, dst);
994 }
995
996 void MacroAssembler::load_and_test_short(Register dst, const Address &a) {
997 int64_t disp = a.disp20();
998 if (Displacement::is_shortDisp(disp)) {
999 z_lh(dst, a);
1000 } else if (Displacement::is_longDisp(disp)) {
1001 z_lhy(dst, a);
1002 } else {
1003 guarantee(false, "displacement out of range");
1004 }
1005 z_ltr(dst, dst);
1006 }
1007
1008 void MacroAssembler::load_and_test_int(Register dst, const Address &a) {
1009 z_lt(dst, a);
1010 }
1011
1012 void MacroAssembler::load_and_test_int2long(Register dst, const Address &a) {
1013 z_ltgf(dst, a);
1014 }
1015
1016 void MacroAssembler::load_and_test_long(Register dst, const Address &a) {
1017 z_ltg(dst, a);
1018 }
1019
1020 // Test a bit in memory for 2 byte datatype.
1021 void MacroAssembler::testbit_ushort(const Address &a, unsigned int bit) {
1022 assert(a.index() == noreg, "no index reg allowed in testbit");
1023 if (bit <= 7) {
1024 z_tm(a.disp() + 1, a.base(), 1 << bit);
1025 } else if (bit <= 15) {
1026 z_tm(a.disp() + 0, a.base(), 1 << (bit - 8));
1027 } else {
1028 ShouldNotReachHere();
1029 }
1030 }
1031
1032 // Test a bit in memory.
1033 void MacroAssembler::testbit(const Address &a, unsigned int bit) {
1034 assert(a.index() == noreg, "no index reg allowed in testbit");
1035 if (bit <= 7) {
1036 z_tm(a.disp() + 3, a.base(), 1 << bit);
1037 } else if (bit <= 15) {
1038 z_tm(a.disp() + 2, a.base(), 1 << (bit - 8));
1039 } else if (bit <= 23) {
1040 z_tm(a.disp() + 1, a.base(), 1 << (bit - 16));
1041 } else if (bit <= 31) {
1042 z_tm(a.disp() + 0, a.base(), 1 << (bit - 24));
1043 } else {
1044 ShouldNotReachHere();
1045 }
1046 }
1047
1048 // Test a bit in a register. Result is reflected in CC.
1049 void MacroAssembler::testbit(Register r, unsigned int bitPos) {
1050 if (bitPos < 16) {
1051 z_tmll(r, 1U<<bitPos);
1052 } else if (bitPos < 32) {
1053 z_tmlh(r, 1U<<(bitPos-16));
1054 } else if (bitPos < 48) {
1055 z_tmhl(r, 1U<<(bitPos-32));
1056 } else if (bitPos < 64) {
1057 z_tmhh(r, 1U<<(bitPos-48));
1058 } else {
1059 ShouldNotReachHere();
1060 }
1061 }
1062
1063 void MacroAssembler::prefetch_read(Address a) {
1064 z_pfd(1, a.disp20(), a.indexOrR0(), a.base());
1065 }
1066 void MacroAssembler::prefetch_update(Address a) {
1067 z_pfd(2, a.disp20(), a.indexOrR0(), a.base());
1068 }
1069
1070 // Clear a register, i.e. load const zero into reg.
1071 // Return len (in bytes) of generated instruction(s).
1072 // whole_reg: Clear 64 bits if true, 32 bits otherwise.
1073 // set_cc: Use instruction that sets the condition code, if true.
1074 int MacroAssembler::clear_reg(Register r, bool whole_reg, bool set_cc) {
1075 unsigned int start_off = offset();
1076 if (whole_reg) {
1077 set_cc ? z_xgr(r, r) : z_laz(r, 0, Z_R0);
1078 } else { // Only 32bit register.
1079 set_cc ? z_xr(r, r) : z_lhi(r, 0);
1080 }
1081 return offset() - start_off;
1082 }
1083
1084 #ifdef ASSERT
1085 int MacroAssembler::preset_reg(Register r, unsigned long pattern, int pattern_len) {
1086 switch (pattern_len) {
1087 case 1:
1088 pattern = (pattern & 0x000000ff) | ((pattern & 0x000000ff)<<8);
1089 case 2:
1090 pattern = (pattern & 0x0000ffff) | ((pattern & 0x0000ffff)<<16);
1091 case 4:
1092 pattern = (pattern & 0xffffffffL) | ((pattern & 0xffffffffL)<<32);
1093 case 8:
1094 return load_const_optimized_rtn_len(r, pattern, true);
1095 break;
1096 default:
1097 guarantee(false, "preset_reg: bad len");
1098 }
1099 return 0;
1100 }
1101 #endif
1102
1103 // addr: Address descriptor of memory to clear. Index register will not be used!
1104 // size: Number of bytes to clear.
1105 // condition code will not be preserved.
1106 // !!! DO NOT USE THEM FOR ATOMIC MEMORY CLEARING !!!
1107 // !!! Use store_const() instead !!!
1108 void MacroAssembler::clear_mem(const Address& addr, unsigned int size) {
1109 guarantee((addr.disp() + size) <= 4096, "MacroAssembler::clear_mem: size too large");
1110
1111 switch (size) {
1112 case 0:
1113 return;
1114 case 1:
1115 z_mvi(addr, 0);
1116 return;
1117 case 2:
1118 z_mvhhi(addr, 0);
1119 return;
1120 case 4:
1121 z_mvhi(addr, 0);
1122 return;
1123 case 8:
1124 z_mvghi(addr, 0);
1125 return;
1126 default: ; // Fallthru to xc.
1127 }
1128
1129 // Caution: the emitter with Address operands does implicitly decrement the length
1130 if (size <= 256) {
1131 z_xc(addr, size, addr);
1132 } else {
1133 unsigned int offset = addr.disp();
1134 unsigned int incr = 256;
1135 for (unsigned int i = 0; i <= size-incr; i += incr) {
1136 z_xc(offset, incr - 1, addr.base(), offset, addr.base());
1137 offset += incr;
1138 }
1139 unsigned int rest = size - (offset - addr.disp());
1140 if (size > 0) {
1141 z_xc(offset, rest-1, addr.base(), offset, addr.base());
1142 }
1143 }
1144 }
1145
1146 void MacroAssembler::align(int modulus) {
1147 align(modulus, offset());
1148 }
1149
1150 void MacroAssembler::align(int modulus, int target) {
1151 assert(((modulus % 2 == 0) && (target % 2 == 0)), "needs to be even");
1152 int delta = target - offset();
1153 while ((offset() + delta) % modulus != 0) z_nop();
1154 }
1155
1156 // Special version for non-relocateable code if required alignment
1157 // is larger than CodeEntryAlignment.
1158 void MacroAssembler::align_address(int modulus) {
1159 while ((uintptr_t)pc() % modulus != 0) z_nop();
1160 }
1161
1162 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
1163 Register temp_reg,
1164 int64_t extra_slot_offset) {
1165 // On Z, we can have index and disp in an Address. So don't call argument_offset,
1166 // which issues an unnecessary add instruction.
1167 int stackElementSize = Interpreter::stackElementSize;
1168 int64_t offset = extra_slot_offset * stackElementSize;
1169 const Register argbase = Z_esp;
1170 if (arg_slot.is_constant()) {
1171 offset += arg_slot.as_constant() * stackElementSize;
1172 return Address(argbase, offset);
1173 }
1174 // else
1175 assert(temp_reg != noreg, "must specify");
1176 assert(temp_reg != Z_ARG1, "base and index are conflicting");
1177 z_sllg(temp_reg, arg_slot.as_register(), exact_log2(stackElementSize)); // tempreg = arg_slot << 3
1178 return Address(argbase, temp_reg, offset);
1179 }
1180
1181
1182 //===================================================================
1183 //=== START C O N S T A N T S I N C O D E S T R E A M ===
1184 //===================================================================
1185 //=== P A T CH A B L E C O N S T A N T S ===
1186 //===================================================================
1187
1188
1189 //---------------------------------------------------
1190 // Load (patchable) constant into register
1191 //---------------------------------------------------
1192
1193
1194 // Load absolute address (and try to optimize).
1195 // Note: This method is usable only for position-fixed code,
1196 // referring to a position-fixed target location.
1197 // If not so, relocations and patching must be used.
1198 void MacroAssembler::load_absolute_address(Register d, address addr) {
1199 assert(addr != nullptr, "should not happen");
1200 BLOCK_COMMENT("load_absolute_address:");
1201 if (addr == nullptr) {
1202 z_larl(d, pc()); // Dummy emit for size calc.
1203 return;
1204 }
1205
1206 if (RelAddr::is_in_range_of_RelAddr32(addr, pc())) {
1207 z_larl(d, addr);
1208 return;
1209 }
1210
1211 load_const_optimized(d, (long)addr);
1212 }
1213
1214 // Load a 64bit constant.
1215 // Patchable code sequence, but not atomically patchable.
1216 // Make sure to keep code size constant -> no value-dependent optimizations.
1217 // Do not kill condition code.
1218 void MacroAssembler::load_const(Register t, long x) {
1219 // Note: Right shift is only cleanly defined for unsigned types
1220 // or for signed types with nonnegative values.
1221 Assembler::z_iihf(t, (long)((unsigned long)x >> 32));
1222 Assembler::z_iilf(t, (long)((unsigned long)x & 0xffffffffUL));
1223 }
1224
1225 // Load a 32bit constant into a 64bit register, sign-extend or zero-extend.
1226 // Patchable code sequence, but not atomically patchable.
1227 // Make sure to keep code size constant -> no value-dependent optimizations.
1228 // Do not kill condition code.
1229 void MacroAssembler::load_const_32to64(Register t, int64_t x, bool sign_extend) {
1230 if (sign_extend) { Assembler::z_lgfi(t, x); }
1231 else { Assembler::z_llilf(t, x); }
1232 }
1233
1234 // Load narrow oop constant, no decompression.
1235 void MacroAssembler::load_narrow_oop(Register t, narrowOop a) {
1236 assert(UseCompressedOops, "must be on to call this method");
1237 load_const_32to64(t, CompressedOops::narrow_oop_value(a), false /*sign_extend*/);
1238 }
1239
1240 // Load narrow klass constant, compression required.
1241 void MacroAssembler::load_narrow_klass(Register t, Klass* k) {
1242 narrowKlass encoded_k = CompressedKlassPointers::encode(k);
1243 load_const_32to64(t, encoded_k, false /*sign_extend*/);
1244 }
1245
1246 //------------------------------------------------------
1247 // Compare (patchable) constant with register.
1248 //------------------------------------------------------
1249
1250 // Compare narrow oop in reg with narrow oop constant, no decompression.
1251 void MacroAssembler::compare_immediate_narrow_oop(Register oop1, narrowOop oop2) {
1252 assert(UseCompressedOops, "must be on to call this method");
1253
1254 Assembler::z_clfi(oop1, CompressedOops::narrow_oop_value(oop2));
1255 }
1256
1257 // Compare narrow oop in reg with narrow oop constant, no decompression.
1258 void MacroAssembler::compare_immediate_narrow_klass(Register klass1, Klass* klass2) {
1259 narrowKlass encoded_k = CompressedKlassPointers::encode(klass2);
1260
1261 Assembler::z_clfi(klass1, encoded_k);
1262 }
1263
1264 //----------------------------------------------------------
1265 // Check which kind of load_constant we have here.
1266 //----------------------------------------------------------
1267
1268 // Detection of CPU version dependent load_const sequence.
1269 // The detection is valid only for code sequences generated by load_const,
1270 // not load_const_optimized.
1271 bool MacroAssembler::is_load_const(address a) {
1272 unsigned long inst1, inst2;
1273 unsigned int len1, len2;
1274
1275 len1 = get_instruction(a, &inst1);
1276 len2 = get_instruction(a + len1, &inst2);
1277
1278 return is_z_iihf(inst1) && is_z_iilf(inst2);
1279 }
1280
1281 // Detection of CPU version dependent load_const_32to64 sequence.
1282 // Mostly used for narrow oops and narrow Klass pointers.
1283 // The detection is valid only for code sequences generated by load_const_32to64.
1284 bool MacroAssembler::is_load_const_32to64(address pos) {
1285 unsigned long inst1, inst2;
1286 unsigned int len1;
1287
1288 len1 = get_instruction(pos, &inst1);
1289 return is_z_llilf(inst1);
1290 }
1291
1292 // Detection of compare_immediate_narrow sequence.
1293 // The detection is valid only for code sequences generated by compare_immediate_narrow_oop.
1294 bool MacroAssembler::is_compare_immediate32(address pos) {
1295 return is_equal(pos, CLFI_ZOPC, RIL_MASK);
1296 }
1297
1298 // Detection of compare_immediate_narrow sequence.
1299 // The detection is valid only for code sequences generated by compare_immediate_narrow_oop.
1300 bool MacroAssembler::is_compare_immediate_narrow_oop(address pos) {
1301 return is_compare_immediate32(pos);
1302 }
1303
1304 // Detection of compare_immediate_narrow sequence.
1305 // The detection is valid only for code sequences generated by compare_immediate_narrow_klass.
1306 bool MacroAssembler::is_compare_immediate_narrow_klass(address pos) {
1307 return is_compare_immediate32(pos);
1308 }
1309
1310 //-----------------------------------
1311 // patch the load_constant
1312 //-----------------------------------
1313
1314 // CPU-version dependent patching of load_const.
1315 void MacroAssembler::patch_const(address a, long x) {
1316 assert(is_load_const(a), "not a load of a constant");
1317 // Note: Right shift is only cleanly defined for unsigned types
1318 // or for signed types with nonnegative values.
1319 set_imm32((address)a, (long)((unsigned long)x >> 32));
1320 set_imm32((address)(a + 6), (long)((unsigned long)x & 0xffffffffUL));
1321 }
1322
1323 // Patching the value of CPU version dependent load_const_32to64 sequence.
1324 // The passed ptr MUST be in compressed format!
1325 int MacroAssembler::patch_load_const_32to64(address pos, int64_t np) {
1326 assert(is_load_const_32to64(pos), "not a load of a narrow ptr (oop or klass)");
1327
1328 set_imm32(pos, np);
1329 return 6;
1330 }
1331
1332 // Patching the value of CPU version dependent compare_immediate_narrow sequence.
1333 // The passed ptr MUST be in compressed format!
1334 int MacroAssembler::patch_compare_immediate_32(address pos, int64_t np) {
1335 assert(is_compare_immediate32(pos), "not a compressed ptr compare");
1336
1337 set_imm32(pos, np);
1338 return 6;
1339 }
1340
1341 // Patching the immediate value of CPU version dependent load_narrow_oop sequence.
1342 // The passed ptr must NOT be in compressed format!
1343 int MacroAssembler::patch_load_narrow_oop(address pos, oop o) {
1344 assert(UseCompressedOops, "Can only patch compressed oops");
1345 return patch_load_const_32to64(pos, CompressedOops::narrow_oop_value(o));
1346 }
1347
1348 // Patching the immediate value of CPU version dependent load_narrow_klass sequence.
1349 // The passed ptr must NOT be in compressed format!
1350 int MacroAssembler::patch_load_narrow_klass(address pos, Klass* k) {
1351 narrowKlass nk = CompressedKlassPointers::encode(k);
1352 return patch_load_const_32to64(pos, nk);
1353 }
1354
1355 // Patching the immediate value of CPU version dependent compare_immediate_narrow_oop sequence.
1356 // The passed ptr must NOT be in compressed format!
1357 int MacroAssembler::patch_compare_immediate_narrow_oop(address pos, oop o) {
1358 assert(UseCompressedOops, "Can only patch compressed oops");
1359 return patch_compare_immediate_32(pos, CompressedOops::narrow_oop_value(o));
1360 }
1361
1362 // Patching the immediate value of CPU version dependent compare_immediate_narrow_klass sequence.
1363 // The passed ptr must NOT be in compressed format!
1364 int MacroAssembler::patch_compare_immediate_narrow_klass(address pos, Klass* k) {
1365 narrowKlass nk = CompressedKlassPointers::encode(k);
1366 return patch_compare_immediate_32(pos, nk);
1367 }
1368
1369 //------------------------------------------------------------------------
1370 // Extract the constant from a load_constant instruction stream.
1371 //------------------------------------------------------------------------
1372
1373 // Get constant from a load_const sequence.
1374 long MacroAssembler::get_const(address a) {
1375 assert(is_load_const(a), "not a load of a constant");
1376 unsigned long x;
1377 x = (((unsigned long) (get_imm32(a,0) & 0xffffffff)) << 32);
1378 x |= (((unsigned long) (get_imm32(a,1) & 0xffffffff)));
1379 return (long) x;
1380 }
1381
1382 //--------------------------------------
1383 // Store a constant in memory.
1384 //--------------------------------------
1385
1386 // General emitter to move a constant to memory.
1387 // The store is atomic.
1388 // o Address must be given in RS format (no index register)
1389 // o Displacement should be 12bit unsigned for efficiency. 20bit signed also supported.
1390 // o Constant can be 1, 2, 4, or 8 bytes, signed or unsigned.
1391 // o Memory slot can be 1, 2, 4, or 8 bytes, signed or unsigned.
1392 // o Memory slot must be at least as wide as constant, will assert otherwise.
1393 // o Signed constants will sign-extend, unsigned constants will zero-extend to slot width.
1394 int MacroAssembler::store_const(const Address &dest, long imm,
1395 unsigned int lm, unsigned int lc,
1396 Register scratch) {
1397 int64_t disp = dest.disp();
1398 Register base = dest.base();
1399 assert(!dest.has_index(), "not supported");
1400 assert((lm==1)||(lm==2)||(lm==4)||(lm==8), "memory length not supported");
1401 assert((lc==1)||(lc==2)||(lc==4)||(lc==8), "constant length not supported");
1402 assert(lm>=lc, "memory slot too small");
1403 assert(lc==8 || Immediate::is_simm(imm, lc*8), "const out of range");
1404 assert(Displacement::is_validDisp(disp), "displacement out of range");
1405
1406 bool is_shortDisp = Displacement::is_shortDisp(disp);
1407 int store_offset = -1;
1408
1409 // For target len == 1 it's easy.
1410 if (lm == 1) {
1411 store_offset = offset();
1412 if (is_shortDisp) {
1413 z_mvi(disp, base, imm);
1414 return store_offset;
1415 } else {
1416 z_mviy(disp, base, imm);
1417 return store_offset;
1418 }
1419 }
1420
1421 // All the "good stuff" takes an unsigned displacement.
1422 if (is_shortDisp) {
1423 // NOTE: Cannot use clear_mem for imm==0, because it is not atomic.
1424
1425 store_offset = offset();
1426 switch (lm) {
1427 case 2: // Lc == 1 handled correctly here, even for unsigned. Instruction does no widening.
1428 z_mvhhi(disp, base, imm);
1429 return store_offset;
1430 case 4:
1431 if (Immediate::is_simm16(imm)) {
1432 z_mvhi(disp, base, imm);
1433 return store_offset;
1434 }
1435 break;
1436 case 8:
1437 if (Immediate::is_simm16(imm)) {
1438 z_mvghi(disp, base, imm);
1439 return store_offset;
1440 }
1441 break;
1442 default:
1443 ShouldNotReachHere();
1444 break;
1445 }
1446 }
1447
1448 // Can't optimize, so load value and store it.
1449 guarantee(scratch != noreg, " need a scratch register here !");
1450 if (imm != 0) {
1451 load_const_optimized(scratch, imm); // Preserves CC anyway.
1452 } else {
1453 // Leave CC alone!!
1454 (void) clear_reg(scratch, true, false); // Indicate unused result.
1455 }
1456
1457 store_offset = offset();
1458 if (is_shortDisp) {
1459 switch (lm) {
1460 case 2:
1461 z_sth(scratch, disp, Z_R0, base);
1462 return store_offset;
1463 case 4:
1464 z_st(scratch, disp, Z_R0, base);
1465 return store_offset;
1466 case 8:
1467 z_stg(scratch, disp, Z_R0, base);
1468 return store_offset;
1469 default:
1470 ShouldNotReachHere();
1471 break;
1472 }
1473 } else {
1474 switch (lm) {
1475 case 2:
1476 z_sthy(scratch, disp, Z_R0, base);
1477 return store_offset;
1478 case 4:
1479 z_sty(scratch, disp, Z_R0, base);
1480 return store_offset;
1481 case 8:
1482 z_stg(scratch, disp, Z_R0, base);
1483 return store_offset;
1484 default:
1485 ShouldNotReachHere();
1486 break;
1487 }
1488 }
1489 return -1; // should not reach here
1490 }
1491
1492 //===================================================================
1493 //=== N O T P A T CH A B L E C O N S T A N T S ===
1494 //===================================================================
1495
1496 // Load constant x into register t with a fast instruction sequence
1497 // depending on the bits in x. Preserves CC under all circumstances.
1498 int MacroAssembler::load_const_optimized_rtn_len(Register t, long x, bool emit) {
1499 if (x == 0) {
1500 int len;
1501 if (emit) {
1502 len = clear_reg(t, true, false);
1503 } else {
1504 len = 4;
1505 }
1506 return len;
1507 }
1508
1509 if (Immediate::is_simm16(x)) {
1510 if (emit) { z_lghi(t, x); }
1511 return 4;
1512 }
1513
1514 // 64 bit value: | part1 | part2 | part3 | part4 |
1515 // At least one part is not zero!
1516 // Note: Right shift is only cleanly defined for unsigned types
1517 // or for signed types with nonnegative values.
1518 int part1 = (int)((unsigned long)x >> 48) & 0x0000ffff;
1519 int part2 = (int)((unsigned long)x >> 32) & 0x0000ffff;
1520 int part3 = (int)((unsigned long)x >> 16) & 0x0000ffff;
1521 int part4 = (int)x & 0x0000ffff;
1522 int part12 = (int)((unsigned long)x >> 32);
1523 int part34 = (int)x;
1524
1525 // Lower word only (unsigned).
1526 if (part12 == 0) {
1527 if (part3 == 0) {
1528 if (emit) z_llill(t, part4);
1529 return 4;
1530 }
1531 if (part4 == 0) {
1532 if (emit) z_llilh(t, part3);
1533 return 4;
1534 }
1535 if (emit) z_llilf(t, part34);
1536 return 6;
1537 }
1538
1539 // Upper word only.
1540 if (part34 == 0) {
1541 if (part1 == 0) {
1542 if (emit) z_llihl(t, part2);
1543 return 4;
1544 }
1545 if (part2 == 0) {
1546 if (emit) z_llihh(t, part1);
1547 return 4;
1548 }
1549 if (emit) z_llihf(t, part12);
1550 return 6;
1551 }
1552
1553 // Lower word only (signed).
1554 if ((part1 == 0x0000ffff) && (part2 == 0x0000ffff) && ((part3 & 0x00008000) != 0)) {
1555 if (emit) z_lgfi(t, part34);
1556 return 6;
1557 }
1558
1559 int len = 0;
1560
1561 if ((part1 == 0) || (part2 == 0)) {
1562 if (part1 == 0) {
1563 if (emit) z_llihl(t, part2);
1564 len += 4;
1565 } else {
1566 if (emit) z_llihh(t, part1);
1567 len += 4;
1568 }
1569 } else {
1570 if (emit) z_llihf(t, part12);
1571 len += 6;
1572 }
1573
1574 if ((part3 == 0) || (part4 == 0)) {
1575 if (part3 == 0) {
1576 if (emit) z_iill(t, part4);
1577 len += 4;
1578 } else {
1579 if (emit) z_iilh(t, part3);
1580 len += 4;
1581 }
1582 } else {
1583 if (emit) z_iilf(t, part34);
1584 len += 6;
1585 }
1586 return len;
1587 }
1588
1589 //=====================================================================
1590 //=== H I G H E R L E V E L B R A N C H E M I T T E R S ===
1591 //=====================================================================
1592
1593 // Note: In the worst case, one of the scratch registers is destroyed!!!
1594 void MacroAssembler::compare32_and_branch(Register r1, RegisterOrConstant x2, branch_condition cond, Label& lbl) {
1595 // Right operand is constant.
1596 if (x2.is_constant()) {
1597 jlong value = x2.as_constant();
1598 compare_and_branch_optimized(r1, value, cond, lbl, /*len64=*/false, /*has_sign=*/true);
1599 return;
1600 }
1601
1602 // Right operand is in register.
1603 compare_and_branch_optimized(r1, x2.as_register(), cond, lbl, /*len64=*/false, /*has_sign=*/true);
1604 }
1605
1606 // Note: In the worst case, one of the scratch registers is destroyed!!!
1607 void MacroAssembler::compareU32_and_branch(Register r1, RegisterOrConstant x2, branch_condition cond, Label& lbl) {
1608 // Right operand is constant.
1609 if (x2.is_constant()) {
1610 jlong value = x2.as_constant();
1611 compare_and_branch_optimized(r1, value, cond, lbl, /*len64=*/false, /*has_sign=*/false);
1612 return;
1613 }
1614
1615 // Right operand is in register.
1616 compare_and_branch_optimized(r1, x2.as_register(), cond, lbl, /*len64=*/false, /*has_sign=*/false);
1617 }
1618
1619 // Note: In the worst case, one of the scratch registers is destroyed!!!
1620 void MacroAssembler::compare64_and_branch(Register r1, RegisterOrConstant x2, branch_condition cond, Label& lbl) {
1621 // Right operand is constant.
1622 if (x2.is_constant()) {
1623 jlong value = x2.as_constant();
1624 compare_and_branch_optimized(r1, value, cond, lbl, /*len64=*/true, /*has_sign=*/true);
1625 return;
1626 }
1627
1628 // Right operand is in register.
1629 compare_and_branch_optimized(r1, x2.as_register(), cond, lbl, /*len64=*/true, /*has_sign=*/true);
1630 }
1631
1632 void MacroAssembler::compareU64_and_branch(Register r1, RegisterOrConstant x2, branch_condition cond, Label& lbl) {
1633 // Right operand is constant.
1634 if (x2.is_constant()) {
1635 jlong value = x2.as_constant();
1636 compare_and_branch_optimized(r1, value, cond, lbl, /*len64=*/true, /*has_sign=*/false);
1637 return;
1638 }
1639
1640 // Right operand is in register.
1641 compare_and_branch_optimized(r1, x2.as_register(), cond, lbl, /*len64=*/true, /*has_sign=*/false);
1642 }
1643
1644 // Generate an optimal branch to the branch target.
1645 // Optimal means that a relative branch (brc or brcl) is used if the
1646 // branch distance is short enough. Loading the target address into a
1647 // register and branching via reg is used as fallback only.
1648 //
1649 // Used registers:
1650 // Z_R1 - work reg. Holds branch target address.
1651 // Used in fallback case only.
1652 //
1653 // This version of branch_optimized is good for cases where the target address is known
1654 // and constant, i.e. is never changed (no relocation, no patching).
1655 void MacroAssembler::branch_optimized(Assembler::branch_condition cond, address branch_addr) {
1656 address branch_origin = pc();
1657
1658 if (RelAddr::is_in_range_of_RelAddr16(branch_addr, branch_origin)) {
1659 z_brc(cond, branch_addr);
1660 } else if (RelAddr::is_in_range_of_RelAddr32(branch_addr, branch_origin)) {
1661 z_brcl(cond, branch_addr);
1662 } else {
1663 load_const_optimized(Z_R1, branch_addr); // CC must not get killed by load_const_optimized.
1664 z_bcr(cond, Z_R1);
1665 }
1666 }
1667
1668 // This version of branch_optimized is good for cases where the target address
1669 // is potentially not yet known at the time the code is emitted.
1670 //
1671 // One very common case is a branch to an unbound label which is handled here.
1672 // The caller might know (or hope) that the branch distance is short enough
1673 // to be encoded in a 16bit relative address. In this case he will pass a
1674 // NearLabel branch_target.
1675 // Care must be taken with unbound labels. Each call to target(label) creates
1676 // an entry in the patch queue for that label to patch all references of the label
1677 // once it gets bound. Those recorded patch locations must be patchable. Otherwise,
1678 // an assertion fires at patch time.
1679 void MacroAssembler::branch_optimized(Assembler::branch_condition cond, Label& branch_target) {
1680 if (branch_target.is_bound()) {
1681 address branch_addr = target(branch_target);
1682 branch_optimized(cond, branch_addr);
1683 } else if (branch_target.is_near()) {
1684 z_brc(cond, branch_target); // Caller assures that the target will be in range for z_brc.
1685 } else {
1686 z_brcl(cond, branch_target); // Let's hope target is in range. Otherwise, we will abort at patch time.
1687 }
1688 }
1689
1690 // Generate an optimal compare and branch to the branch target.
1691 // Optimal means that a relative branch (clgrj, brc or brcl) is used if the
1692 // branch distance is short enough. Loading the target address into a
1693 // register and branching via reg is used as fallback only.
1694 //
1695 // Input:
1696 // r1 - left compare operand
1697 // r2 - right compare operand
1698 void MacroAssembler::compare_and_branch_optimized(Register r1,
1699 Register r2,
1700 Assembler::branch_condition cond,
1701 address branch_addr,
1702 bool len64,
1703 bool has_sign) {
1704 unsigned int casenum = (len64?2:0)+(has_sign?0:1);
1705
1706 address branch_origin = pc();
1707 if (VM_Version::has_CompareBranch() && RelAddr::is_in_range_of_RelAddr16(branch_addr, branch_origin)) {
1708 switch (casenum) {
1709 case 0: z_crj( r1, r2, cond, branch_addr); break;
1710 case 1: z_clrj (r1, r2, cond, branch_addr); break;
1711 case 2: z_cgrj(r1, r2, cond, branch_addr); break;
1712 case 3: z_clgrj(r1, r2, cond, branch_addr); break;
1713 default: ShouldNotReachHere(); break;
1714 }
1715 } else {
1716 switch (casenum) {
1717 case 0: z_cr( r1, r2); break;
1718 case 1: z_clr(r1, r2); break;
1719 case 2: z_cgr(r1, r2); break;
1720 case 3: z_clgr(r1, r2); break;
1721 default: ShouldNotReachHere(); break;
1722 }
1723 branch_optimized(cond, branch_addr);
1724 }
1725 }
1726
1727 // Generate an optimal compare and branch to the branch target.
1728 // Optimal means that a relative branch (clgij, brc or brcl) is used if the
1729 // branch distance is short enough. Loading the target address into a
1730 // register and branching via reg is used as fallback only.
1731 //
1732 // Input:
1733 // r1 - left compare operand (in register)
1734 // x2 - right compare operand (immediate)
1735 void MacroAssembler::compare_and_branch_optimized(Register r1,
1736 jlong x2,
1737 Assembler::branch_condition cond,
1738 Label& branch_target,
1739 bool len64,
1740 bool has_sign) {
1741 address branch_origin = pc();
1742 bool x2_imm8 = (has_sign && Immediate::is_simm8(x2)) || (!has_sign && Immediate::is_uimm8(x2));
1743 bool is_RelAddr16 = branch_target.is_near() ||
1744 (branch_target.is_bound() &&
1745 RelAddr::is_in_range_of_RelAddr16(target(branch_target), branch_origin));
1746 unsigned int casenum = (len64?2:0)+(has_sign?0:1);
1747
1748 if (VM_Version::has_CompareBranch() && is_RelAddr16 && x2_imm8) {
1749 switch (casenum) {
1750 case 0: z_cij( r1, x2, cond, branch_target); break;
1751 case 1: z_clij(r1, x2, cond, branch_target); break;
1752 case 2: z_cgij(r1, x2, cond, branch_target); break;
1753 case 3: z_clgij(r1, x2, cond, branch_target); break;
1754 default: ShouldNotReachHere(); break;
1755 }
1756 return;
1757 }
1758
1759 if (x2 == 0) {
1760 switch (casenum) {
1761 case 0: z_ltr(r1, r1); break;
1762 case 1: z_ltr(r1, r1); break; // Caution: unsigned test only provides zero/notZero indication!
1763 case 2: z_ltgr(r1, r1); break;
1764 case 3: z_ltgr(r1, r1); break; // Caution: unsigned test only provides zero/notZero indication!
1765 default: ShouldNotReachHere(); break;
1766 }
1767 } else {
1768 if ((has_sign && Immediate::is_simm16(x2)) || (!has_sign && Immediate::is_uimm(x2, 15))) {
1769 switch (casenum) {
1770 case 0: z_chi(r1, x2); break;
1771 case 1: z_chi(r1, x2); break; // positive immediate < 2**15
1772 case 2: z_cghi(r1, x2); break;
1773 case 3: z_cghi(r1, x2); break; // positive immediate < 2**15
1774 default: break;
1775 }
1776 } else if ( (has_sign && Immediate::is_simm32(x2)) || (!has_sign && Immediate::is_uimm32(x2)) ) {
1777 switch (casenum) {
1778 case 0: z_cfi( r1, x2); break;
1779 case 1: z_clfi(r1, x2); break;
1780 case 2: z_cgfi(r1, x2); break;
1781 case 3: z_clgfi(r1, x2); break;
1782 default: ShouldNotReachHere(); break;
1783 }
1784 } else {
1785 // No instruction with immediate operand possible, so load into register.
1786 Register scratch = (r1 != Z_R0) ? Z_R0 : Z_R1;
1787 load_const_optimized(scratch, x2);
1788 switch (casenum) {
1789 case 0: z_cr( r1, scratch); break;
1790 case 1: z_clr(r1, scratch); break;
1791 case 2: z_cgr(r1, scratch); break;
1792 case 3: z_clgr(r1, scratch); break;
1793 default: ShouldNotReachHere(); break;
1794 }
1795 }
1796 }
1797 branch_optimized(cond, branch_target);
1798 }
1799
1800 // Generate an optimal compare and branch to the branch target.
1801 // Optimal means that a relative branch (clgrj, brc or brcl) is used if the
1802 // branch distance is short enough. Loading the target address into a
1803 // register and branching via reg is used as fallback only.
1804 //
1805 // Input:
1806 // r1 - left compare operand
1807 // r2 - right compare operand
1808 void MacroAssembler::compare_and_branch_optimized(Register r1,
1809 Register r2,
1810 Assembler::branch_condition cond,
1811 Label& branch_target,
1812 bool len64,
1813 bool has_sign) {
1814 unsigned int casenum = (len64 ? 2 : 0) + (has_sign ? 0 : 1);
1815
1816 if (branch_target.is_bound()) {
1817 address branch_addr = target(branch_target);
1818 compare_and_branch_optimized(r1, r2, cond, branch_addr, len64, has_sign);
1819 } else {
1820 if (VM_Version::has_CompareBranch() && branch_target.is_near()) {
1821 switch (casenum) {
1822 case 0: z_crj( r1, r2, cond, branch_target); break;
1823 case 1: z_clrj( r1, r2, cond, branch_target); break;
1824 case 2: z_cgrj( r1, r2, cond, branch_target); break;
1825 case 3: z_clgrj(r1, r2, cond, branch_target); break;
1826 default: ShouldNotReachHere(); break;
1827 }
1828 } else {
1829 switch (casenum) {
1830 case 0: z_cr( r1, r2); break;
1831 case 1: z_clr(r1, r2); break;
1832 case 2: z_cgr(r1, r2); break;
1833 case 3: z_clgr(r1, r2); break;
1834 default: ShouldNotReachHere(); break;
1835 }
1836 branch_optimized(cond, branch_target);
1837 }
1838 }
1839 }
1840
1841 //===========================================================================
1842 //=== END H I G H E R L E V E L B R A N C H E M I T T E R S ===
1843 //===========================================================================
1844
1845 AddressLiteral MacroAssembler::allocate_metadata_address(Metadata* obj) {
1846 assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
1847 int index = oop_recorder()->allocate_metadata_index(obj);
1848 RelocationHolder rspec = metadata_Relocation::spec(index);
1849 return AddressLiteral((address)obj, rspec);
1850 }
1851
1852 AddressLiteral MacroAssembler::constant_metadata_address(Metadata* obj) {
1853 assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
1854 int index = oop_recorder()->find_index(obj);
1855 RelocationHolder rspec = metadata_Relocation::spec(index);
1856 return AddressLiteral((address)obj, rspec);
1857 }
1858
1859 AddressLiteral MacroAssembler::allocate_oop_address(jobject obj) {
1860 assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
1861 int oop_index = oop_recorder()->allocate_oop_index(obj);
1862 return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
1863 }
1864
1865 AddressLiteral MacroAssembler::constant_oop_address(jobject obj) {
1866 assert(oop_recorder() != nullptr, "this assembler needs an OopRecorder");
1867 int oop_index = oop_recorder()->find_index(obj);
1868 return AddressLiteral(address(obj), oop_Relocation::spec(oop_index));
1869 }
1870
1871 // NOTE: destroys r
1872 void MacroAssembler::c2bool(Register r, Register t) {
1873 z_lcr(t, r); // t = -r
1874 z_or(r, t); // r = -r OR r
1875 z_srl(r, 31); // Yields 0 if r was 0, 1 otherwise.
1876 }
1877
1878 // Patch instruction `inst' at offset `inst_pos' to refer to `dest_pos'
1879 // and return the resulting instruction.
1880 // Dest_pos and inst_pos are 32 bit only. These parms can only designate
1881 // relative positions.
1882 // Use correct argument types. Do not pre-calculate distance.
1883 unsigned long MacroAssembler::patched_branch(address dest_pos, unsigned long inst, address inst_pos) {
1884 int c = 0;
1885 unsigned long patched_inst = 0;
1886 if (is_call_pcrelative_short(inst) ||
1887 is_branch_pcrelative_short(inst) ||
1888 is_branchoncount_pcrelative_short(inst) ||
1889 is_branchonindex32_pcrelative_short(inst)) {
1890 c = 1;
1891 int m = fmask(15, 0); // simm16(-1, 16, 32);
1892 int v = simm16(RelAddr::pcrel_off16(dest_pos, inst_pos), 16, 32);
1893 patched_inst = (inst & ~m) | v;
1894 } else if (is_compareandbranch_pcrelative_short(inst)) {
1895 c = 2;
1896 long m = fmask(31, 16); // simm16(-1, 16, 48);
1897 long v = simm16(RelAddr::pcrel_off16(dest_pos, inst_pos), 16, 48);
1898 patched_inst = (inst & ~m) | v;
1899 } else if (is_branchonindex64_pcrelative_short(inst)) {
1900 c = 3;
1901 long m = fmask(31, 16); // simm16(-1, 16, 48);
1902 long v = simm16(RelAddr::pcrel_off16(dest_pos, inst_pos), 16, 48);
1903 patched_inst = (inst & ~m) | v;
1904 } else if (is_call_pcrelative_long(inst) || is_branch_pcrelative_long(inst)) {
1905 c = 4;
1906 long m = fmask(31, 0); // simm32(-1, 16, 48);
1907 long v = simm32(RelAddr::pcrel_off32(dest_pos, inst_pos), 16, 48);
1908 patched_inst = (inst & ~m) | v;
1909 } else if (is_pcrelative_long(inst)) { // These are the non-branch pc-relative instructions.
1910 c = 5;
1911 long m = fmask(31, 0); // simm32(-1, 16, 48);
1912 long v = simm32(RelAddr::pcrel_off32(dest_pos, inst_pos), 16, 48);
1913 patched_inst = (inst & ~m) | v;
1914 } else {
1915 print_dbg_msg(tty, inst, "not a relative branch", 0);
1916 dump_code_range(tty, inst_pos, 32, "not a pcrelative branch");
1917 ShouldNotReachHere();
1918 }
1919
1920 long new_off = get_pcrel_offset(patched_inst);
1921 if (new_off != (dest_pos-inst_pos)) {
1922 tty->print_cr("case %d: dest_pos = %p, inst_pos = %p, disp = %ld(%12.12lx)", c, dest_pos, inst_pos, new_off, new_off);
1923 print_dbg_msg(tty, inst, "<- original instruction: branch patching error", 0);
1924 print_dbg_msg(tty, patched_inst, "<- patched instruction: branch patching error", 0);
1925 #ifdef LUCY_DBG
1926 VM_Version::z_SIGSEGV();
1927 #endif
1928 ShouldNotReachHere();
1929 }
1930 return patched_inst;
1931 }
1932
1933 // Only called when binding labels (share/vm/asm/assembler.cpp)
1934 // Pass arguments as intended. Do not pre-calculate distance.
1935 void MacroAssembler::pd_patch_instruction(address branch, address target, const char* file, int line) {
1936
1937 if (is_load_const(branch)) {
1938 patch_const(branch, (long)target);
1939 return;
1940 }
1941
1942 unsigned long stub_inst;
1943 int inst_len = get_instruction(branch, &stub_inst);
1944
1945 set_instruction(branch, patched_branch(target, stub_inst, branch), inst_len);
1946 }
1947
1948
1949 // Extract relative address (aka offset).
1950 // inv_simm16 works for 4-byte instructions only.
1951 // compare and branch instructions are 6-byte and have a 16bit offset "in the middle".
1952 long MacroAssembler::get_pcrel_offset(unsigned long inst) {
1953
1954 if (MacroAssembler::is_pcrelative_short(inst)) {
1955 if (((inst&0xFFFFffff00000000UL) == 0) && ((inst&0x00000000FFFF0000UL) != 0)) {
1956 return RelAddr::inv_pcrel_off16(inv_simm16(inst));
1957 } else {
1958 return RelAddr::inv_pcrel_off16(inv_simm16_48(inst));
1959 }
1960 }
1961
1962 if (MacroAssembler::is_pcrelative_long(inst)) {
1963 return RelAddr::inv_pcrel_off32(inv_simm32(inst));
1964 }
1965
1966 print_dbg_msg(tty, inst, "not a pcrelative instruction", 6);
1967 #ifdef LUCY_DBG
1968 VM_Version::z_SIGSEGV();
1969 #else
1970 ShouldNotReachHere();
1971 #endif
1972 return -1;
1973 }
1974
1975 long MacroAssembler::get_pcrel_offset(address pc) {
1976 unsigned long inst;
1977 unsigned int len = get_instruction(pc, &inst);
1978
1979 #ifdef ASSERT
1980 long offset;
1981 if (MacroAssembler::is_pcrelative_short(inst) || MacroAssembler::is_pcrelative_long(inst)) {
1982 offset = get_pcrel_offset(inst);
1983 } else {
1984 offset = -1;
1985 }
1986
1987 if (offset == -1) {
1988 dump_code_range(tty, pc, 32, "not a pcrelative instruction");
1989 #ifdef LUCY_DBG
1990 VM_Version::z_SIGSEGV();
1991 #else
1992 ShouldNotReachHere();
1993 #endif
1994 }
1995 return offset;
1996 #else
1997 return get_pcrel_offset(inst);
1998 #endif // ASSERT
1999 }
2000
2001 // Get target address from pc-relative instructions.
2002 address MacroAssembler::get_target_addr_pcrel(address pc) {
2003 assert(is_pcrelative_long(pc), "not a pcrelative instruction");
2004 return pc + get_pcrel_offset(pc);
2005 }
2006
2007 // Patch pc relative load address.
2008 void MacroAssembler::patch_target_addr_pcrel(address pc, address con) {
2009 unsigned long inst;
2010 // Offset is +/- 2**32 -> use long.
2011 ptrdiff_t distance = con - pc;
2012
2013 get_instruction(pc, &inst);
2014
2015 if (is_pcrelative_short(inst)) {
2016 *(short *)(pc+2) = RelAddr::pcrel_off16(con, pc); // Instructions are at least 2-byte aligned, no test required.
2017
2018 // Some extra safety net.
2019 if (!RelAddr::is_in_range_of_RelAddr16(distance)) {
2020 print_dbg_msg(tty, inst, "distance out of range (16bit)", 4);
2021 dump_code_range(tty, pc, 32, "distance out of range (16bit)");
2022 guarantee(RelAddr::is_in_range_of_RelAddr16(distance), "too far away (more than +/- 2**16");
2023 }
2024 return;
2025 }
2026
2027 if (is_pcrelative_long(inst)) {
2028 *(int *)(pc+2) = RelAddr::pcrel_off32(con, pc);
2029
2030 // Some Extra safety net.
2031 if (!RelAddr::is_in_range_of_RelAddr32(distance)) {
2032 print_dbg_msg(tty, inst, "distance out of range (32bit)", 6);
2033 dump_code_range(tty, pc, 32, "distance out of range (32bit)");
2034 guarantee(RelAddr::is_in_range_of_RelAddr32(distance), "too far away (more than +/- 2**32");
2035 }
2036 return;
2037 }
2038
2039 guarantee(false, "not a pcrelative instruction to patch!");
2040 }
2041
2042 // "Current PC" here means the address just behind the basr instruction.
2043 address MacroAssembler::get_PC(Register result) {
2044 z_basr(result, Z_R0); // Don't branch, just save next instruction address in result.
2045 return pc();
2046 }
2047
2048 // Get current PC + offset.
2049 // Offset given in bytes, must be even!
2050 // "Current PC" here means the address of the larl instruction plus the given offset.
2051 address MacroAssembler::get_PC(Register result, int64_t offset) {
2052 address here = pc();
2053 z_larl(result, offset/2); // Save target instruction address in result.
2054 return here + offset;
2055 }
2056
2057 void MacroAssembler::instr_size(Register size, Register pc) {
2058 // Extract 2 most significant bits of current instruction.
2059 z_llgc(size, Address(pc));
2060 z_srl(size, 6);
2061 // Compute (x+3)&6 which translates 0->2, 1->4, 2->4, 3->6.
2062 z_ahi(size, 3);
2063 z_nill(size, 6);
2064 }
2065
2066 // Resize_frame with SP(new) = SP(old) - [offset].
2067 void MacroAssembler::resize_frame_sub(Register offset, Register fp, bool load_fp)
2068 {
2069 assert_different_registers(offset, fp, Z_SP);
2070 if (load_fp) { z_lg(fp, _z_abi(callers_sp), Z_SP); }
2071
2072 z_sgr(Z_SP, offset);
2073 z_stg(fp, _z_abi(callers_sp), Z_SP);
2074 }
2075
2076 // Resize_frame with SP(new) = [newSP] + offset.
2077 // This emitter is useful if we already have calculated a pointer
2078 // into the to-be-allocated stack space, e.g. with special alignment properties,
2079 // but need some additional space, e.g. for spilling.
2080 // newSP is the pre-calculated pointer. It must not be modified.
2081 // fp holds, or is filled with, the frame pointer.
2082 // offset is the additional increment which is added to addr to form the new SP.
2083 // Note: specify a negative value to reserve more space!
2084 // load_fp == true only indicates that fp is not pre-filled with the frame pointer.
2085 // It does not guarantee that fp contains the frame pointer at the end.
2086 void MacroAssembler::resize_frame_abs_with_offset(Register newSP, Register fp, int offset, bool load_fp) {
2087 assert_different_registers(newSP, fp, Z_SP);
2088
2089 if (load_fp) {
2090 z_lg(fp, _z_abi(callers_sp), Z_SP);
2091 }
2092
2093 add2reg(Z_SP, offset, newSP);
2094 z_stg(fp, _z_abi(callers_sp), Z_SP);
2095 }
2096
2097 // Resize_frame with SP(new) = [newSP].
2098 // load_fp == true only indicates that fp is not pre-filled with the frame pointer.
2099 // It does not guarantee that fp contains the frame pointer at the end.
2100 void MacroAssembler::resize_frame_absolute(Register newSP, Register fp, bool load_fp) {
2101 assert_different_registers(newSP, fp, Z_SP);
2102
2103 if (load_fp) {
2104 z_lg(fp, _z_abi(callers_sp), Z_SP); // need to use load/store.
2105 }
2106
2107 z_lgr(Z_SP, newSP);
2108 if (newSP != Z_R0) { // make sure we generate correct code, no matter what register newSP uses.
2109 z_stg(fp, _z_abi(callers_sp), newSP);
2110 } else {
2111 z_stg(fp, _z_abi(callers_sp), Z_SP);
2112 }
2113 }
2114
2115 // Resize_frame with SP(new) = SP(old) + offset.
2116 void MacroAssembler::resize_frame(RegisterOrConstant offset, Register fp, bool load_fp) {
2117 assert_different_registers(fp, Z_SP);
2118
2119 if (load_fp) {
2120 z_lg(fp, _z_abi(callers_sp), Z_SP);
2121 }
2122 add64(Z_SP, offset);
2123 z_stg(fp, _z_abi(callers_sp), Z_SP);
2124 }
2125
2126 void MacroAssembler::push_frame(Register bytes, Register old_sp, bool copy_sp, bool bytes_with_inverted_sign) {
2127 #ifdef ASSERT
2128 assert_different_registers(bytes, old_sp, Z_SP);
2129 if (!copy_sp) {
2130 z_cgr(old_sp, Z_SP);
2131 asm_assert(bcondEqual, "[old_sp]!=[Z_SP]", 0x211);
2132 }
2133 #endif
2134 if (copy_sp) { z_lgr(old_sp, Z_SP); }
2135 if (bytes_with_inverted_sign) {
2136 z_agr(Z_SP, bytes);
2137 } else {
2138 z_sgr(Z_SP, bytes); // Z_sgfr sufficient, but probably not faster.
2139 }
2140 z_stg(old_sp, _z_abi(callers_sp), Z_SP);
2141 }
2142
2143 unsigned int MacroAssembler::push_frame(unsigned int bytes, Register scratch) {
2144 long offset = Assembler::align(bytes, frame::alignment_in_bytes);
2145 assert(offset > 0, "should push a frame with positive size, size = %ld.", offset);
2146 assert(Displacement::is_validDisp(-offset), "frame size out of range, size = %ld", offset);
2147
2148 // We must not write outside the current stack bounds (given by Z_SP).
2149 // Thus, we have to first update Z_SP and then store the previous SP as stack linkage.
2150 // We rely on Z_R0 by default to be available as scratch.
2151 z_lgr(scratch, Z_SP);
2152 add2reg(Z_SP, -offset);
2153 z_stg(scratch, _z_abi(callers_sp), Z_SP);
2154 #ifdef ASSERT
2155 // Just make sure nobody uses the value in the default scratch register.
2156 // When another register is used, the caller might rely on it containing the frame pointer.
2157 if (scratch == Z_R0) {
2158 z_iihf(scratch, 0xbaadbabe);
2159 z_iilf(scratch, 0xdeadbeef);
2160 }
2161 #endif
2162 return offset;
2163 }
2164
2165 // Push a frame of size `bytes' plus abi160 on top.
2166 unsigned int MacroAssembler::push_frame_abi160(unsigned int bytes) {
2167 BLOCK_COMMENT("push_frame_abi160 {");
2168 unsigned int res = push_frame(bytes + frame::z_abi_160_size);
2169 BLOCK_COMMENT("} push_frame_abi160");
2170 return res;
2171 }
2172
2173 // Pop current C frame.
2174 void MacroAssembler::pop_frame() {
2175 BLOCK_COMMENT("pop_frame {");
2176 Assembler::z_lg(Z_SP, _z_abi(callers_sp), Z_SP);
2177 BLOCK_COMMENT("} pop_frame");
2178 }
2179
2180 // Pop current C frame and restore return PC register (Z_R14).
2181 void MacroAssembler::pop_frame_restore_retPC(int frame_size_in_bytes) {
2182 BLOCK_COMMENT("pop_frame_restore_retPC:");
2183 int retPC_offset = _z_common_abi(return_pc) + frame_size_in_bytes;
2184 // If possible, pop frame by add instead of load (a penny saved is a penny got :-).
2185 if (Displacement::is_validDisp(retPC_offset)) {
2186 z_lg(Z_R14, retPC_offset, Z_SP);
2187 add2reg(Z_SP, frame_size_in_bytes);
2188 } else {
2189 add2reg(Z_SP, frame_size_in_bytes);
2190 restore_return_pc();
2191 }
2192 }
2193
2194 void MacroAssembler::call_VM_leaf_base(address entry_point, bool allow_relocation) {
2195 if (allow_relocation) {
2196 call_c(entry_point);
2197 } else {
2198 call_c_static(entry_point);
2199 }
2200 }
2201
2202 void MacroAssembler::call_VM_leaf_base(address entry_point) {
2203 bool allow_relocation = true;
2204 call_VM_leaf_base(entry_point, allow_relocation);
2205 }
2206
2207 int MacroAssembler::ic_check_size() {
2208 int ic_size = 24;
2209 if (!ImplicitNullChecks) {
2210 ic_size += 6;
2211 }
2212 if (UseCompactObjectHeaders) {
2213 ic_size += 12;
2214 } else {
2215 ic_size += 6; // either z_llgf or z_lg
2216 }
2217 return ic_size;
2218 }
2219
2220 int MacroAssembler::ic_check(int end_alignment) {
2221 Register R2_receiver = Z_ARG1;
2222 Register R0_scratch = Z_R0_scratch;
2223 Register R1_scratch = Z_R1_scratch;
2224 Register R9_data = Z_inline_cache;
2225 Label success, failure;
2226
2227 // The UEP of a code blob ensures that the VEP is padded. However, the padding of the UEP is placed
2228 // before the inline cache check, so we don't have to execute any nop instructions when dispatching
2229 // through the UEP, yet we can ensure that the VEP is aligned appropriately. That's why we align
2230 // before the inline cache check here, and not after
2231 align(end_alignment, offset() + ic_check_size());
2232
2233 int uep_offset = offset();
2234 if (!ImplicitNullChecks) {
2235 z_cgij(R2_receiver, 0, Assembler::bcondEqual, failure);
2236 }
2237
2238 if (UseCompactObjectHeaders) {
2239 load_narrow_klass_compact(R1_scratch, R2_receiver);
2240 } else {
2241 z_llgf(R1_scratch, Address(R2_receiver, oopDesc::klass_offset_in_bytes()));
2242 }
2243 z_cg(R1_scratch, Address(R9_data, in_bytes(CompiledICData::speculated_klass_offset())));
2244 z_bre(success);
2245
2246 bind(failure);
2247 load_const(R1_scratch, AddressLiteral(SharedRuntime::get_ic_miss_stub()));
2248 z_br(R1_scratch);
2249 bind(success);
2250
2251 assert((offset() % end_alignment) == 0, "Misaligned verified entry point, offset() = %d, end_alignment = %d", offset(), end_alignment);
2252 return uep_offset;
2253 }
2254
2255 void MacroAssembler::call_VM_base(Register oop_result,
2256 Register last_java_sp,
2257 address entry_point,
2258 bool allow_relocation,
2259 bool check_exceptions, // Defaults to true.
2260 Label *last_java_pc) {
2261 // Allow_relocation indicates, if true, that the generated code shall
2262 // be fit for code relocation or referenced data relocation. In other
2263 // words: all addresses must be considered variable. PC-relative addressing
2264 // is not possible then.
2265 // On the other hand, if (allow_relocation == false), addresses and offsets
2266 // may be considered stable, enabling us to take advantage of some PC-relative
2267 // addressing tweaks. These might improve performance and reduce code size.
2268
2269 // Determine last_java_sp register.
2270 if (!last_java_sp->is_valid()) {
2271 last_java_sp = Z_SP; // Load Z_SP as SP.
2272 }
2273
2274 set_top_ijava_frame_at_SP_as_last_Java_frame(last_java_sp, Z_R1, allow_relocation, last_java_pc);
2275
2276 // ARG1 must hold thread address.
2277 z_lgr(Z_ARG1, Z_thread);
2278
2279 address return_pc = nullptr;
2280 if (allow_relocation) {
2281 return_pc = call_c(entry_point);
2282 } else {
2283 return_pc = call_c_static(entry_point);
2284 }
2285
2286 reset_last_Java_frame(allow_relocation);
2287
2288 // C++ interp handles this in the interpreter.
2289 check_and_handle_popframe(Z_thread);
2290 check_and_handle_earlyret(Z_thread);
2291
2292 // Check for pending exceptions.
2293 if (check_exceptions) {
2294 // Check for pending exceptions (java_thread is set upon return).
2295 load_and_test_long(Z_R0_scratch, Address(Z_thread, Thread::pending_exception_offset()));
2296
2297 // This used to conditionally jump to forward_exception however it is
2298 // possible if we relocate that the branch will not reach. So we must jump
2299 // around so we can always reach.
2300
2301 Label ok;
2302 z_bre(ok); // Bcondequal is the same as bcondZero.
2303 call_stub(StubRoutines::forward_exception_entry());
2304 bind(ok);
2305 }
2306
2307 // Get oop result if there is one and reset the value in the thread.
2308 if (oop_result->is_valid()) {
2309 get_vm_result_oop(oop_result);
2310 }
2311
2312 _last_calls_return_pc = return_pc; // Wipe out other (error handling) calls.
2313 }
2314
2315 void MacroAssembler::call_VM_base(Register oop_result,
2316 Register last_java_sp,
2317 address entry_point,
2318 bool check_exceptions) { // Defaults to true.
2319 bool allow_relocation = true;
2320 call_VM_base(oop_result, last_java_sp, entry_point, allow_relocation, check_exceptions, nullptr);
2321 }
2322
2323 // VM calls without explicit last_java_sp.
2324
2325 void MacroAssembler::call_VM(Register oop_result, address entry_point, bool check_exceptions, Label* last_java_pc) {
2326 // Call takes possible detour via InterpreterMacroAssembler.
2327 call_VM_base(oop_result, noreg, entry_point, true, check_exceptions, last_java_pc);
2328 }
2329
2330 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, bool check_exceptions) {
2331 // Z_ARG1 is reserved for the thread.
2332 lgr_if_needed(Z_ARG2, arg_1);
2333 call_VM(oop_result, entry_point, check_exceptions);
2334 }
2335
2336 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2, bool check_exceptions) {
2337 // Z_ARG1 is reserved for the thread.
2338 assert_different_registers(arg_2, Z_ARG2);
2339 lgr_if_needed(Z_ARG2, arg_1);
2340 lgr_if_needed(Z_ARG3, arg_2);
2341 call_VM(oop_result, entry_point, check_exceptions);
2342 }
2343
2344 void MacroAssembler::call_VM(Register oop_result, address entry_point, Register arg_1, Register arg_2,
2345 Register arg_3, bool check_exceptions) {
2346 // Z_ARG1 is reserved for the thread.
2347 assert_different_registers(arg_3, Z_ARG2, Z_ARG3);
2348 assert_different_registers(arg_2, Z_ARG2);
2349 lgr_if_needed(Z_ARG2, arg_1);
2350 lgr_if_needed(Z_ARG3, arg_2);
2351 lgr_if_needed(Z_ARG4, arg_3);
2352 call_VM(oop_result, entry_point, check_exceptions);
2353 }
2354
2355 // VM static calls without explicit last_java_sp.
2356
2357 void MacroAssembler::call_VM_static(Register oop_result, address entry_point, bool check_exceptions) {
2358 // Call takes possible detour via InterpreterMacroAssembler.
2359 call_VM_base(oop_result, noreg, entry_point, false, check_exceptions, nullptr);
2360 }
2361
2362 void MacroAssembler::call_VM_static(Register oop_result, address entry_point, Register arg_1, Register arg_2,
2363 Register arg_3, bool check_exceptions) {
2364 // Z_ARG1 is reserved for the thread.
2365 assert_different_registers(arg_3, Z_ARG2, Z_ARG3);
2366 assert_different_registers(arg_2, Z_ARG2);
2367 lgr_if_needed(Z_ARG2, arg_1);
2368 lgr_if_needed(Z_ARG3, arg_2);
2369 lgr_if_needed(Z_ARG4, arg_3);
2370 call_VM_static(oop_result, entry_point, check_exceptions);
2371 }
2372
2373 // VM calls with explicit last_java_sp.
2374
2375 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, bool check_exceptions) {
2376 // Call takes possible detour via InterpreterMacroAssembler.
2377 call_VM_base(oop_result, last_java_sp, entry_point, true, check_exceptions, nullptr);
2378 }
2379
2380 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1, bool check_exceptions) {
2381 // Z_ARG1 is reserved for the thread.
2382 lgr_if_needed(Z_ARG2, arg_1);
2383 call_VM(oop_result, last_java_sp, entry_point, check_exceptions);
2384 }
2385
2386 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1,
2387 Register arg_2, bool check_exceptions) {
2388 // Z_ARG1 is reserved for the thread.
2389 assert_different_registers(arg_2, Z_ARG2);
2390 lgr_if_needed(Z_ARG2, arg_1);
2391 lgr_if_needed(Z_ARG3, arg_2);
2392 call_VM(oop_result, last_java_sp, entry_point, check_exceptions);
2393 }
2394
2395 void MacroAssembler::call_VM(Register oop_result, Register last_java_sp, address entry_point, Register arg_1,
2396 Register arg_2, Register arg_3, bool check_exceptions) {
2397 // Z_ARG1 is reserved for the thread.
2398 assert_different_registers(arg_3, Z_ARG2, Z_ARG3);
2399 assert_different_registers(arg_2, Z_ARG2);
2400 lgr_if_needed(Z_ARG2, arg_1);
2401 lgr_if_needed(Z_ARG3, arg_2);
2402 lgr_if_needed(Z_ARG4, arg_3);
2403 call_VM(oop_result, last_java_sp, entry_point, check_exceptions);
2404 }
2405
2406 // VM leaf calls.
2407
2408 void MacroAssembler::call_VM_leaf(address entry_point) {
2409 // Call takes possible detour via InterpreterMacroAssembler.
2410 call_VM_leaf_base(entry_point, true);
2411 }
2412
2413 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1) {
2414 if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2415 call_VM_leaf(entry_point);
2416 }
2417
2418 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2) {
2419 assert_different_registers(arg_2, Z_ARG1);
2420 if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2421 if (arg_2 != noreg) lgr_if_needed(Z_ARG2, arg_2);
2422 call_VM_leaf(entry_point);
2423 }
2424
2425 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_1, Register arg_2, Register arg_3) {
2426 assert_different_registers(arg_3, Z_ARG1, Z_ARG2);
2427 assert_different_registers(arg_2, Z_ARG1);
2428 if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2429 if (arg_2 != noreg) lgr_if_needed(Z_ARG2, arg_2);
2430 if (arg_3 != noreg) lgr_if_needed(Z_ARG3, arg_3);
2431 call_VM_leaf(entry_point);
2432 }
2433
2434 // Static VM leaf calls.
2435 // Really static VM leaf calls are never patched.
2436
2437 void MacroAssembler::call_VM_leaf_static(address entry_point) {
2438 // Call takes possible detour via InterpreterMacroAssembler.
2439 call_VM_leaf_base(entry_point, false);
2440 }
2441
2442 void MacroAssembler::call_VM_leaf_static(address entry_point, Register arg_1) {
2443 if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2444 call_VM_leaf_static(entry_point);
2445 }
2446
2447 void MacroAssembler::call_VM_leaf_static(address entry_point, Register arg_1, Register arg_2) {
2448 assert_different_registers(arg_2, Z_ARG1);
2449 if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2450 if (arg_2 != noreg) lgr_if_needed(Z_ARG2, arg_2);
2451 call_VM_leaf_static(entry_point);
2452 }
2453
2454 void MacroAssembler::call_VM_leaf_static(address entry_point, Register arg_1, Register arg_2, Register arg_3) {
2455 assert_different_registers(arg_3, Z_ARG1, Z_ARG2);
2456 assert_different_registers(arg_2, Z_ARG1);
2457 if (arg_1 != noreg) lgr_if_needed(Z_ARG1, arg_1);
2458 if (arg_2 != noreg) lgr_if_needed(Z_ARG2, arg_2);
2459 if (arg_3 != noreg) lgr_if_needed(Z_ARG3, arg_3);
2460 call_VM_leaf_static(entry_point);
2461 }
2462
2463 // Don't use detour via call_c(reg).
2464 address MacroAssembler::call_c(address function_entry) {
2465 load_const(Z_R1, function_entry);
2466 return call(Z_R1);
2467 }
2468
2469 // Variant for really static (non-relocatable) calls which are never patched.
2470 address MacroAssembler::call_c_static(address function_entry) {
2471 load_absolute_address(Z_R1, function_entry);
2472 #if 0 // def ASSERT
2473 // Verify that call site did not move.
2474 load_const_optimized(Z_R0, function_entry);
2475 z_cgr(Z_R1, Z_R0);
2476 z_brc(bcondEqual, 3);
2477 z_illtrap(0xba);
2478 #endif
2479 return call(Z_R1);
2480 }
2481
2482 address MacroAssembler::call_c_opt(address function_entry) {
2483 bool success = call_far_patchable(function_entry, -2 /* emit relocation + constant */);
2484 _last_calls_return_pc = success ? pc() : nullptr;
2485 return _last_calls_return_pc;
2486 }
2487
2488 // Identify a call_far_patchable instruction: LARL + LG + BASR
2489 //
2490 // nop ; optionally, if required for alignment
2491 // lgrl rx,A(TOC entry) ; PC-relative access into constant pool
2492 // basr Z_R14,rx ; end of this instruction must be aligned to a word boundary
2493 //
2494 // Code pattern will eventually get patched into variant2 (see below for detection code).
2495 //
2496 bool MacroAssembler::is_call_far_patchable_variant0_at(address instruction_addr) {
2497 address iaddr = instruction_addr;
2498
2499 // Check for the actual load instruction.
2500 if (!is_load_const_from_toc(iaddr)) { return false; }
2501 iaddr += load_const_from_toc_size();
2502
2503 // Check for the call (BASR) instruction, finally.
2504 assert(iaddr-instruction_addr+call_byregister_size() == call_far_patchable_size(), "size mismatch");
2505 return is_call_byregister(iaddr);
2506 }
2507
2508 // Identify a call_far_patchable instruction: BRASL
2509 //
2510 // Code pattern to suits atomic patching:
2511 // nop ; Optionally, if required for alignment.
2512 // nop ... ; Multiple filler nops to compensate for size difference (variant0 is longer).
2513 // nop ; For code pattern detection: Prepend each BRASL with a nop.
2514 // brasl Z_R14,<reladdr> ; End of code must be 4-byte aligned !
2515 bool MacroAssembler::is_call_far_patchable_variant2_at(address instruction_addr) {
2516 const address call_addr = (address)((intptr_t)instruction_addr + call_far_patchable_size() - call_far_pcrelative_size());
2517
2518 // Check for correct number of leading nops.
2519 address iaddr;
2520 for (iaddr = instruction_addr; iaddr < call_addr; iaddr += nop_size()) {
2521 if (!is_z_nop(iaddr)) { return false; }
2522 }
2523 assert(iaddr == call_addr, "sanity");
2524
2525 // --> Check for call instruction.
2526 if (is_call_far_pcrelative(call_addr)) {
2527 assert(call_addr-instruction_addr+call_far_pcrelative_size() == call_far_patchable_size(), "size mismatch");
2528 return true;
2529 }
2530
2531 return false;
2532 }
2533
2534 // Emit a NOT mt-safely patchable 64 bit absolute call.
2535 // If toc_offset == -2, then the destination of the call (= target) is emitted
2536 // to the constant pool and a runtime_call relocation is added
2537 // to the code buffer.
2538 // If toc_offset != -2, target must already be in the constant pool at
2539 // _ctableStart+toc_offset (a caller can retrieve toc_offset
2540 // from the runtime_call relocation).
2541 // Special handling of emitting to scratch buffer when there is no constant pool.
2542 // Slightly changed code pattern. We emit an additional nop if we would
2543 // not end emitting at a word aligned address. This is to ensure
2544 // an atomically patchable displacement in brasl instructions.
2545 //
2546 // A call_far_patchable comes in different flavors:
2547 // - LARL(CP) / LG(CP) / BR (address in constant pool, access via CP register)
2548 // - LGRL(CP) / BR (address in constant pool, pc-relative access)
2549 // - BRASL (relative address of call target coded in instruction)
2550 // All flavors occupy the same amount of space. Length differences are compensated
2551 // by leading nops, such that the instruction sequence always ends at the same
2552 // byte offset. This is required to keep the return offset constant.
2553 // Furthermore, the return address (the end of the instruction sequence) is forced
2554 // to be on a 4-byte boundary. This is required for atomic patching, should we ever
2555 // need to patch the call target of the BRASL flavor.
2556 // RETURN value: false, if no constant pool entry could be allocated, true otherwise.
2557 bool MacroAssembler::call_far_patchable(address target, int64_t tocOffset) {
2558 // Get current pc and ensure word alignment for end of instr sequence.
2559 const address start_pc = pc();
2560 const intptr_t start_off = offset();
2561 assert(!call_far_patchable_requires_alignment_nop(start_pc), "call_far_patchable requires aligned address");
2562 const ptrdiff_t dist = (ptrdiff_t)(target - (start_pc + 2)); // Prepend each BRASL with a nop.
2563 const bool emit_target_to_pool = (tocOffset == -2) && !code_section()->scratch_emit();
2564 const bool emit_relative_call = !emit_target_to_pool &&
2565 RelAddr::is_in_range_of_RelAddr32(dist) &&
2566 ReoptimizeCallSequences &&
2567 !code_section()->scratch_emit();
2568
2569 if (emit_relative_call) {
2570 // Add padding to get the same size as below.
2571 const unsigned int padding = call_far_patchable_size() - call_far_pcrelative_size();
2572 unsigned int current_padding;
2573 for (current_padding = 0; current_padding < padding; current_padding += nop_size()) { z_nop(); }
2574 assert(current_padding == padding, "sanity");
2575
2576 // relative call: len = 2(nop) + 6 (brasl)
2577 // CodeBlob resize cannot occur in this case because
2578 // this call is emitted into pre-existing space.
2579 z_nop(); // Prepend each BRASL with a nop.
2580 z_brasl(Z_R14, target);
2581 } else {
2582 // absolute call: Get address from TOC.
2583 // len = (load TOC){6|0} + (load from TOC){6} + (basr){2} = {14|8}
2584 if (emit_target_to_pool) {
2585 // When emitting the call for the first time, we do not need to use
2586 // the pc-relative version. It will be patched anyway, when the code
2587 // buffer is copied.
2588 // Relocation is not needed when !ReoptimizeCallSequences.
2589 relocInfo::relocType rt = ReoptimizeCallSequences ? relocInfo::runtime_call_w_cp_type : relocInfo::none;
2590 AddressLiteral dest(target, rt);
2591 // Store_oop_in_toc() adds dest to the constant table. As side effect, this kills
2592 // inst_mark(). Reset if possible.
2593 bool reset_mark = (inst_mark() == pc());
2594 tocOffset = store_oop_in_toc(dest);
2595 if (reset_mark) { set_inst_mark(); }
2596 if (tocOffset == -1) {
2597 return false; // Couldn't create constant pool entry.
2598 }
2599 }
2600 assert(offset() == start_off, "emit no code before this point!");
2601
2602 address tocPos = pc() + tocOffset;
2603 if (emit_target_to_pool) {
2604 tocPos = code()->consts()->start() + tocOffset;
2605 }
2606 load_long_pcrelative(Z_R14, tocPos);
2607 z_basr(Z_R14, Z_R14);
2608 }
2609
2610 #ifdef ASSERT
2611 // Assert that we can identify the emitted call.
2612 assert(is_call_far_patchable_at(addr_at(start_off)), "can't identify emitted call");
2613 assert(offset() == start_off+call_far_patchable_size(), "wrong size");
2614
2615 if (emit_target_to_pool) {
2616 assert(get_dest_of_call_far_patchable_at(addr_at(start_off), code()->consts()->start()) == target,
2617 "wrong encoding of dest address");
2618 }
2619 #endif
2620 return true; // success
2621 }
2622
2623 // Identify a call_far_patchable instruction.
2624 // For more detailed information see header comment of call_far_patchable.
2625 bool MacroAssembler::is_call_far_patchable_at(address instruction_addr) {
2626 return is_call_far_patchable_variant2_at(instruction_addr) || // short version: BRASL
2627 is_call_far_patchable_variant0_at(instruction_addr); // long version LARL + LG + BASR
2628 }
2629
2630 // Does the call_far_patchable instruction use a pc-relative encoding
2631 // of the call destination?
2632 bool MacroAssembler::is_call_far_patchable_pcrelative_at(address instruction_addr) {
2633 // Variant 2 is pc-relative.
2634 return is_call_far_patchable_variant2_at(instruction_addr);
2635 }
2636
2637 bool MacroAssembler::is_call_far_pcrelative(address instruction_addr) {
2638 // Prepend each BRASL with a nop.
2639 return is_z_nop(instruction_addr) && is_z_brasl(instruction_addr + nop_size()); // Match at position after one nop required.
2640 }
2641
2642 // Set destination address of a call_far_patchable instruction.
2643 void MacroAssembler::set_dest_of_call_far_patchable_at(address instruction_addr, address dest, int64_t tocOffset) {
2644 ResourceMark rm;
2645
2646 // Now that CP entry is verified, patch call to a pc-relative call (if circumstances permit).
2647 int code_size = MacroAssembler::call_far_patchable_size();
2648 CodeBuffer buf(instruction_addr, code_size);
2649 MacroAssembler masm(&buf);
2650 masm.call_far_patchable(dest, tocOffset);
2651 ICache::invalidate_range(instruction_addr, code_size); // Empty on z.
2652 }
2653
2654 // Get dest address of a call_far_patchable instruction.
2655 address MacroAssembler::get_dest_of_call_far_patchable_at(address instruction_addr, address ctable) {
2656 // Dynamic TOC: absolute address in constant pool.
2657 // Check variant2 first, it is more frequent.
2658
2659 // Relative address encoded in call instruction.
2660 if (is_call_far_patchable_variant2_at(instruction_addr)) {
2661 return MacroAssembler::get_target_addr_pcrel(instruction_addr + nop_size()); // Prepend each BRASL with a nop.
2662
2663 // Absolute address in constant pool.
2664 } else if (is_call_far_patchable_variant0_at(instruction_addr)) {
2665 address iaddr = instruction_addr;
2666
2667 long tocOffset = get_load_const_from_toc_offset(iaddr);
2668 address tocLoc = iaddr + tocOffset;
2669 return *(address *)(tocLoc);
2670 } else {
2671 fprintf(stderr, "MacroAssembler::get_dest_of_call_far_patchable_at has a problem at %p:\n", instruction_addr);
2672 fprintf(stderr, "not a call_far_patchable: %16.16lx %16.16lx, len = %d\n",
2673 *(unsigned long*)instruction_addr,
2674 *(unsigned long*)(instruction_addr+8),
2675 call_far_patchable_size());
2676 Disassembler::decode(instruction_addr, instruction_addr+call_far_patchable_size());
2677 ShouldNotReachHere();
2678 return nullptr;
2679 }
2680 }
2681
2682 void MacroAssembler::align_call_far_patchable(address pc) {
2683 if (call_far_patchable_requires_alignment_nop(pc)) { z_nop(); }
2684 }
2685
2686 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2687 }
2688
2689 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2690 }
2691
2692 // Read from the polling page.
2693 // Use TM or TMY instruction, depending on read offset.
2694 // offset = 0: Use TM, safepoint polling.
2695 // offset < 0: Use TMY, profiling safepoint polling.
2696 void MacroAssembler::load_from_polling_page(Register polling_page_address, int64_t offset) {
2697 if (Immediate::is_uimm12(offset)) {
2698 z_tm(offset, polling_page_address, mask_safepoint);
2699 } else {
2700 z_tmy(offset, polling_page_address, mask_profiling);
2701 }
2702 }
2703
2704 // Check whether z_instruction is a read access to the polling page
2705 // which was emitted by load_from_polling_page(..).
2706 bool MacroAssembler::is_load_from_polling_page(address instr_loc) {
2707 unsigned long z_instruction;
2708 unsigned int ilen = get_instruction(instr_loc, &z_instruction);
2709
2710 if (ilen == 2) { return false; } // It's none of the allowed instructions.
2711
2712 if (ilen == 4) {
2713 if (!is_z_tm(z_instruction)) { return false; } // It's len=4, but not a z_tm. fail.
2714
2715 int ms = inv_mask(z_instruction,8,32); // mask
2716 int ra = inv_reg(z_instruction,16,32); // base register
2717 int ds = inv_uimm12(z_instruction); // displacement
2718
2719 if (!(ds == 0 && ra != 0 && ms == mask_safepoint)) {
2720 return false; // It's not a z_tm(0, ra, mask_safepoint). Fail.
2721 }
2722
2723 } else { /* if (ilen == 6) */
2724
2725 assert(!is_z_lg(z_instruction), "old form (LG) polling page access. Please fix and use TM(Y).");
2726
2727 if (!is_z_tmy(z_instruction)) { return false; } // It's len=6, but not a z_tmy. fail.
2728
2729 int ms = inv_mask(z_instruction,8,48); // mask
2730 int ra = inv_reg(z_instruction,16,48); // base register
2731 int ds = inv_simm20(z_instruction); // displacement
2732 }
2733
2734 return true;
2735 }
2736
2737 // Extract poll address from instruction and ucontext.
2738 address MacroAssembler::get_poll_address(address instr_loc, void* ucontext) {
2739 assert(ucontext != nullptr, "must have ucontext");
2740 ucontext_t* uc = (ucontext_t*) ucontext;
2741 unsigned long z_instruction;
2742 unsigned int ilen = get_instruction(instr_loc, &z_instruction);
2743
2744 if (ilen == 4 && is_z_tm(z_instruction)) {
2745 int ra = inv_reg(z_instruction, 16, 32); // base register
2746 int ds = inv_uimm12(z_instruction); // displacement
2747 address addr = (address)uc->uc_mcontext.gregs[ra];
2748 return addr + ds;
2749 } else if (ilen == 6 && is_z_tmy(z_instruction)) {
2750 int ra = inv_reg(z_instruction, 16, 48); // base register
2751 int ds = inv_simm20(z_instruction); // displacement
2752 address addr = (address)uc->uc_mcontext.gregs[ra];
2753 return addr + ds;
2754 }
2755
2756 ShouldNotReachHere();
2757 return nullptr;
2758 }
2759
2760 // Extract poll register from instruction.
2761 uint MacroAssembler::get_poll_register(address instr_loc) {
2762 unsigned long z_instruction;
2763 unsigned int ilen = get_instruction(instr_loc, &z_instruction);
2764
2765 if (ilen == 4 && is_z_tm(z_instruction)) {
2766 return (uint)inv_reg(z_instruction, 16, 32); // base register
2767 } else if (ilen == 6 && is_z_tmy(z_instruction)) {
2768 return (uint)inv_reg(z_instruction, 16, 48); // base register
2769 }
2770
2771 ShouldNotReachHere();
2772 return 0;
2773 }
2774
2775 void MacroAssembler::safepoint_poll(Label& slow_path, Register temp_reg) {
2776 const Address poll_byte_addr(Z_thread, in_bytes(JavaThread::polling_word_offset()) + 7 /* Big Endian */);
2777 // Armed page has poll_bit set.
2778 z_tm(poll_byte_addr, SafepointMechanism::poll_bit());
2779 z_brnaz(slow_path);
2780 }
2781
2782 // Don't rely on register locking, always use Z_R1 as scratch register instead.
2783 void MacroAssembler::bang_stack_with_offset(int offset) {
2784 // Stack grows down, caller passes positive offset.
2785 assert(offset > 0, "must bang with positive offset");
2786 if (Displacement::is_validDisp(-offset)) {
2787 z_tmy(-offset, Z_SP, mask_stackbang);
2788 } else {
2789 add2reg(Z_R1, -offset, Z_SP); // Do not destroy Z_SP!!!
2790 z_tm(0, Z_R1, mask_stackbang); // Just banging.
2791 }
2792 }
2793
2794 void MacroAssembler::reserved_stack_check(Register return_pc) {
2795 // Test if reserved zone needs to be enabled.
2796 Label no_reserved_zone_enabling;
2797 assert(return_pc == Z_R14, "Return pc must be in R14 before z_br() to StackOverflow stub.");
2798 BLOCK_COMMENT("reserved_stack_check {");
2799
2800 z_clg(Z_SP, Address(Z_thread, JavaThread::reserved_stack_activation_offset()));
2801 z_brl(no_reserved_zone_enabling);
2802
2803 // Enable reserved zone again, throw stack overflow exception.
2804 save_return_pc();
2805 push_frame_abi160(0);
2806 call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), Z_thread);
2807 pop_frame();
2808 restore_return_pc();
2809
2810 load_const_optimized(Z_R1, SharedRuntime::throw_delayed_StackOverflowError_entry());
2811 // Don't use call() or z_basr(), they will invalidate Z_R14 which contains the return pc.
2812 z_br(Z_R1);
2813
2814 should_not_reach_here();
2815
2816 bind(no_reserved_zone_enabling);
2817 BLOCK_COMMENT("} reserved_stack_check");
2818 }
2819
2820 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
2821 void MacroAssembler::tlab_allocate(Register obj,
2822 Register var_size_in_bytes,
2823 int con_size_in_bytes,
2824 Register t1,
2825 Label& slow_case) {
2826 assert_different_registers(obj, var_size_in_bytes, t1);
2827 Register end = t1;
2828 Register thread = Z_thread;
2829
2830 z_lg(obj, Address(thread, JavaThread::tlab_top_offset()));
2831 if (var_size_in_bytes == noreg) {
2832 z_lay(end, Address(obj, con_size_in_bytes));
2833 } else {
2834 z_lay(end, Address(obj, var_size_in_bytes));
2835 }
2836 z_cg(end, Address(thread, JavaThread::tlab_end_offset()));
2837 branch_optimized(bcondHigh, slow_case);
2838
2839 // Update the tlab top pointer.
2840 z_stg(end, Address(thread, JavaThread::tlab_top_offset()));
2841
2842 // Recover var_size_in_bytes if necessary.
2843 if (var_size_in_bytes == end) {
2844 z_sgr(var_size_in_bytes, obj);
2845 }
2846 }
2847
2848 // Emitter for interface method lookup.
2849 // input: recv_klass, intf_klass, itable_index
2850 // output: method_result
2851 // kills: itable_index, temp1_reg, Z_R0, Z_R1
2852 // TODO: Temp2_reg is unused. we may use this emitter also in the itable stubs.
2853 // If the register is still not needed then, remove it.
2854 void MacroAssembler::lookup_interface_method(Register recv_klass,
2855 Register intf_klass,
2856 RegisterOrConstant itable_index,
2857 Register method_result,
2858 Register temp1_reg,
2859 Label& no_such_interface,
2860 bool return_method) {
2861
2862 const Register vtable_len = temp1_reg; // Used to compute itable_entry_addr.
2863 const Register itable_entry_addr = Z_R1_scratch;
2864 const Register itable_interface = Z_R0_scratch;
2865
2866 BLOCK_COMMENT("lookup_interface_method {");
2867
2868 // Load start of itable entries into itable_entry_addr.
2869 z_llgf(vtable_len, Address(recv_klass, Klass::vtable_length_offset()));
2870 z_sllg(vtable_len, vtable_len, exact_log2(vtableEntry::size_in_bytes()));
2871
2872 // Loop over all itable entries until desired interfaceOop(Rinterface) found.
2873 add2reg_with_index(itable_entry_addr,
2874 in_bytes(Klass::vtable_start_offset() + itableOffsetEntry::interface_offset()),
2875 recv_klass, vtable_len);
2876
2877 const int itable_offset_search_inc = itableOffsetEntry::size() * wordSize;
2878 Label search;
2879
2880 bind(search);
2881
2882 // Handle IncompatibleClassChangeError.
2883 // If the entry is null then we've reached the end of the table
2884 // without finding the expected interface, so throw an exception.
2885 load_and_test_long(itable_interface, Address(itable_entry_addr));
2886 z_bre(no_such_interface);
2887
2888 add2reg(itable_entry_addr, itable_offset_search_inc);
2889 z_cgr(itable_interface, intf_klass);
2890 z_brne(search);
2891
2892 // Entry found and itable_entry_addr points to it, get offset of vtable for interface.
2893 if (return_method) {
2894 const int vtable_offset_offset = in_bytes(itableOffsetEntry::offset_offset() -
2895 itableOffsetEntry::interface_offset()) -
2896 itable_offset_search_inc;
2897
2898 // Compute itableMethodEntry and get method and entry point
2899 // we use addressing with index and displacement, since the formula
2900 // for computing the entry's offset has a fixed and a dynamic part,
2901 // the latter depending on the matched interface entry and on the case,
2902 // that the itable index has been passed as a register, not a constant value.
2903 int method_offset = in_bytes(itableMethodEntry::method_offset());
2904 // Fixed part (displacement), common operand.
2905 Register itable_offset = method_result; // Dynamic part (index register).
2906
2907 if (itable_index.is_register()) {
2908 // Compute the method's offset in that register, for the formula, see the
2909 // else-clause below.
2910 z_sllg(itable_offset, itable_index.as_register(), exact_log2(itableMethodEntry::size() * wordSize));
2911 z_agf(itable_offset, vtable_offset_offset, itable_entry_addr);
2912 } else {
2913 // Displacement increases.
2914 method_offset += itableMethodEntry::size() * wordSize * itable_index.as_constant();
2915
2916 // Load index from itable.
2917 z_llgf(itable_offset, vtable_offset_offset, itable_entry_addr);
2918 }
2919
2920 // Finally load the method's oop.
2921 z_lg(method_result, method_offset, itable_offset, recv_klass);
2922 }
2923 BLOCK_COMMENT("} lookup_interface_method");
2924 }
2925
2926 // Lookup for virtual method invocation.
2927 void MacroAssembler::lookup_virtual_method(Register recv_klass,
2928 RegisterOrConstant vtable_index,
2929 Register method_result) {
2930 assert_different_registers(recv_klass, vtable_index.register_or_noreg());
2931 assert(vtableEntry::size() * wordSize == wordSize,
2932 "else adjust the scaling in the code below");
2933
2934 BLOCK_COMMENT("lookup_virtual_method {");
2935
2936 const int base = in_bytes(Klass::vtable_start_offset());
2937
2938 if (vtable_index.is_constant()) {
2939 // Load with base + disp.
2940 Address vtable_entry_addr(recv_klass,
2941 vtable_index.as_constant() * wordSize +
2942 base +
2943 in_bytes(vtableEntry::method_offset()));
2944
2945 z_lg(method_result, vtable_entry_addr);
2946 } else {
2947 // Shift index properly and load with base + index + disp.
2948 Register vindex = vtable_index.as_register();
2949 Address vtable_entry_addr(recv_klass, vindex,
2950 base + in_bytes(vtableEntry::method_offset()));
2951
2952 z_sllg(vindex, vindex, exact_log2(wordSize));
2953 z_lg(method_result, vtable_entry_addr);
2954 }
2955 BLOCK_COMMENT("} lookup_virtual_method");
2956 }
2957
2958 // Factor out code to call ic_miss_handler.
2959 // Generate code to call the inline cache miss handler.
2960 //
2961 // In most cases, this code will be generated out-of-line.
2962 // The method parameters are intended to provide some variability.
2963 // ICM - Label which has to be bound to the start of useful code (past any traps).
2964 // trapMarker - Marking byte for the generated illtrap instructions (if any).
2965 // Any value except 0x00 is supported.
2966 // = 0x00 - do not generate illtrap instructions.
2967 // use nops to fill unused space.
2968 // requiredSize - required size of the generated code. If the actually
2969 // generated code is smaller, use padding instructions to fill up.
2970 // = 0 - no size requirement, no padding.
2971 // scratch - scratch register to hold branch target address.
2972 //
2973 // The method returns the code offset of the bound label.
2974 unsigned int MacroAssembler::call_ic_miss_handler(Label& ICM, int trapMarker, int requiredSize, Register scratch) {
2975 intptr_t startOffset = offset();
2976
2977 // Prevent entry at content_begin().
2978 if (trapMarker != 0) {
2979 z_illtrap(trapMarker);
2980 }
2981
2982 // Load address of inline cache miss code into scratch register
2983 // and branch to cache miss handler.
2984 BLOCK_COMMENT("IC miss handler {");
2985 BIND(ICM);
2986 unsigned int labelOffset = offset();
2987 AddressLiteral icmiss(SharedRuntime::get_ic_miss_stub());
2988
2989 load_const_optimized(scratch, icmiss);
2990 z_br(scratch);
2991
2992 // Fill unused space.
2993 if (requiredSize > 0) {
2994 while ((offset() - startOffset) < requiredSize) {
2995 if (trapMarker == 0) {
2996 z_nop();
2997 } else {
2998 z_illtrap(trapMarker);
2999 }
3000 }
3001 }
3002 BLOCK_COMMENT("} IC miss handler");
3003 return labelOffset;
3004 }
3005
3006 void MacroAssembler::nmethod_UEP(Label& ic_miss) {
3007 Register ic_reg = Z_inline_cache;
3008 int klass_offset = oopDesc::klass_offset_in_bytes();
3009 if (!ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(klass_offset)) {
3010 if (VM_Version::has_CompareBranch()) {
3011 z_cgij(Z_ARG1, 0, Assembler::bcondEqual, ic_miss);
3012 } else {
3013 z_ltgr(Z_ARG1, Z_ARG1);
3014 z_bre(ic_miss);
3015 }
3016 }
3017 // Compare cached class against klass from receiver.
3018 compare_klass_ptr(ic_reg, klass_offset, Z_ARG1, false);
3019 z_brne(ic_miss);
3020 }
3021
3022 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
3023 Register super_klass,
3024 Register temp1_reg,
3025 Label* L_success,
3026 Label* L_failure,
3027 Label* L_slow_path,
3028 Register super_check_offset) {
3029 // Input registers must not overlap.
3030 assert_different_registers(sub_klass, super_klass, temp1_reg, super_check_offset);
3031
3032 const int sco_offset = in_bytes(Klass::super_check_offset_offset());
3033 bool must_load_sco = ! super_check_offset->is_valid();
3034
3035 // Input registers must not overlap.
3036 if (must_load_sco) {
3037 assert(temp1_reg != noreg, "supply either a temp or a register offset");
3038 }
3039
3040 const Register Rsuper_check_offset = temp1_reg;
3041
3042 NearLabel L_fallthrough;
3043 int label_nulls = 0;
3044 if (L_success == nullptr) { L_success = &L_fallthrough; label_nulls++; }
3045 if (L_failure == nullptr) { L_failure = &L_fallthrough; label_nulls++; }
3046 if (L_slow_path == nullptr) { L_slow_path = &L_fallthrough; label_nulls++; }
3047 assert(label_nulls <= 1 || (L_slow_path == &L_fallthrough && label_nulls <= 2), "at most one null in the batch, usually");
3048
3049 BLOCK_COMMENT("check_klass_subtype_fast_path {");
3050 // If the pointers are equal, we are done (e.g., String[] elements).
3051 // This self-check enables sharing of secondary supertype arrays among
3052 // non-primary types such as array-of-interface. Otherwise, each such
3053 // type would need its own customized SSA.
3054 // We move this check to the front of the fast path because many
3055 // type checks are in fact trivially successful in this manner,
3056 // so we get a nicely predicted branch right at the start of the check.
3057 compare64_and_branch(sub_klass, super_klass, bcondEqual, *L_success);
3058
3059 // Check the supertype display, which is uint.
3060 if (must_load_sco) {
3061 z_llgf(Rsuper_check_offset, sco_offset, super_klass);
3062 super_check_offset = Rsuper_check_offset;
3063 }
3064
3065 Address super_check_addr(sub_klass, super_check_offset, 0);
3066 z_cg(super_klass, super_check_addr); // compare w/ displayed supertype
3067 branch_optimized(Assembler::bcondEqual, *L_success);
3068
3069 // This check has worked decisively for primary supers.
3070 // Secondary supers are sought in the super_cache ('super_cache_addr').
3071 // (Secondary supers are interfaces and very deeply nested subtypes.)
3072 // This works in the same check above because of a tricky aliasing
3073 // between the super_cache and the primary super display elements.
3074 // (The 'super_check_addr' can address either, as the case requires.)
3075 // Note that the cache is updated below if it does not help us find
3076 // what we need immediately.
3077 // So if it was a primary super, we can just fail immediately.
3078 // Otherwise, it's the slow path for us (no success at this point).
3079
3080 // Hacked jmp, which may only be used just before L_fallthrough.
3081 #define final_jmp(label) \
3082 if (&(label) == &L_fallthrough) { /*do nothing*/ } \
3083 else { branch_optimized(Assembler::bcondAlways, label); } /*omit semicolon*/
3084
3085 z_cfi(super_check_offset, in_bytes(Klass::secondary_super_cache_offset()));
3086 if (L_failure == &L_fallthrough) {
3087 branch_optimized(Assembler::bcondEqual, *L_slow_path);
3088 } else {
3089 branch_optimized(Assembler::bcondNotEqual, *L_failure);
3090 final_jmp(*L_slow_path);
3091 }
3092
3093 bind(L_fallthrough);
3094 #undef final_jmp
3095 BLOCK_COMMENT("} check_klass_subtype_fast_path");
3096 // fallthru (to slow path)
3097 }
3098
3099 void MacroAssembler::check_klass_subtype_slow_path_linear(Register Rsubklass,
3100 Register Rsuperklass,
3101 Register Rarray_ptr, // tmp
3102 Register Rlength, // tmp
3103 Label* L_success,
3104 Label* L_failure,
3105 bool set_cond_codes /* unused */) {
3106 // Input registers must not overlap.
3107 // Also check for R1 which is explicitly used here.
3108 assert_different_registers(Z_R1, Rsubklass, Rsuperklass, Rarray_ptr, Rlength);
3109 NearLabel L_fallthrough;
3110 int label_nulls = 0;
3111 if (L_success == nullptr) { L_success = &L_fallthrough; label_nulls++; }
3112 if (L_failure == nullptr) { L_failure = &L_fallthrough; label_nulls++; }
3113 assert(label_nulls <= 1, "at most one null in the batch");
3114
3115 const int ss_offset = in_bytes(Klass::secondary_supers_offset());
3116 const int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
3117
3118 const int length_offset = Array<Klass*>::length_offset_in_bytes();
3119 const int base_offset = Array<Klass*>::base_offset_in_bytes();
3120
3121 // Hacked jmp, which may only be used just before L_fallthrough.
3122 #define final_jmp(label) \
3123 if (&(label) == &L_fallthrough) { /*do nothing*/ } \
3124 else branch_optimized(Assembler::bcondAlways, label) /*omit semicolon*/
3125
3126 NearLabel loop_iterate, loop_count, match;
3127
3128 BLOCK_COMMENT("check_klass_subtype_slow_path_linear {");
3129 z_lg(Rarray_ptr, ss_offset, Rsubklass);
3130
3131 load_and_test_int(Rlength, Address(Rarray_ptr, length_offset));
3132 branch_optimized(Assembler::bcondZero, *L_failure);
3133
3134 // Oops in table are NO MORE compressed.
3135 z_cg(Rsuperklass, base_offset, Rarray_ptr); // Check array element for match.
3136 z_bre(match); // Shortcut for array length = 1.
3137
3138 // No match yet, so we must walk the array's elements.
3139 z_lngfr(Rlength, Rlength);
3140 z_sllg(Rlength, Rlength, LogBytesPerWord); // -#bytes of cache array
3141 z_llill(Z_R1, BytesPerWord); // Set increment/end index.
3142 add2reg(Rlength, 2 * BytesPerWord); // start index = -(n-2)*BytesPerWord
3143 z_slgr(Rarray_ptr, Rlength); // start addr: += (n-2)*BytesPerWord
3144 z_bru(loop_count);
3145
3146 BIND(loop_iterate);
3147 z_cg(Rsuperklass, base_offset, Rlength, Rarray_ptr); // Check array element for match.
3148 z_bre(match);
3149 BIND(loop_count);
3150 z_brxlg(Rlength, Z_R1, loop_iterate);
3151
3152 // Rsuperklass not found among secondary super classes -> failure.
3153 branch_optimized(Assembler::bcondAlways, *L_failure);
3154
3155 // Got a hit. Return success (zero result). Set cache.
3156 // Cache load doesn't happen here. For speed, it is directly emitted by the compiler.
3157
3158 BIND(match);
3159
3160 if (UseSecondarySupersCache) {
3161 z_stg(Rsuperklass, sc_offset, Rsubklass); // Save result to cache.
3162 }
3163 final_jmp(*L_success);
3164
3165 // Exit to the surrounding code.
3166 BIND(L_fallthrough);
3167 #undef final_jmp
3168 BLOCK_COMMENT("} check_klass_subtype_slow_path_linear");
3169 }
3170
3171 // If Register r is invalid, remove a new register from
3172 // available_regs, and add new register to regs_to_push.
3173 Register MacroAssembler::allocate_if_noreg(Register r,
3174 RegSetIterator<Register> &available_regs,
3175 RegSet ®s_to_push) {
3176 if (!r->is_valid()) {
3177 r = *available_regs++;
3178 regs_to_push += r;
3179 }
3180 return r;
3181 }
3182
3183 // check_klass_subtype_slow_path_table() looks for super_klass in the
3184 // hash table belonging to super_klass, branching to L_success or
3185 // L_failure as appropriate. This is essentially a shim which
3186 // allocates registers as necessary and then calls
3187 // lookup_secondary_supers_table() to do the work. Any of the temp
3188 // regs may be noreg, in which case this logic will choose some
3189 // registers push and pop them from the stack.
3190 void MacroAssembler::check_klass_subtype_slow_path_table(Register sub_klass,
3191 Register super_klass,
3192 Register temp_reg,
3193 Register temp2_reg,
3194 Register temp3_reg,
3195 Register temp4_reg,
3196 Register result_reg,
3197 Label* L_success,
3198 Label* L_failure,
3199 bool set_cond_codes) {
3200 BLOCK_COMMENT("check_klass_subtype_slow_path_table {");
3201
3202 RegSet temps = RegSet::of(temp_reg, temp2_reg, temp3_reg, temp4_reg);
3203
3204 assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg, temp4_reg);
3205
3206 Label L_fallthrough;
3207 int label_nulls = 0;
3208 if (L_success == nullptr) { L_success = &L_fallthrough; label_nulls++; }
3209 if (L_failure == nullptr) { L_failure = &L_fallthrough; label_nulls++; }
3210 assert(label_nulls <= 1, "at most one null in the batch");
3211
3212 RegSetIterator<Register> available_regs
3213 // Z_R0 will be used to hold Z_R15(Z_SP) while pushing a new frame, So don't use that here.
3214 // Z_R1 will be used to hold r_bitmap in lookup_secondary_supers_table_var, so can't be used
3215 // Z_R2, Z_R3, Z_R4 will be used in secondary_supers_verify, for the failure reporting
3216 = (RegSet::range(Z_R0, Z_R15) - temps - sub_klass - super_klass - Z_R1_scratch - Z_R0_scratch - Z_R2 - Z_R3 - Z_R4).begin();
3217
3218 RegSet pushed_regs;
3219
3220 temp_reg = allocate_if_noreg(temp_reg, available_regs, pushed_regs);
3221 temp2_reg = allocate_if_noreg(temp2_reg, available_regs, pushed_regs);
3222 temp3_reg = allocate_if_noreg(temp3_reg, available_regs, pushed_regs);;
3223 temp4_reg = allocate_if_noreg(temp4_reg, available_regs, pushed_regs);
3224 result_reg = allocate_if_noreg(result_reg, available_regs, pushed_regs);
3225
3226 const int frame_size = pushed_regs.size() * BytesPerWord + frame::z_abi_160_size;
3227
3228 // Push & save registers
3229 {
3230 int i = 0;
3231 save_return_pc();
3232 push_frame(frame_size);
3233
3234 for (auto it = pushed_regs.begin(); *it != noreg; i++) {
3235 z_stg(*it++, i * BytesPerWord + frame::z_abi_160_size, Z_SP);
3236 }
3237 assert(i * BytesPerWord + frame::z_abi_160_size == frame_size, "sanity");
3238 }
3239
3240 lookup_secondary_supers_table_var(sub_klass,
3241 super_klass,
3242 temp_reg, temp2_reg, temp3_reg, temp4_reg, result_reg);
3243
3244 // NOTE: Condition Code should not be altered before jump instruction below !!!!
3245 z_cghi(result_reg, 0);
3246
3247 {
3248 int i = 0;
3249 for (auto it = pushed_regs.begin(); *it != noreg; ++i) {
3250 z_lg(*it++, i * BytesPerWord + frame::z_abi_160_size, Z_SP);
3251 }
3252 assert(i * BytesPerWord + frame::z_abi_160_size == frame_size, "sanity");
3253 pop_frame();
3254 restore_return_pc();
3255 }
3256
3257 // NB! Callers may assume that, when set_cond_codes is true, this
3258 // code sets temp2_reg to a nonzero value.
3259 if (set_cond_codes) {
3260 z_lghi(temp2_reg, 1);
3261 }
3262
3263 branch_optimized(bcondNotEqual, *L_failure);
3264
3265 if(L_success != &L_fallthrough) {
3266 z_bru(*L_success);
3267 }
3268
3269 bind(L_fallthrough);
3270 BLOCK_COMMENT("} check_klass_subtype_slow_path_table");
3271 }
3272
3273 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
3274 Register super_klass,
3275 Register temp_reg,
3276 Register temp2_reg,
3277 Label* L_success,
3278 Label* L_failure,
3279 bool set_cond_codes) {
3280 BLOCK_COMMENT("check_klass_subtype_slow_path {");
3281 if (UseSecondarySupersTable) {
3282 check_klass_subtype_slow_path_table(sub_klass,
3283 super_klass,
3284 temp_reg,
3285 temp2_reg,
3286 /*temp3*/noreg,
3287 /*temp4*/noreg,
3288 /*result*/noreg,
3289 L_success,
3290 L_failure,
3291 set_cond_codes);
3292 } else {
3293 check_klass_subtype_slow_path_linear(sub_klass,
3294 super_klass,
3295 temp_reg,
3296 temp2_reg,
3297 L_success,
3298 L_failure,
3299 set_cond_codes);
3300 }
3301 BLOCK_COMMENT("} check_klass_subtype_slow_path");
3302 }
3303
3304 // Emitter for combining fast and slow path.
3305 void MacroAssembler::check_klass_subtype(Register sub_klass,
3306 Register super_klass,
3307 Register temp1_reg,
3308 Register temp2_reg,
3309 Label& L_success) {
3310 NearLabel failure;
3311 BLOCK_COMMENT(err_msg("check_klass_subtype(%s subclass of %s) {", sub_klass->name(), super_klass->name()));
3312 check_klass_subtype_fast_path(sub_klass, super_klass, temp1_reg,
3313 &L_success, &failure, nullptr);
3314 check_klass_subtype_slow_path(sub_klass, super_klass,
3315 temp1_reg, temp2_reg, &L_success, nullptr);
3316 BIND(failure);
3317 BLOCK_COMMENT("} check_klass_subtype");
3318 }
3319
3320 // scans r_count pointer sized words at [r_addr] for occurrence of r_value,
3321 // generic (r_count must be >0)
3322 // iff found: CC eq, r_result == 0
3323 void MacroAssembler::repne_scan(Register r_addr, Register r_value, Register r_count, Register r_result) {
3324 NearLabel L_loop, L_exit;
3325
3326 BLOCK_COMMENT("repne_scan {");
3327 #ifdef ASSERT
3328 z_chi(r_count, 0);
3329 asm_assert(bcondHigh, "count must be positive", 11);
3330 #endif
3331
3332 clear_reg(r_result, true /* whole_reg */, false /* set_cc */); // sets r_result=0, let's hope that search will be successful
3333
3334 bind(L_loop);
3335 z_cg(r_value, Address(r_addr));
3336 z_bre(L_exit); // branch on success
3337 z_la(r_addr, wordSize, r_addr);
3338 z_brct(r_count, L_loop);
3339
3340 // z_brct above doesn't change CC.
3341 // If we reach here, then the value in r_value is not present. Set r_result to 1.
3342 z_lghi(r_result, 1);
3343
3344 bind(L_exit);
3345 BLOCK_COMMENT("} repne_scan");
3346 }
3347
3348 // Ensure that the inline code and the stub are using the same registers.
3349 #define LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS \
3350 do { \
3351 assert(r_super_klass == Z_ARG1 && \
3352 r_array_base == Z_ARG5 && \
3353 r_array_length == Z_ARG4 && \
3354 (r_array_index == Z_ARG3 || r_array_index == noreg) && \
3355 (r_sub_klass == Z_ARG2 || r_sub_klass == noreg) && \
3356 (r_bitmap == Z_R10 || r_bitmap == noreg) && \
3357 (r_result == Z_R11 || r_result == noreg), "registers must match s390.ad"); \
3358 } while(0)
3359
3360 // Note: this method also kills Z_R1_scratch register on machines older than z15
3361 void MacroAssembler::lookup_secondary_supers_table_const(Register r_sub_klass,
3362 Register r_super_klass,
3363 Register r_temp1,
3364 Register r_temp2,
3365 Register r_temp3,
3366 Register r_temp4,
3367 Register r_result,
3368 u1 super_klass_slot) {
3369 NearLabel L_done, L_failure;
3370
3371 BLOCK_COMMENT("lookup_secondary_supers_table_const {");
3372
3373 const Register
3374 r_array_base = r_temp1,
3375 r_array_length = r_temp2,
3376 r_array_index = r_temp3,
3377 r_bitmap = r_temp4;
3378
3379 LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS;
3380
3381 z_lg(r_bitmap, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
3382
3383 // First check the bitmap to see if super_klass might be present. If
3384 // the bit is zero, we are certain that super_klass is not one of
3385 // the secondary supers.
3386 u1 bit = super_klass_slot;
3387 int shift_count = Klass::SECONDARY_SUPERS_TABLE_MASK - bit;
3388
3389 z_sllg(r_array_index, r_bitmap, shift_count); // take the bit to 63rd location
3390
3391 // Initialize r_result with 0 (indicating success). If searching fails, r_result will be loaded
3392 // with 1 (failure) at the end of this method.
3393 clear_reg(r_result, true /* whole_reg */, false /* set_cc */); // r_result = 0
3394
3395 // We test the MSB of r_array_index, i.e., its sign bit
3396 testbit(r_array_index, 63);
3397 z_bfalse(L_failure); // if not set, then jump!!!
3398
3399 // We will consult the secondary-super array.
3400 z_lg(r_array_base, Address(r_sub_klass, Klass::secondary_supers_offset()));
3401
3402 // The value i in r_array_index is >= 1, so even though r_array_base
3403 // points to the length, we don't need to adjust it to point to the
3404 // data.
3405 assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "Adjust this code");
3406
3407 // Get the first array index that can contain super_klass.
3408 if (bit != 0) {
3409 pop_count_long(r_array_index, r_array_index, Z_R1_scratch); // kills Z_R1_scratch on machines older than z15
3410
3411 // NB! r_array_index is off by 1. It is compensated by keeping r_array_base off by 1 word.
3412 z_sllg(r_array_index, r_array_index, LogBytesPerWord); // scale
3413 } else {
3414 // Actually use index 0, but r_array_base and r_array_index are off by 1 word
3415 // such that the sum is precise.
3416 z_lghi(r_array_index, BytesPerWord); // for slow path (scaled)
3417 }
3418
3419 z_cg(r_super_klass, Address(r_array_base, r_array_index));
3420 branch_optimized(bcondEqual, L_done); // found a match; success
3421
3422 // Is there another entry to check? Consult the bitmap.
3423 testbit(r_bitmap, (bit + 1) & Klass::SECONDARY_SUPERS_TABLE_MASK);
3424 z_bfalse(L_failure);
3425
3426 // Linear probe. Rotate the bitmap so that the next bit to test is
3427 // in Bit 2 for the look-ahead check in the slow path.
3428 if (bit != 0) {
3429 z_rllg(r_bitmap, r_bitmap, 64-bit); // rotate right
3430 }
3431
3432 // Calls into the stub generated by lookup_secondary_supers_table_slow_path.
3433 // Arguments: r_super_klass, r_array_base, r_array_index, r_bitmap.
3434 // Kills: r_array_length.
3435 // Returns: r_result
3436
3437 call_stub(StubRoutines::lookup_secondary_supers_table_slow_path_stub());
3438
3439 z_bru(L_done); // pass whatever result we got from a slow path
3440
3441 bind(L_failure);
3442
3443 z_lghi(r_result, 1);
3444
3445 bind(L_done);
3446 BLOCK_COMMENT("} lookup_secondary_supers_table_const");
3447
3448 if (VerifySecondarySupers) {
3449 verify_secondary_supers_table(r_sub_klass, r_super_klass, r_result,
3450 r_temp1, r_temp2, r_temp3);
3451 }
3452 }
3453
3454 // At runtime, return 0 in result if r_super_klass is a superclass of
3455 // r_sub_klass, otherwise return nonzero. Use this version of
3456 // lookup_secondary_supers_table() if you don't know ahead of time
3457 // which superclass will be searched for. Used by interpreter and
3458 // runtime stubs. It is larger and has somewhat greater latency than
3459 // the version above, which takes a constant super_klass_slot.
3460 void MacroAssembler::lookup_secondary_supers_table_var(Register r_sub_klass,
3461 Register r_super_klass,
3462 Register temp1,
3463 Register temp2,
3464 Register temp3,
3465 Register temp4,
3466 Register result) {
3467 assert_different_registers(r_sub_klass, r_super_klass, temp1, temp2, temp3, temp4, result, Z_R1_scratch);
3468
3469 Label L_done, L_failure;
3470
3471 BLOCK_COMMENT("lookup_secondary_supers_table_var {");
3472
3473 const Register
3474 r_array_index = temp3,
3475 slot = temp4, // NOTE: "slot" can't be Z_R0 otherwise z_sllg and z_rllg instructions below will mess up!!!!
3476 r_bitmap = Z_R1_scratch;
3477
3478 z_llgc(slot, Address(r_super_klass, Klass::hash_slot_offset()));
3479
3480 // Initialize r_result with 0 (indicating success). If searching fails, r_result will be loaded
3481 // with 1 (failure) at the end of this method.
3482 clear_reg(result, true /* whole_reg */, false /* set_cc */); // result = 0
3483
3484 z_lg(r_bitmap, Address(r_sub_klass, Klass::secondary_supers_bitmap_offset()));
3485
3486 // First check the bitmap to see if super_klass might be present. If
3487 // the bit is zero, we are certain that super_klass is not one of
3488 // the secondary supers.
3489 z_xilf(slot, (u1)(Klass::SECONDARY_SUPERS_TABLE_SIZE - 1)); // slot ^ 63 === 63 - slot (mod 64)
3490 z_sllg(r_array_index, r_bitmap, /*d2 = */ 0, /* b2 = */ slot);
3491
3492 testbit(r_array_index, Klass::SECONDARY_SUPERS_TABLE_SIZE - 1);
3493 branch_optimized(bcondAllZero, L_failure);
3494
3495 const Register
3496 r_array_base = temp1,
3497 r_array_length = temp2;
3498
3499 // Get the first array index that can contain super_klass into r_array_index.
3500 // NOTE: Z_R1_scratch is holding bitmap (look above for r_bitmap). So let's try to save it.
3501 // On the other hand, r_array_base/temp1 is free at current moment (look at the load operation below).
3502 pop_count_long(r_array_index, r_array_index, temp1); // kills r_array_base/temp1 on machines older than z15
3503
3504 // The value i in r_array_index is >= 1, so even though r_array_base
3505 // points to the length, we don't need to adjust it to point to the data.
3506 assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "Adjust this code");
3507 assert(Array<Klass*>::length_offset_in_bytes() == 0, "Adjust this code");
3508
3509 // We will consult the secondary-super array.
3510 z_lg(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
3511
3512 // NB! r_array_index is off by 1. It is compensated by keeping r_array_base off by 1 word.
3513 z_sllg(r_array_index, r_array_index, LogBytesPerWord); // scale, r_array_index is loaded by popcnt above
3514
3515 z_cg(r_super_klass, Address(r_array_base, r_array_index));
3516 branch_optimized(bcondEqual, L_done); // found a match
3517
3518 // Note: this is a small hack:
3519 //
3520 // The operation "(slot ^ 63) === 63 - slot (mod 64)" has already been performed above.
3521 // Since we lack a rotate-right instruction, we achieve the same effect by rotating left
3522 // by "64 - slot" positions. This produces the result equivalent to a right rotation by "slot" positions.
3523 //
3524 // => initial slot value
3525 // => slot = 63 - slot // done above with that z_xilf instruction
3526 // => slot = 64 - slot // need to do for rotating right by "slot" positions
3527 // => slot = 64 - (63 - slot)
3528 // => slot = slot - 63 + 64
3529 // => slot = slot + 1
3530 //
3531 // So instead of rotating-left by 64-slot times, we can, for now, just rotate left by slot+1 and it would be fine.
3532
3533 // Linear probe. Rotate the bitmap so that the next bit to test is
3534 // in Bit 1.
3535 z_aghi(slot, 1); // slot = slot + 1
3536
3537 z_rllg(r_bitmap, r_bitmap, /*d2=*/ 0, /*b2=*/ slot);
3538 testbit(r_bitmap, 1);
3539 branch_optimized(bcondAllZero, L_failure);
3540
3541 // The slot we just inspected is at secondary_supers[r_array_index - 1].
3542 // The next slot to be inspected, by the logic we're about to call,
3543 // is secondary_supers[r_array_index]. Bits 0 and 1 in the bitmap
3544 // have been checked.
3545 lookup_secondary_supers_table_slow_path(r_super_klass, r_array_base, r_array_index,
3546 r_bitmap, /*temp=*/ r_array_length, result, /*is_stub*/false);
3547
3548 // pass whatever we got from slow path
3549 z_bru(L_done);
3550
3551 bind(L_failure);
3552 z_lghi(result, 1); // load 1 to represent failure
3553
3554 bind(L_done);
3555
3556 BLOCK_COMMENT("} lookup_secondary_supers_table_var");
3557
3558 if (VerifySecondarySupers) {
3559 verify_secondary_supers_table(r_sub_klass, r_super_klass, result,
3560 temp1, temp2, temp3);
3561 }
3562 }
3563
3564 // Called by code generated by check_klass_subtype_slow_path
3565 // above. This is called when there is a collision in the hashed
3566 // lookup in the secondary supers array.
3567 void MacroAssembler::lookup_secondary_supers_table_slow_path(Register r_super_klass,
3568 Register r_array_base,
3569 Register r_array_index,
3570 Register r_bitmap,
3571 Register r_temp,
3572 Register r_result,
3573 bool is_stub) {
3574 assert_different_registers(r_super_klass, r_array_base, r_array_index, r_bitmap, r_result, r_temp);
3575
3576 const Register
3577 r_array_length = r_temp,
3578 r_sub_klass = noreg;
3579
3580 if(is_stub) {
3581 LOOKUP_SECONDARY_SUPERS_TABLE_REGISTERS;
3582 }
3583
3584 BLOCK_COMMENT("lookup_secondary_supers_table_slow_path {");
3585 NearLabel L_done, L_failure;
3586
3587 // Load the array length.
3588 z_llgf(r_array_length, Address(r_array_base, Array<Klass*>::length_offset_in_bytes()));
3589
3590 // And adjust the array base to point to the data.
3591 // NB!
3592 // Effectively increments the current slot index by 1.
3593 assert(Array<Klass*>::base_offset_in_bytes() == wordSize, "");
3594 add2reg(r_array_base, Array<Klass*>::base_offset_in_bytes());
3595
3596 // Linear probe
3597 NearLabel L_huge;
3598
3599 // The bitmap is full to bursting.
3600 z_chi(r_array_length, Klass::SECONDARY_SUPERS_BITMAP_FULL - 2);
3601 z_brh(L_huge);
3602
3603 // NB! Our caller has checked bits 0 and 1 in the bitmap. The
3604 // current slot (at secondary_supers[r_array_index]) has not yet
3605 // been inspected, and r_array_index may be out of bounds if we
3606 // wrapped around the end of the array.
3607
3608 { // This is conventional linear probing, but instead of terminating
3609 // when a null entry is found in the table, we maintain a bitmap
3610 // in which a 0 indicates missing entries.
3611 // As long as the bitmap is not completely full,
3612 // array_length == popcount(bitmap). The array_length check above
3613 // guarantees there are 0s in the bitmap, so the loop eventually
3614 // terminates.
3615
3616 #ifdef ASSERT
3617 // r_result is set to 0 by lookup_secondary_supers_table.
3618 // clear_reg(r_result, true /* whole_reg */, false /* set_cc */);
3619 z_cghi(r_result, 0);
3620 asm_assert(bcondEqual, "r_result required to be 0, used by z_locgr", 44);
3621
3622 // We should only reach here after having found a bit in the bitmap.
3623 z_ltgr(r_array_length, r_array_length);
3624 asm_assert(bcondHigh, "array_length > 0, should hold", 22);
3625 #endif // ASSERT
3626
3627 // Compute limit in r_array_length
3628 add2reg(r_array_length, -1);
3629 z_sllg(r_array_length, r_array_length, LogBytesPerWord);
3630
3631 NearLabel L_loop;
3632 bind(L_loop);
3633
3634 // Check for wraparound.
3635 z_cgr(r_array_index, r_array_length);
3636 z_locgr(r_array_index, r_result, bcondHigh); // r_result is containing 0
3637
3638 z_cg(r_super_klass, Address(r_array_base, r_array_index));
3639 z_bre(L_done); // success
3640
3641 // look-ahead check: if Bit 2 is 0, we're done
3642 testbit(r_bitmap, 2);
3643 z_bfalse(L_failure);
3644
3645 z_rllg(r_bitmap, r_bitmap, 64-1); // rotate right
3646 add2reg(r_array_index, BytesPerWord);
3647
3648 z_bru(L_loop);
3649 }
3650
3651 { // Degenerate case: more than 64 secondary supers.
3652 // FIXME: We could do something smarter here, maybe a vectorized
3653 // comparison or a binary search, but is that worth any added
3654 // complexity?
3655
3656 bind(L_huge);
3657 repne_scan(r_array_base, r_super_klass, r_array_length, r_result);
3658
3659 z_bru(L_done); // forward the result we got from repne_scan
3660 }
3661
3662 bind(L_failure);
3663 z_lghi(r_result, 1);
3664
3665 bind(L_done);
3666 BLOCK_COMMENT("} lookup_secondary_supers_table_slow_path");
3667 }
3668
3669 // Make sure that the hashed lookup and a linear scan agree.
3670 void MacroAssembler::verify_secondary_supers_table(Register r_sub_klass,
3671 Register r_super_klass,
3672 Register r_result /* expected */,
3673 Register r_temp1,
3674 Register r_temp2,
3675 Register r_temp3) {
3676 assert_different_registers(r_sub_klass, r_super_klass, r_result, r_temp1, r_temp2, r_temp3);
3677
3678 const Register
3679 r_array_base = r_temp1,
3680 r_array_length = r_temp2,
3681 r_array_index = r_temp3,
3682 r_bitmap = noreg; // unused
3683
3684 BLOCK_COMMENT("verify_secondary_supers_table {");
3685
3686 Label L_passed, L_failure;
3687
3688 // We will consult the secondary-super array.
3689 z_lg(r_array_base, Address(r_sub_klass, in_bytes(Klass::secondary_supers_offset())));
3690
3691 // Load the array length.
3692 z_llgf(r_array_length, Address(r_array_base, Array<Klass*>::length_offset_in_bytes()));
3693
3694 // And adjust the array base to point to the data.
3695 z_aghi(r_array_base, Array<Klass*>::base_offset_in_bytes());
3696
3697 const Register r_linear_result = r_array_index; // reuse
3698 z_chi(r_array_length, 0);
3699 load_on_condition_imm_32(r_linear_result, 1, bcondNotHigh); // load failure if array_length <= 0
3700 z_brc(bcondNotHigh, L_failure);
3701 repne_scan(r_array_base, r_super_klass, r_array_length, r_linear_result);
3702 bind(L_failure);
3703
3704 z_cr(r_result, r_linear_result);
3705 z_bre(L_passed);
3706
3707 // report fatal error and terminate VM
3708
3709 // Argument shuffle
3710 // Z_F1, Z_F3, Z_F5 are volatile regs
3711 z_ldgr(Z_F1, r_super_klass);
3712 z_ldgr(Z_F3, r_sub_klass);
3713 z_ldgr(Z_F5, r_linear_result);
3714
3715 z_lgr(Z_ARG4, r_result);
3716
3717 z_lgdr(Z_ARG1, Z_F1); // r_super_klass
3718 z_lgdr(Z_ARG2, Z_F3); // r_sub_klass
3719 z_lgdr(Z_ARG3, Z_F5); // r_linear_result
3720
3721 const char* msg = "mismatch";
3722 load_const_optimized(Z_ARG5, (address)msg);
3723
3724 call_VM_leaf(CAST_FROM_FN_PTR(address, Klass::on_secondary_supers_verification_failure));
3725 should_not_reach_here();
3726
3727 bind(L_passed);
3728
3729 BLOCK_COMMENT("} verify_secondary_supers_table");
3730 }
3731
3732 void MacroAssembler::clinit_barrier(Register klass, Register thread, Label* L_fast_path, Label* L_slow_path) {
3733 assert(L_fast_path != nullptr || L_slow_path != nullptr, "at least one is required");
3734
3735 Label L_fallthrough;
3736 if (L_fast_path == nullptr) {
3737 L_fast_path = &L_fallthrough;
3738 } else if (L_slow_path == nullptr) {
3739 L_slow_path = &L_fallthrough;
3740 }
3741
3742 // Fast path check: class is fully initialized.
3743 // init_state needs acquire, but S390 is TSO, and so we are already good.
3744 z_cli(Address(klass, InstanceKlass::init_state_offset()), InstanceKlass::fully_initialized);
3745 z_bre(*L_fast_path);
3746
3747 // Fast path check: current thread is initializer thread
3748 z_cg(thread, Address(klass, InstanceKlass::init_thread_offset()));
3749 if (L_slow_path == &L_fallthrough) {
3750 z_bre(*L_fast_path);
3751 } else if (L_fast_path == &L_fallthrough) {
3752 z_brne(*L_slow_path);
3753 } else {
3754 Unimplemented();
3755 }
3756
3757 bind(L_fallthrough);
3758 }
3759
3760 // Increment a counter at counter_address when the eq condition code is
3761 // set. Kills registers tmp1_reg and tmp2_reg and preserves the condition code.
3762 void MacroAssembler::increment_counter_eq(address counter_address, Register tmp1_reg, Register tmp2_reg) {
3763 Label l;
3764 z_brne(l);
3765 load_const(tmp1_reg, counter_address);
3766 add2mem_32(Address(tmp1_reg), 1, tmp2_reg);
3767 z_cr(tmp1_reg, tmp1_reg); // Set cc to eq.
3768 bind(l);
3769 }
3770
3771 void MacroAssembler::resolve_jobject(Register value, Register tmp1, Register tmp2) {
3772 BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
3773 bs->resolve_jobject(this, value, tmp1, tmp2);
3774 }
3775
3776 void MacroAssembler::resolve_global_jobject(Register value, Register tmp1, Register tmp2) {
3777 BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
3778 bs->resolve_global_jobject(this, value, tmp1, tmp2);
3779 }
3780
3781 // Last_Java_sp must comply to the rules in frame_s390.hpp.
3782 void MacroAssembler::set_last_Java_frame(Register last_Java_sp, Register last_Java_pc, bool allow_relocation) {
3783 BLOCK_COMMENT("set_last_Java_frame {");
3784
3785 // Always set last_Java_pc and flags first because once last_Java_sp
3786 // is visible has_last_Java_frame is true and users will look at the
3787 // rest of the fields. (Note: flags should always be zero before we
3788 // get here so doesn't need to be set.)
3789
3790 // Verify that last_Java_pc was zeroed on return to Java.
3791 if (allow_relocation) {
3792 asm_assert_mem8_is_zero(in_bytes(JavaThread::last_Java_pc_offset()),
3793 Z_thread,
3794 "last_Java_pc not zeroed before leaving Java",
3795 0x200);
3796 } else {
3797 asm_assert_mem8_is_zero_static(in_bytes(JavaThread::last_Java_pc_offset()),
3798 Z_thread,
3799 "last_Java_pc not zeroed before leaving Java",
3800 0x200);
3801 }
3802
3803 // When returning from calling out from Java mode the frame anchor's
3804 // last_Java_pc will always be set to null. It is set here so that
3805 // if we are doing a call to native (not VM) that we capture the
3806 // known pc and don't have to rely on the native call having a
3807 // standard frame linkage where we can find the pc.
3808 if (last_Java_pc!=noreg) {
3809 z_stg(last_Java_pc, Address(Z_thread, JavaThread::last_Java_pc_offset()));
3810 }
3811
3812 // This membar release is not required on z/Architecture, since the sequence of stores
3813 // in maintained. Nevertheless, we leave it in to document the required ordering.
3814 // The implementation of z_release() should be empty.
3815 // z_release();
3816
3817 z_stg(last_Java_sp, Address(Z_thread, JavaThread::last_Java_sp_offset()));
3818 BLOCK_COMMENT("} set_last_Java_frame");
3819 }
3820
3821 void MacroAssembler::reset_last_Java_frame(bool check_last_java_sp, bool allow_relocation) {
3822 BLOCK_COMMENT("reset_last_Java_frame {");
3823
3824 if (check_last_java_sp) {
3825 if (allow_relocation) {
3826 asm_assert_mem8_isnot_zero(in_bytes(JavaThread::last_Java_sp_offset()),
3827 Z_thread,
3828 "SP was not set, still zero",
3829 0x202);
3830 } else {
3831 asm_assert_mem8_isnot_zero_static(in_bytes(JavaThread::last_Java_sp_offset()),
3832 Z_thread,
3833 "SP was not set, still zero",
3834 0x202);
3835 }
3836 }
3837
3838 // _last_Java_sp = 0
3839 // Clearing storage must be atomic here, so don't use clear_mem()!
3840 store_const(Address(Z_thread, JavaThread::last_Java_sp_offset()), 0);
3841
3842 // _last_Java_pc = 0
3843 store_const(Address(Z_thread, JavaThread::last_Java_pc_offset()), 0);
3844
3845 BLOCK_COMMENT("} reset_last_Java_frame");
3846 return;
3847 }
3848
3849 void MacroAssembler::set_top_ijava_frame_at_SP_as_last_Java_frame(Register sp, Register tmp1, bool allow_relocation, Label* jpc) {
3850 assert_different_registers(sp, tmp1);
3851
3852 if (jpc == nullptr || jpc->is_bound()) {
3853 load_const_optimized(tmp1, jpc == nullptr ? pc() : target(*jpc));
3854 } else {
3855 load_const(tmp1, *jpc);
3856 }
3857 set_last_Java_frame(/*sp=*/sp, /*pc=*/tmp1, allow_relocation);
3858 }
3859
3860 void MacroAssembler::set_thread_state(JavaThreadState new_state) {
3861 z_release();
3862
3863 assert(Immediate::is_uimm16(_thread_max_state), "enum value out of range for instruction");
3864 assert(sizeof(JavaThreadState) == sizeof(int), "enum value must have base type int");
3865 store_const(Address(Z_thread, JavaThread::thread_state_offset()), new_state, Z_R0, false);
3866 }
3867
3868 void MacroAssembler::get_vm_result_oop(Register oop_result) {
3869 z_lg(oop_result, Address(Z_thread, JavaThread::vm_result_oop_offset()));
3870 clear_mem(Address(Z_thread, JavaThread::vm_result_oop_offset()), sizeof(void*));
3871
3872 verify_oop(oop_result, FILE_AND_LINE);
3873 }
3874
3875 void MacroAssembler::get_vm_result_metadata(Register result) {
3876 z_lg(result, Address(Z_thread, JavaThread::vm_result_metadata_offset()));
3877 clear_mem(Address(Z_thread, JavaThread::vm_result_metadata_offset()), sizeof(void*));
3878 }
3879
3880 // We require that C code which does not return a value in vm_result will
3881 // leave it undisturbed.
3882 void MacroAssembler::set_vm_result(Register oop_result) {
3883 z_stg(oop_result, Address(Z_thread, JavaThread::vm_result_oop_offset()));
3884 }
3885
3886 // Explicit null checks (used for method handle code).
3887 void MacroAssembler::null_check(Register reg, Register tmp, int64_t offset) {
3888 if (!ImplicitNullChecks) {
3889 NearLabel ok;
3890
3891 compare64_and_branch(reg, (intptr_t) 0, Assembler::bcondNotEqual, ok);
3892
3893 // We just put the address into reg if it was 0 (tmp==Z_R0 is allowed so we can't use it for the address).
3894 address exception_entry = Interpreter::throw_NullPointerException_entry();
3895 load_absolute_address(reg, exception_entry);
3896 z_br(reg);
3897
3898 bind(ok);
3899 } else {
3900 if (needs_explicit_null_check((intptr_t)offset)) {
3901 // Provoke OS null exception if reg is null by
3902 // accessing M[reg] w/o changing any registers.
3903 z_lg(tmp, 0, reg);
3904 }
3905 // else
3906 // Nothing to do, (later) access of M[reg + offset]
3907 // will provoke OS null exception if reg is null.
3908 }
3909 }
3910
3911 //-------------------------------------
3912 // Compressed Klass Pointers
3913 //-------------------------------------
3914
3915 // Klass oop manipulations if compressed.
3916 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
3917 Register current = (src != noreg) ? src : dst; // Klass is in dst if no src provided. (dst == src) also possible.
3918 address base = CompressedKlassPointers::base();
3919 int shift = CompressedKlassPointers::shift();
3920 bool need_zero_extend = base != nullptr;
3921
3922 BLOCK_COMMENT("cKlass encoder {");
3923
3924 #ifdef ASSERT
3925 Label ok;
3926 z_tmll(current, CompressedKlassPointers::klass_alignment_in_bytes() - 1); // Check alignment.
3927 z_brc(Assembler::bcondAllZero, ok);
3928 // The plain disassembler does not recognize illtrap. It instead displays
3929 // a 32-bit value. Issuing two illtraps assures the disassembler finds
3930 // the proper beginning of the next instruction.
3931 z_illtrap(0xee);
3932 z_illtrap(0xee);
3933 bind(ok);
3934 #endif
3935
3936 // Scale down the incoming klass pointer first.
3937 // We then can be sure we calculate an offset that fits into 32 bit.
3938 // More generally speaking: all subsequent calculations are purely 32-bit.
3939 if (shift != 0) {
3940 z_srlg(dst, current, shift);
3941 current = dst;
3942 }
3943
3944 if (base != nullptr) {
3945 // Use scaled-down base address parts to match scaled-down klass pointer.
3946 unsigned int base_h = ((unsigned long)base)>>(32+shift);
3947 unsigned int base_l = (unsigned int)(((unsigned long)base)>>shift);
3948
3949 // General considerations:
3950 // - when calculating (current_h - base_h), all digits must cancel (become 0).
3951 // Otherwise, we would end up with a compressed klass pointer which doesn't
3952 // fit into 32-bit.
3953 // - Only bit#33 of the difference could potentially be non-zero. For that
3954 // to happen, (current_l < base_l) must hold. In this case, the subtraction
3955 // will create a borrow out of bit#32, nicely killing bit#33.
3956 // - With the above, we only need to consider current_l and base_l to
3957 // calculate the result.
3958 // - Both values are treated as unsigned. The unsigned subtraction is
3959 // replaced by adding (unsigned) the 2's complement of the subtrahend.
3960
3961 if (base_l == 0) {
3962 // - By theory, the calculation to be performed here (current_h - base_h) MUST
3963 // cancel all high-word bits. Otherwise, we would end up with an offset
3964 // (i.e. compressed klass pointer) that does not fit into 32 bit.
3965 // - current_l remains unchanged.
3966 // - Therefore, we can replace all calculation with just a
3967 // zero-extending load 32 to 64 bit.
3968 // - Even that can be replaced with a conditional load if dst != current.
3969 // (this is a local view. The shift step may have requested zero-extension).
3970 } else {
3971 if ((base_h == 0) && is_uimm(base_l, 31)) {
3972 // If we happen to find that (base_h == 0), and that base_l is within the range
3973 // which can be represented by a signed int, then we can use 64bit signed add with
3974 // (-base_l) as 32bit signed immediate operand. The add will take care of the
3975 // upper 32 bits of the result, saving us the need of an extra zero extension.
3976 // For base_l to be in the required range, it must not have the most significant
3977 // bit (aka sign bit) set.
3978 lgr_if_needed(dst, current); // no zero/sign extension in this case!
3979 z_agfi(dst, -(int)base_l); // base_l must be passed as signed.
3980 need_zero_extend = false;
3981 current = dst;
3982 } else {
3983 // To begin with, we may need to copy and/or zero-extend the register operand.
3984 // We have to calculate (current_l - base_l). Because there is no unsigend
3985 // subtract instruction with immediate operand, we add the 2's complement of base_l.
3986 if (need_zero_extend) {
3987 z_llgfr(dst, current);
3988 need_zero_extend = false;
3989 } else {
3990 llgfr_if_needed(dst, current);
3991 }
3992 current = dst;
3993 z_alfi(dst, -base_l);
3994 }
3995 }
3996 }
3997
3998 if (need_zero_extend) {
3999 // We must zero-extend the calculated result. It may have some leftover bits in
4000 // the hi-word because we only did optimized calculations.
4001 z_llgfr(dst, current);
4002 } else {
4003 llgfr_if_needed(dst, current); // zero-extension while copying comes at no extra cost.
4004 }
4005
4006 BLOCK_COMMENT("} cKlass encoder");
4007 }
4008
4009 // This function calculates the size of the code generated by
4010 // decode_klass_not_null(register dst, Register src)
4011 // when Universe::heap() isn't null. Hence, if the instructions
4012 // it generates change, then this method needs to be updated.
4013 int MacroAssembler::instr_size_for_decode_klass_not_null() {
4014 address base = CompressedKlassPointers::base();
4015 int shift_size = CompressedKlassPointers::shift() == 0 ? 0 : 6; /* sllg */
4016 int addbase_size = 0;
4017
4018 if (base != nullptr) {
4019 unsigned int base_h = ((unsigned long)base)>>32;
4020 unsigned int base_l = (unsigned int)((unsigned long)base);
4021 if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
4022 addbase_size += 6; /* aih */
4023 } else if ((base_h == 0) && (base_l != 0)) {
4024 addbase_size += 6; /* algfi */
4025 } else {
4026 addbase_size += load_const_size();
4027 addbase_size += 4; /* algr */
4028 }
4029 }
4030 #ifdef ASSERT
4031 addbase_size += 10;
4032 addbase_size += 2; // Extra sigill.
4033 #endif
4034 return addbase_size + shift_size;
4035 }
4036
4037 // !!! If the instructions that get generated here change
4038 // then function instr_size_for_decode_klass_not_null()
4039 // needs to get updated.
4040 // This variant of decode_klass_not_null() must generate predictable code!
4041 // The code must only depend on globally known parameters.
4042 void MacroAssembler::decode_klass_not_null(Register dst) {
4043 address base = CompressedKlassPointers::base();
4044 int shift = CompressedKlassPointers::shift();
4045 int beg_off = offset();
4046
4047 BLOCK_COMMENT("cKlass decoder (const size) {");
4048
4049 if (shift != 0) { // Shift required?
4050 z_sllg(dst, dst, shift);
4051 }
4052 if (base != nullptr) {
4053 unsigned int base_h = ((unsigned long)base)>>32;
4054 unsigned int base_l = (unsigned int)((unsigned long)base);
4055 if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
4056 z_aih(dst, base_h); // Base has no set bits in lower half.
4057 } else if ((base_h == 0) && (base_l != 0)) {
4058 z_algfi(dst, base_l); // Base has no set bits in upper half.
4059 } else {
4060 load_const(Z_R0, base); // Base has set bits everywhere.
4061 z_algr(dst, Z_R0);
4062 }
4063 }
4064
4065 #ifdef ASSERT
4066 Label ok;
4067 z_tmll(dst, CompressedKlassPointers::klass_alignment_in_bytes() - 1); // Check alignment.
4068 z_brc(Assembler::bcondAllZero, ok);
4069 // The plain disassembler does not recognize illtrap. It instead displays
4070 // a 32-bit value. Issuing two illtraps assures the disassembler finds
4071 // the proper beginning of the next instruction.
4072 z_illtrap(0xd1);
4073 z_illtrap(0xd1);
4074 bind(ok);
4075 #endif
4076 assert(offset() == beg_off + instr_size_for_decode_klass_not_null(), "Code gen mismatch.");
4077
4078 BLOCK_COMMENT("} cKlass decoder (const size)");
4079 }
4080
4081 // This variant of decode_klass_not_null() is for cases where
4082 // 1) the size of the generated instructions may vary
4083 // 2) the result is (potentially) stored in a register different from the source.
4084 void MacroAssembler::decode_klass_not_null(Register dst, Register src) {
4085 address base = CompressedKlassPointers::base();
4086 int shift = CompressedKlassPointers::shift();
4087
4088 BLOCK_COMMENT("cKlass decoder {");
4089
4090 if (src == noreg) src = dst;
4091
4092 if (shift != 0) { // Shift or at least move required?
4093 z_sllg(dst, src, shift);
4094 } else {
4095 lgr_if_needed(dst, src);
4096 }
4097
4098 if (base != nullptr) {
4099 unsigned int base_h = ((unsigned long)base)>>32;
4100 unsigned int base_l = (unsigned int)((unsigned long)base);
4101 if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
4102 z_aih(dst, base_h); // Base has not set bits in lower half.
4103 } else if ((base_h == 0) && (base_l != 0)) {
4104 z_algfi(dst, base_l); // Base has no set bits in upper half.
4105 } else {
4106 load_const_optimized(Z_R0, base); // Base has set bits everywhere.
4107 z_algr(dst, Z_R0);
4108 }
4109 }
4110
4111 #ifdef ASSERT
4112 Label ok;
4113 z_tmll(dst, CompressedKlassPointers::klass_alignment_in_bytes() - 1); // Check alignment.
4114 z_brc(Assembler::bcondAllZero, ok);
4115 // The plain disassembler does not recognize illtrap. It instead displays
4116 // a 32-bit value. Issuing two illtraps assures the disassembler finds
4117 // the proper beginning of the next instruction.
4118 z_illtrap(0xd2);
4119 z_illtrap(0xd2);
4120 bind(ok);
4121 #endif
4122 BLOCK_COMMENT("} cKlass decoder");
4123 }
4124
4125 void MacroAssembler::load_klass(Register klass, Address mem) {
4126 z_llgf(klass, mem);
4127 // Attention: no null check here!
4128 decode_klass_not_null(klass);
4129 }
4130
4131 // Loads the obj's Klass* into dst.
4132 // Input:
4133 // src - the oop we want to load the klass from.
4134 // dst - output nklass.
4135 void MacroAssembler::load_narrow_klass_compact(Register dst, Register src) {
4136 BLOCK_COMMENT("load_narrow_klass_compact {");
4137 assert(UseCompactObjectHeaders, "expects UseCompactObjectHeaders");
4138 z_lg(dst, Address(src, oopDesc::mark_offset_in_bytes()));
4139 z_srlg(dst, dst, markWord::klass_shift);
4140 BLOCK_COMMENT("} load_narrow_klass_compact");
4141 }
4142
4143 void MacroAssembler::cmp_klass(Register klass, Register obj, Register tmp) {
4144 BLOCK_COMMENT("cmp_klass {");
4145 assert_different_registers(obj, klass, tmp);
4146 if (UseCompactObjectHeaders) {
4147 assert(tmp != noreg, "required");
4148 assert_different_registers(klass, obj, tmp);
4149 load_narrow_klass_compact(tmp, obj);
4150 z_cr(klass, tmp);
4151 } else {
4152 z_c(klass, Address(obj, oopDesc::klass_offset_in_bytes()));
4153 }
4154 BLOCK_COMMENT("} cmp_klass");
4155 }
4156
4157 void MacroAssembler::cmp_klasses_from_objects(Register obj1, Register obj2, Register tmp1, Register tmp2) {
4158 BLOCK_COMMENT("cmp_klasses_from_objects {");
4159 if (UseCompactObjectHeaders) {
4160 assert(tmp1 != noreg && tmp2 != noreg, "required");
4161 assert_different_registers(obj1, obj2, tmp1, tmp2);
4162 load_narrow_klass_compact(tmp1, obj1);
4163 load_narrow_klass_compact(tmp2, obj2);
4164 z_cr(tmp1, tmp2);
4165 } else {
4166 z_l(tmp1, Address(obj1, oopDesc::klass_offset_in_bytes()));
4167 z_c(tmp1, Address(obj2, oopDesc::klass_offset_in_bytes()));
4168 }
4169 BLOCK_COMMENT("} cmp_klasses_from_objects");
4170 }
4171
4172 void MacroAssembler::load_klass(Register klass, Register src_oop) {
4173 if (UseCompactObjectHeaders) {
4174 load_narrow_klass_compact(klass, src_oop);
4175 decode_klass_not_null(klass);
4176 } else {
4177 z_llgf(klass, oopDesc::klass_offset_in_bytes(), src_oop);
4178 decode_klass_not_null(klass);
4179 }
4180 }
4181
4182 void MacroAssembler::store_klass(Register klass, Register dst_oop, Register ck) {
4183 assert(!UseCompactObjectHeaders, "Don't use with compact headers");
4184 assert_different_registers(dst_oop, klass, Z_R0);
4185 if (ck == noreg) ck = klass;
4186 encode_klass_not_null(ck, klass);
4187 z_st(ck, Address(dst_oop, oopDesc::klass_offset_in_bytes()));
4188 }
4189
4190 void MacroAssembler::store_klass_gap(Register s, Register d) {
4191 assert(!UseCompactObjectHeaders, "Don't use with compact headers");
4192 assert(s != d, "not enough registers");
4193 // Support s = noreg.
4194 if (s != noreg) {
4195 z_st(s, Address(d, oopDesc::klass_gap_offset_in_bytes()));
4196 } else {
4197 z_mvhi(Address(d, oopDesc::klass_gap_offset_in_bytes()), 0);
4198 }
4199 }
4200
4201 // Compare klass ptr in memory against klass ptr in register.
4202 //
4203 // Rop1 - klass in register, always uncompressed.
4204 // disp - Offset of klass in memory, compressed/uncompressed, depending on runtime flag.
4205 // Rbase - Base address of cKlass in memory.
4206 // maybenull - True if Rop1 possibly is a null.
4207 void MacroAssembler::compare_klass_ptr(Register Rop1, int64_t disp, Register Rbase, bool maybenull) {
4208
4209 BLOCK_COMMENT("compare klass ptr {");
4210
4211 const int shift = CompressedKlassPointers::shift();
4212 address base = CompressedKlassPointers::base();
4213
4214 if (UseCompactObjectHeaders) {
4215 assert(shift >= 3, "cKlass encoder detected bad shift");
4216 } else {
4217 assert((shift == 0) || (shift == 3), "cKlass encoder detected bad shift");
4218 }
4219 assert_different_registers(Rop1, Z_R0);
4220 assert_different_registers(Rop1, Rbase, Z_R1);
4221
4222 // First encode register oop and then compare with cOop in memory.
4223 // This sequence saves an unnecessary cOop load and decode.
4224 if (base == nullptr) {
4225 if (shift == 0) {
4226 z_cl(Rop1, disp, Rbase); // Unscaled
4227 } else {
4228 z_srlg(Z_R0, Rop1, shift); // ZeroBased
4229 z_cl(Z_R0, disp, Rbase);
4230 }
4231 } else { // HeapBased
4232 #ifdef ASSERT
4233 bool used_R0 = true;
4234 bool used_R1 = true;
4235 #endif
4236 Register current = Rop1;
4237 Label done;
4238
4239 if (maybenull) { // null pointer must be preserved!
4240 z_ltgr(Z_R0, current);
4241 z_bre(done);
4242 current = Z_R0;
4243 }
4244
4245 unsigned int base_h = ((unsigned long)base)>>32;
4246 unsigned int base_l = (unsigned int)((unsigned long)base);
4247 if ((base_h != 0) && (base_l == 0) && VM_Version::has_HighWordInstr()) {
4248 lgr_if_needed(Z_R0, current);
4249 z_aih(Z_R0, -((int)base_h)); // Base has no set bits in lower half.
4250 } else if ((base_h == 0) && (base_l != 0)) {
4251 lgr_if_needed(Z_R0, current);
4252 z_agfi(Z_R0, -(int)base_l);
4253 } else {
4254 int pow2_offset = get_oop_base_complement(Z_R1, ((uint64_t)(intptr_t)base));
4255 add2reg_with_index(Z_R0, pow2_offset, Z_R1, Rop1); // Subtract base by adding complement.
4256 }
4257
4258 if (shift != 0) {
4259 z_srlg(Z_R0, Z_R0, shift);
4260 }
4261 bind(done);
4262 z_cl(Z_R0, disp, Rbase);
4263 #ifdef ASSERT
4264 if (used_R0) preset_reg(Z_R0, 0xb05bUL, 2);
4265 if (used_R1) preset_reg(Z_R1, 0xb06bUL, 2);
4266 #endif
4267 }
4268
4269 BLOCK_COMMENT("} compare klass ptr");
4270 }
4271
4272 //---------------------------
4273 // Compressed oops
4274 //---------------------------
4275
4276 void MacroAssembler::encode_heap_oop(Register oop) {
4277 oop_encoder(oop, oop, true /*maybe null*/);
4278 }
4279
4280 void MacroAssembler::encode_heap_oop_not_null(Register oop) {
4281 oop_encoder(oop, oop, false /*not null*/);
4282 }
4283
4284 // Called with something derived from the oop base. e.g. oop_base>>3.
4285 int MacroAssembler::get_oop_base_pow2_offset(uint64_t oop_base) {
4286 unsigned int oop_base_ll = ((unsigned int)(oop_base >> 0)) & 0xffff;
4287 unsigned int oop_base_lh = ((unsigned int)(oop_base >> 16)) & 0xffff;
4288 unsigned int oop_base_hl = ((unsigned int)(oop_base >> 32)) & 0xffff;
4289 unsigned int oop_base_hh = ((unsigned int)(oop_base >> 48)) & 0xffff;
4290 unsigned int n_notzero_parts = (oop_base_ll == 0 ? 0:1)
4291 + (oop_base_lh == 0 ? 0:1)
4292 + (oop_base_hl == 0 ? 0:1)
4293 + (oop_base_hh == 0 ? 0:1);
4294
4295 assert(oop_base != 0, "This is for HeapBased cOops only");
4296
4297 if (n_notzero_parts != 1) { // Check if oop_base is just a few pages shy of a power of 2.
4298 uint64_t pow2_offset = 0x10000 - oop_base_ll;
4299 if (pow2_offset < 0x8000) { // This might not be necessary.
4300 uint64_t oop_base2 = oop_base + pow2_offset;
4301
4302 oop_base_ll = ((unsigned int)(oop_base2 >> 0)) & 0xffff;
4303 oop_base_lh = ((unsigned int)(oop_base2 >> 16)) & 0xffff;
4304 oop_base_hl = ((unsigned int)(oop_base2 >> 32)) & 0xffff;
4305 oop_base_hh = ((unsigned int)(oop_base2 >> 48)) & 0xffff;
4306 n_notzero_parts = (oop_base_ll == 0 ? 0:1) +
4307 (oop_base_lh == 0 ? 0:1) +
4308 (oop_base_hl == 0 ? 0:1) +
4309 (oop_base_hh == 0 ? 0:1);
4310 if (n_notzero_parts == 1) {
4311 assert(-(int64_t)pow2_offset != (int64_t)-1, "We use -1 to signal uninitialized base register");
4312 return -pow2_offset;
4313 }
4314 }
4315 }
4316 return 0;
4317 }
4318
4319 // If base address is offset from a straight power of two by just a few pages,
4320 // return this offset to the caller for a possible later composite add.
4321 // TODO/FIX: will only work correctly for 4k pages.
4322 int MacroAssembler::get_oop_base(Register Rbase, uint64_t oop_base) {
4323 int pow2_offset = get_oop_base_pow2_offset(oop_base);
4324
4325 load_const_optimized(Rbase, oop_base - pow2_offset); // Best job possible.
4326
4327 return pow2_offset;
4328 }
4329
4330 int MacroAssembler::get_oop_base_complement(Register Rbase, uint64_t oop_base) {
4331 int offset = get_oop_base(Rbase, oop_base);
4332 z_lcgr(Rbase, Rbase);
4333 return -offset;
4334 }
4335
4336 // Compare compressed oop in memory against oop in register.
4337 // Rop1 - Oop in register.
4338 // disp - Offset of cOop in memory.
4339 // Rbase - Base address of cOop in memory.
4340 // maybenull - True if Rop1 possibly is a null.
4341 // maybenulltarget - Branch target for Rop1 == nullptr, if flow control shall NOT continue with compare instruction.
4342 void MacroAssembler::compare_heap_oop(Register Rop1, Address mem, bool maybenull) {
4343 Register Rbase = mem.baseOrR0();
4344 Register Rindex = mem.indexOrR0();
4345 int64_t disp = mem.disp();
4346
4347 const int shift = CompressedOops::shift();
4348 address base = CompressedOops::base();
4349
4350 assert(UseCompressedOops, "must be on to call this method");
4351 assert(Universe::heap() != nullptr, "java heap must be initialized to call this method");
4352 assert((shift == 0) || (shift == LogMinObjAlignmentInBytes), "cOop encoder detected bad shift");
4353 assert_different_registers(Rop1, Z_R0);
4354 assert_different_registers(Rop1, Rbase, Z_R1);
4355 assert_different_registers(Rop1, Rindex, Z_R1);
4356
4357 BLOCK_COMMENT("compare heap oop {");
4358
4359 // First encode register oop and then compare with cOop in memory.
4360 // This sequence saves an unnecessary cOop load and decode.
4361 if (base == nullptr) {
4362 if (shift == 0) {
4363 z_cl(Rop1, disp, Rindex, Rbase); // Unscaled
4364 } else {
4365 z_srlg(Z_R0, Rop1, shift); // ZeroBased
4366 z_cl(Z_R0, disp, Rindex, Rbase);
4367 }
4368 } else { // HeapBased
4369 #ifdef ASSERT
4370 bool used_R0 = true;
4371 bool used_R1 = true;
4372 #endif
4373 Label done;
4374 int pow2_offset = get_oop_base_complement(Z_R1, ((uint64_t)(intptr_t)base));
4375
4376 if (maybenull) { // null pointer must be preserved!
4377 z_ltgr(Z_R0, Rop1);
4378 z_bre(done);
4379 }
4380
4381 add2reg_with_index(Z_R0, pow2_offset, Z_R1, Rop1);
4382 z_srlg(Z_R0, Z_R0, shift);
4383
4384 bind(done);
4385 z_cl(Z_R0, disp, Rindex, Rbase);
4386 #ifdef ASSERT
4387 if (used_R0) preset_reg(Z_R0, 0xb05bUL, 2);
4388 if (used_R1) preset_reg(Z_R1, 0xb06bUL, 2);
4389 #endif
4390 }
4391 BLOCK_COMMENT("} compare heap oop");
4392 }
4393
4394 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators,
4395 const Address& addr, Register val,
4396 Register tmp1, Register tmp2, Register tmp3) {
4397 assert((decorators & ~(AS_RAW | IN_HEAP | IN_NATIVE | IS_ARRAY | IS_NOT_NULL |
4398 ON_UNKNOWN_OOP_REF)) == 0, "unsupported decorator");
4399 BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4400 decorators = AccessInternal::decorator_fixup(decorators, type);
4401 bool as_raw = (decorators & AS_RAW) != 0;
4402 if (as_raw) {
4403 bs->BarrierSetAssembler::store_at(this, decorators, type,
4404 addr, val,
4405 tmp1, tmp2, tmp3);
4406 } else {
4407 bs->store_at(this, decorators, type,
4408 addr, val,
4409 tmp1, tmp2, tmp3);
4410 }
4411 }
4412
4413 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators,
4414 const Address& addr, Register dst,
4415 Register tmp1, Register tmp2, Label *is_null) {
4416 assert((decorators & ~(AS_RAW | IN_HEAP | IN_NATIVE | IS_ARRAY | IS_NOT_NULL |
4417 ON_PHANTOM_OOP_REF | ON_WEAK_OOP_REF)) == 0, "unsupported decorator");
4418 BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4419 decorators = AccessInternal::decorator_fixup(decorators, type);
4420 bool as_raw = (decorators & AS_RAW) != 0;
4421 if (as_raw) {
4422 bs->BarrierSetAssembler::load_at(this, decorators, type,
4423 addr, dst,
4424 tmp1, tmp2, is_null);
4425 } else {
4426 bs->load_at(this, decorators, type,
4427 addr, dst,
4428 tmp1, tmp2, is_null);
4429 }
4430 }
4431
4432 void MacroAssembler::load_heap_oop(Register dest, const Address &a,
4433 Register tmp1, Register tmp2,
4434 DecoratorSet decorators, Label *is_null) {
4435 access_load_at(T_OBJECT, IN_HEAP | decorators, a, dest, tmp1, tmp2, is_null);
4436 }
4437
4438 void MacroAssembler::store_heap_oop(Register Roop, const Address &a,
4439 Register tmp1, Register tmp2, Register tmp3,
4440 DecoratorSet decorators) {
4441 access_store_at(T_OBJECT, IN_HEAP | decorators, a, Roop, tmp1, tmp2, tmp3);
4442 }
4443
4444 //-------------------------------------------------
4445 // Encode compressed oop. Generally usable encoder.
4446 //-------------------------------------------------
4447 // Rsrc - contains regular oop on entry. It remains unchanged.
4448 // Rdst - contains compressed oop on exit.
4449 // Rdst and Rsrc may indicate same register, in which case Rsrc does not remain unchanged.
4450 //
4451 // Rdst must not indicate scratch register Z_R1 (Z_R1_scratch) for functionality.
4452 // Rdst should not indicate scratch register Z_R0 (Z_R0_scratch) for performance.
4453 //
4454 // only32bitValid is set, if later code only uses the lower 32 bits. In this
4455 // case we must not fix the upper 32 bits.
4456 void MacroAssembler::oop_encoder(Register Rdst, Register Rsrc, bool maybenull,
4457 Register Rbase, int pow2_offset, bool only32bitValid) {
4458
4459 const address oop_base = CompressedOops::base();
4460 const int oop_shift = CompressedOops::shift();
4461 const bool disjoint = CompressedOops::base_disjoint();
4462
4463 assert(UseCompressedOops, "must be on to call this method");
4464 assert(Universe::heap() != nullptr, "java heap must be initialized to call this encoder");
4465 assert((oop_shift == 0) || (oop_shift == LogMinObjAlignmentInBytes), "cOop encoder detected bad shift");
4466
4467 if (disjoint || (oop_base == nullptr)) {
4468 BLOCK_COMMENT("cOop encoder zeroBase {");
4469 if (oop_shift == 0) {
4470 if (oop_base != nullptr && !only32bitValid) {
4471 z_llgfr(Rdst, Rsrc); // Clear upper bits in case the register will be decoded again.
4472 } else {
4473 lgr_if_needed(Rdst, Rsrc);
4474 }
4475 } else {
4476 z_srlg(Rdst, Rsrc, oop_shift);
4477 if (oop_base != nullptr && !only32bitValid) {
4478 z_llgfr(Rdst, Rdst); // Clear upper bits in case the register will be decoded again.
4479 }
4480 }
4481 BLOCK_COMMENT("} cOop encoder zeroBase");
4482 return;
4483 }
4484
4485 bool used_R0 = false;
4486 bool used_R1 = false;
4487
4488 BLOCK_COMMENT("cOop encoder general {");
4489 assert_different_registers(Rdst, Z_R1);
4490 assert_different_registers(Rsrc, Rbase);
4491 if (maybenull) {
4492 Label done;
4493 // We reorder shifting and subtracting, so that we can compare
4494 // and shift in parallel:
4495 //
4496 // cycle 0: potential LoadN, base = <const>
4497 // cycle 1: base = !base dst = src >> 3, cmp cr = (src != 0)
4498 // cycle 2: if (cr) br, dst = dst + base + offset
4499
4500 // Get oop_base components.
4501 if (pow2_offset == -1) {
4502 if (Rdst == Rbase) {
4503 if (Rdst == Z_R1 || Rsrc == Z_R1) {
4504 Rbase = Z_R0;
4505 used_R0 = true;
4506 } else {
4507 Rdst = Z_R1;
4508 used_R1 = true;
4509 }
4510 }
4511 if (Rbase == Z_R1) {
4512 used_R1 = true;
4513 }
4514 pow2_offset = get_oop_base_complement(Rbase, ((uint64_t)(intptr_t)oop_base) >> oop_shift);
4515 }
4516 assert_different_registers(Rdst, Rbase);
4517
4518 // Check for null oop (must be left alone) and shift.
4519 if (oop_shift != 0) { // Shift out alignment bits
4520 if (((intptr_t)oop_base&0xc000000000000000L) == 0L) { // We are sure: no single address will have the leftmost bit set.
4521 z_srag(Rdst, Rsrc, oop_shift); // Arithmetic shift sets the condition code.
4522 } else {
4523 z_srlg(Rdst, Rsrc, oop_shift);
4524 z_ltgr(Rsrc, Rsrc); // This is the recommended way of testing for zero.
4525 // This probably is faster, as it does not write a register. No!
4526 // z_cghi(Rsrc, 0);
4527 }
4528 } else {
4529 z_ltgr(Rdst, Rsrc); // Move null to result register.
4530 }
4531 z_bre(done);
4532
4533 // Subtract oop_base components.
4534 if ((Rdst == Z_R0) || (Rbase == Z_R0)) {
4535 z_algr(Rdst, Rbase);
4536 if (pow2_offset != 0) { add2reg(Rdst, pow2_offset); }
4537 } else {
4538 add2reg_with_index(Rdst, pow2_offset, Rbase, Rdst);
4539 }
4540 if (!only32bitValid) {
4541 z_llgfr(Rdst, Rdst); // Clear upper bits in case the register will be decoded again.
4542 }
4543 bind(done);
4544
4545 } else { // not null
4546 // Get oop_base components.
4547 if (pow2_offset == -1) {
4548 pow2_offset = get_oop_base_complement(Rbase, (uint64_t)(intptr_t)oop_base);
4549 }
4550
4551 // Subtract oop_base components and shift.
4552 if (Rdst == Z_R0 || Rsrc == Z_R0 || Rbase == Z_R0) {
4553 // Don't use lay instruction.
4554 if (Rdst == Rsrc) {
4555 z_algr(Rdst, Rbase);
4556 } else {
4557 lgr_if_needed(Rdst, Rbase);
4558 z_algr(Rdst, Rsrc);
4559 }
4560 if (pow2_offset != 0) add2reg(Rdst, pow2_offset);
4561 } else {
4562 add2reg_with_index(Rdst, pow2_offset, Rbase, Rsrc);
4563 }
4564 if (oop_shift != 0) { // Shift out alignment bits.
4565 z_srlg(Rdst, Rdst, oop_shift);
4566 }
4567 if (!only32bitValid) {
4568 z_llgfr(Rdst, Rdst); // Clear upper bits in case the register will be decoded again.
4569 }
4570 }
4571 #ifdef ASSERT
4572 if (used_R0 && Rdst != Z_R0 && Rsrc != Z_R0) { preset_reg(Z_R0, 0xb01bUL, 2); }
4573 if (used_R1 && Rdst != Z_R1 && Rsrc != Z_R1) { preset_reg(Z_R1, 0xb02bUL, 2); }
4574 #endif
4575 BLOCK_COMMENT("} cOop encoder general");
4576 }
4577
4578 //-------------------------------------------------
4579 // decode compressed oop. Generally usable decoder.
4580 //-------------------------------------------------
4581 // Rsrc - contains compressed oop on entry.
4582 // Rdst - contains regular oop on exit.
4583 // Rdst and Rsrc may indicate same register.
4584 // Rdst must not be the same register as Rbase, if Rbase was preloaded (before call).
4585 // Rdst can be the same register as Rbase. Then, either Z_R0 or Z_R1 must be available as scratch.
4586 // Rbase - register to use for the base
4587 // pow2_offset - offset of base to nice value. If -1, base must be loaded.
4588 // For performance, it is good to
4589 // - avoid Z_R0 for any of the argument registers.
4590 // - keep Rdst and Rsrc distinct from Rbase. Rdst == Rsrc is ok for performance.
4591 // - avoid Z_R1 for Rdst if Rdst == Rbase.
4592 void MacroAssembler::oop_decoder(Register Rdst, Register Rsrc, bool maybenull, Register Rbase, int pow2_offset) {
4593
4594 const address oop_base = CompressedOops::base();
4595 const int oop_shift = CompressedOops::shift();
4596 const bool disjoint = CompressedOops::base_disjoint();
4597
4598 assert(UseCompressedOops, "must be on to call this method");
4599 assert(Universe::heap() != nullptr, "java heap must be initialized to call this decoder");
4600 assert((oop_shift == 0) || (oop_shift == LogMinObjAlignmentInBytes),
4601 "cOop encoder detected bad shift");
4602
4603 // cOops are always loaded zero-extended from memory. No explicit zero-extension necessary.
4604
4605 if (oop_base != nullptr) {
4606 unsigned int oop_base_hl = ((unsigned int)((uint64_t)(intptr_t)oop_base >> 32)) & 0xffff;
4607 unsigned int oop_base_hh = ((unsigned int)((uint64_t)(intptr_t)oop_base >> 48)) & 0xffff;
4608 unsigned int oop_base_hf = ((unsigned int)((uint64_t)(intptr_t)oop_base >> 32)) & 0xFFFFffff;
4609 if (disjoint && (oop_base_hl == 0 || oop_base_hh == 0)) {
4610 BLOCK_COMMENT("cOop decoder disjointBase {");
4611 // We do not need to load the base. Instead, we can install the upper bits
4612 // with an OR instead of an ADD.
4613 Label done;
4614
4615 // Rsrc contains a narrow oop. Thus we are sure the leftmost <oop_shift> bits will never be set.
4616 if (maybenull) { // null pointer must be preserved!
4617 z_slag(Rdst, Rsrc, oop_shift); // Arithmetic shift sets the condition code.
4618 z_bre(done);
4619 } else {
4620 z_sllg(Rdst, Rsrc, oop_shift); // Logical shift leaves condition code alone.
4621 }
4622 if ((oop_base_hl != 0) && (oop_base_hh != 0)) {
4623 z_oihf(Rdst, oop_base_hf);
4624 } else if (oop_base_hl != 0) {
4625 z_oihl(Rdst, oop_base_hl);
4626 } else {
4627 assert(oop_base_hh != 0, "not heapbased mode");
4628 z_oihh(Rdst, oop_base_hh);
4629 }
4630 bind(done);
4631 BLOCK_COMMENT("} cOop decoder disjointBase");
4632 } else {
4633 BLOCK_COMMENT("cOop decoder general {");
4634 // There are three decode steps:
4635 // scale oop offset (shift left)
4636 // get base (in reg) and pow2_offset (constant)
4637 // add base, pow2_offset, and oop offset
4638 // The following register overlap situations may exist:
4639 // Rdst == Rsrc, Rbase any other
4640 // not a problem. Scaling in-place leaves Rbase undisturbed.
4641 // Loading Rbase does not impact the scaled offset.
4642 // Rdst == Rbase, Rsrc any other
4643 // scaling would destroy a possibly preloaded Rbase. Loading Rbase
4644 // would destroy the scaled offset.
4645 // Remedy: use Rdst_tmp if Rbase has been preloaded.
4646 // use Rbase_tmp if base has to be loaded.
4647 // Rsrc == Rbase, Rdst any other
4648 // Only possible without preloaded Rbase.
4649 // Loading Rbase does not destroy compressed oop because it was scaled into Rdst before.
4650 // Rsrc == Rbase, Rdst == Rbase
4651 // Only possible without preloaded Rbase.
4652 // Loading Rbase would destroy compressed oop. Scaling in-place is ok.
4653 // Remedy: use Rbase_tmp.
4654 //
4655 Label done;
4656 Register Rdst_tmp = Rdst;
4657 Register Rbase_tmp = Rbase;
4658 bool used_R0 = false;
4659 bool used_R1 = false;
4660 bool base_preloaded = pow2_offset >= 0;
4661 guarantee(!(base_preloaded && (Rsrc == Rbase)), "Register clash, check caller");
4662 assert(oop_shift != 0, "room for optimization");
4663
4664 // Check if we need to use scratch registers.
4665 if (Rdst == Rbase) {
4666 assert(!(((Rdst == Z_R0) && (Rsrc == Z_R1)) || ((Rdst == Z_R1) && (Rsrc == Z_R0))), "need a scratch reg");
4667 if (Rdst != Rsrc) {
4668 if (base_preloaded) { Rdst_tmp = (Rdst == Z_R1) ? Z_R0 : Z_R1; }
4669 else { Rbase_tmp = (Rdst == Z_R1) ? Z_R0 : Z_R1; }
4670 } else {
4671 Rbase_tmp = (Rdst == Z_R1) ? Z_R0 : Z_R1;
4672 }
4673 }
4674 if (base_preloaded) lgr_if_needed(Rbase_tmp, Rbase);
4675
4676 // Scale oop and check for null.
4677 // Rsrc contains a narrow oop. Thus we are sure the leftmost <oop_shift> bits will never be set.
4678 if (maybenull) { // null pointer must be preserved!
4679 z_slag(Rdst_tmp, Rsrc, oop_shift); // Arithmetic shift sets the condition code.
4680 z_bre(done);
4681 } else {
4682 z_sllg(Rdst_tmp, Rsrc, oop_shift); // Logical shift leaves condition code alone.
4683 }
4684
4685 // Get oop_base components.
4686 if (!base_preloaded) {
4687 pow2_offset = get_oop_base(Rbase_tmp, (uint64_t)(intptr_t)oop_base);
4688 }
4689
4690 // Add up all components.
4691 if ((Rbase_tmp == Z_R0) || (Rdst_tmp == Z_R0)) {
4692 z_algr(Rdst_tmp, Rbase_tmp);
4693 if (pow2_offset != 0) { add2reg(Rdst_tmp, pow2_offset); }
4694 } else {
4695 add2reg_with_index(Rdst_tmp, pow2_offset, Rbase_tmp, Rdst_tmp);
4696 }
4697
4698 bind(done);
4699 lgr_if_needed(Rdst, Rdst_tmp);
4700 #ifdef ASSERT
4701 if (used_R0 && Rdst != Z_R0 && Rsrc != Z_R0) { preset_reg(Z_R0, 0xb03bUL, 2); }
4702 if (used_R1 && Rdst != Z_R1 && Rsrc != Z_R1) { preset_reg(Z_R1, 0xb04bUL, 2); }
4703 #endif
4704 BLOCK_COMMENT("} cOop decoder general");
4705 }
4706 } else {
4707 BLOCK_COMMENT("cOop decoder zeroBase {");
4708 if (oop_shift == 0) {
4709 lgr_if_needed(Rdst, Rsrc);
4710 } else {
4711 z_sllg(Rdst, Rsrc, oop_shift);
4712 }
4713 BLOCK_COMMENT("} cOop decoder zeroBase");
4714 }
4715 }
4716
4717 // ((OopHandle)result).resolve();
4718 void MacroAssembler::resolve_oop_handle(Register result, Register tmp1, Register tmp2) {
4719 access_load_at(T_OBJECT, IN_NATIVE, Address(result, 0), result, tmp1, tmp2);
4720 }
4721
4722 void MacroAssembler::load_method_holder(Register holder, Register method) {
4723 mem2reg_opt(holder, Address(method, Method::const_offset()));
4724 mem2reg_opt(holder, Address(holder, ConstMethod::constants_offset()));
4725 mem2reg_opt(holder, Address(holder, ConstantPool::pool_holder_offset()));
4726 }
4727
4728 //---------------------------------------------------------------
4729 //--- Operations on arrays.
4730 //---------------------------------------------------------------
4731
4732 // Compiler ensures base is doubleword aligned and cnt is #doublewords.
4733 // Emitter does not KILL cnt and base arguments, since they need to be copied to
4734 // work registers anyway.
4735 // Actually, only r0, r1, and r5 are killed.
4736 unsigned int MacroAssembler::Clear_Array(Register cnt_arg, Register base_pointer_arg, Register odd_tmp_reg) {
4737
4738 int block_start = offset();
4739 Register dst_len = Z_R1; // Holds dst len for MVCLE.
4740 Register dst_addr = Z_R0; // Holds dst addr for MVCLE.
4741
4742 Label doXC, doMVCLE, done;
4743
4744 BLOCK_COMMENT("Clear_Array {");
4745
4746 // Check for zero len and convert to long.
4747 z_ltgfr(odd_tmp_reg, cnt_arg);
4748 z_bre(done); // Nothing to do if len == 0.
4749
4750 // Prefetch data to be cleared.
4751 if (VM_Version::has_Prefetch()) {
4752 z_pfd(0x02, 0, Z_R0, base_pointer_arg);
4753 z_pfd(0x02, 256, Z_R0, base_pointer_arg);
4754 }
4755
4756 z_sllg(dst_len, odd_tmp_reg, 3); // #bytes to clear.
4757 z_cghi(odd_tmp_reg, 32); // Check for len <= 256 bytes (<=32 DW).
4758 z_brnh(doXC); // If so, use executed XC to clear.
4759
4760 // MVCLE: initialize long arrays (general case).
4761 bind(doMVCLE);
4762 z_lgr(dst_addr, base_pointer_arg);
4763 // Pass 0 as source length to MVCLE: destination will be filled with padding byte 0.
4764 // The even register of the register pair is not killed.
4765 clear_reg(odd_tmp_reg, true, false);
4766 MacroAssembler::move_long_ext(dst_addr, as_Register(odd_tmp_reg->encoding()-1), 0);
4767 z_bru(done);
4768
4769 // XC: initialize short arrays.
4770 Label XC_template; // Instr template, never exec directly!
4771 bind(XC_template);
4772 z_xc(0,0,base_pointer_arg,0,base_pointer_arg);
4773
4774 bind(doXC);
4775 add2reg(dst_len, -1); // Get #bytes-1 for EXECUTE.
4776 if (VM_Version::has_ExecuteExtensions()) {
4777 z_exrl(dst_len, XC_template); // Execute XC with var. len.
4778 } else {
4779 z_larl(odd_tmp_reg, XC_template);
4780 z_ex(dst_len,0,Z_R0,odd_tmp_reg); // Execute XC with var. len.
4781 }
4782 // z_bru(done); // fallthru
4783
4784 bind(done);
4785
4786 BLOCK_COMMENT("} Clear_Array");
4787
4788 int block_end = offset();
4789 return block_end - block_start;
4790 }
4791
4792 // Compiler ensures base is doubleword aligned and cnt is count of doublewords.
4793 // Emitter does not KILL any arguments nor work registers.
4794 // Emitter generates up to 16 XC instructions, depending on the array length.
4795 unsigned int MacroAssembler::Clear_Array_Const(long cnt, Register base) {
4796 int block_start = offset();
4797 int off;
4798 int lineSize_Bytes = AllocatePrefetchStepSize;
4799 int lineSize_DW = AllocatePrefetchStepSize>>LogBytesPerWord;
4800 bool doPrefetch = VM_Version::has_Prefetch();
4801 int XC_maxlen = 256;
4802 int numXCInstr = cnt > 0 ? (cnt*BytesPerWord-1)/XC_maxlen+1 : 0;
4803
4804 BLOCK_COMMENT("Clear_Array_Const {");
4805 assert(cnt*BytesPerWord <= 4096, "ClearArrayConst can handle 4k only");
4806
4807 // Do less prefetching for very short arrays.
4808 if (numXCInstr > 0) {
4809 // Prefetch only some cache lines, then begin clearing.
4810 if (doPrefetch) {
4811 if (cnt*BytesPerWord <= lineSize_Bytes/4) { // If less than 1/4 of a cache line to clear,
4812 z_pfd(0x02, 0, Z_R0, base); // prefetch just the first cache line.
4813 } else {
4814 assert(XC_maxlen == lineSize_Bytes, "ClearArrayConst needs 256B cache lines");
4815 for (off = 0; (off < AllocatePrefetchLines) && (off <= numXCInstr); off ++) {
4816 z_pfd(0x02, off*lineSize_Bytes, Z_R0, base);
4817 }
4818 }
4819 }
4820
4821 for (off=0; off<(numXCInstr-1); off++) {
4822 z_xc(off*XC_maxlen, XC_maxlen-1, base, off*XC_maxlen, base);
4823
4824 // Prefetch some cache lines in advance.
4825 if (doPrefetch && (off <= numXCInstr-AllocatePrefetchLines)) {
4826 z_pfd(0x02, (off+AllocatePrefetchLines)*lineSize_Bytes, Z_R0, base);
4827 }
4828 }
4829 if (off*XC_maxlen < cnt*BytesPerWord) {
4830 z_xc(off*XC_maxlen, (cnt*BytesPerWord-off*XC_maxlen)-1, base, off*XC_maxlen, base);
4831 }
4832 }
4833 BLOCK_COMMENT("} Clear_Array_Const");
4834
4835 int block_end = offset();
4836 return block_end - block_start;
4837 }
4838
4839 // Compiler ensures base is doubleword aligned and cnt is #doublewords.
4840 // Emitter does not KILL cnt and base arguments, since they need to be copied to
4841 // work registers anyway.
4842 // Actually, only r0, r1, (which are work registers) and odd_tmp_reg are killed.
4843 //
4844 // For very large arrays, exploit MVCLE H/W support.
4845 // MVCLE instruction automatically exploits H/W-optimized page mover.
4846 // - Bytes up to next page boundary are cleared with a series of XC to self.
4847 // - All full pages are cleared with the page mover H/W assist.
4848 // - Remaining bytes are again cleared by a series of XC to self.
4849 //
4850 unsigned int MacroAssembler::Clear_Array_Const_Big(long cnt, Register base_pointer_arg, Register odd_tmp_reg) {
4851
4852 int block_start = offset();
4853 Register dst_len = Z_R1; // Holds dst len for MVCLE.
4854 Register dst_addr = Z_R0; // Holds dst addr for MVCLE.
4855
4856 BLOCK_COMMENT("Clear_Array_Const_Big {");
4857
4858 // Get len to clear.
4859 load_const_optimized(dst_len, (long)cnt*8L); // in Bytes = #DW*8
4860
4861 // Prepare other args to MVCLE.
4862 z_lgr(dst_addr, base_pointer_arg);
4863 // Pass 0 as source length to MVCLE: destination will be filled with padding byte 0.
4864 // The even register of the register pair is not killed.
4865 (void) clear_reg(odd_tmp_reg, true, false); // Src len of MVCLE is zero.
4866 MacroAssembler::move_long_ext(dst_addr, as_Register(odd_tmp_reg->encoding() - 1), 0);
4867 BLOCK_COMMENT("} Clear_Array_Const_Big");
4868
4869 int block_end = offset();
4870 return block_end - block_start;
4871 }
4872
4873 // Allocator.
4874 unsigned int MacroAssembler::CopyRawMemory_AlignedDisjoint(Register src_reg, Register dst_reg,
4875 Register cnt_reg,
4876 Register tmp1_reg, Register tmp2_reg) {
4877 // Tmp1 is oddReg.
4878 // Tmp2 is evenReg.
4879
4880 int block_start = offset();
4881 Label doMVC, doMVCLE, done, MVC_template;
4882
4883 BLOCK_COMMENT("CopyRawMemory_AlignedDisjoint {");
4884
4885 // Check for zero len and convert to long.
4886 z_ltgfr(cnt_reg, cnt_reg); // Remember casted value for doSTG case.
4887 z_bre(done); // Nothing to do if len == 0.
4888
4889 z_sllg(Z_R1, cnt_reg, 3); // Dst len in bytes. calc early to have the result ready.
4890
4891 z_cghi(cnt_reg, 32); // Check for len <= 256 bytes (<=32 DW).
4892 z_brnh(doMVC); // If so, use executed MVC to clear.
4893
4894 bind(doMVCLE); // A lot of data (more than 256 bytes).
4895 // Prep dest reg pair.
4896 z_lgr(Z_R0, dst_reg); // dst addr
4897 // Dst len already in Z_R1.
4898 // Prep src reg pair.
4899 z_lgr(tmp2_reg, src_reg); // src addr
4900 z_lgr(tmp1_reg, Z_R1); // Src len same as dst len.
4901
4902 // Do the copy.
4903 move_long_ext(Z_R0, tmp2_reg, 0xb0); // Bypass cache.
4904 z_bru(done); // All done.
4905
4906 bind(MVC_template); // Just some data (not more than 256 bytes).
4907 z_mvc(0, 0, dst_reg, 0, src_reg);
4908
4909 bind(doMVC);
4910
4911 if (VM_Version::has_ExecuteExtensions()) {
4912 add2reg(Z_R1, -1);
4913 } else {
4914 add2reg(tmp1_reg, -1, Z_R1);
4915 z_larl(Z_R1, MVC_template);
4916 }
4917
4918 if (VM_Version::has_Prefetch()) {
4919 z_pfd(1, 0,Z_R0,src_reg);
4920 z_pfd(2, 0,Z_R0,dst_reg);
4921 // z_pfd(1,256,Z_R0,src_reg); // Assume very short copy.
4922 // z_pfd(2,256,Z_R0,dst_reg);
4923 }
4924
4925 if (VM_Version::has_ExecuteExtensions()) {
4926 z_exrl(Z_R1, MVC_template);
4927 } else {
4928 z_ex(tmp1_reg, 0, Z_R0, Z_R1);
4929 }
4930
4931 bind(done);
4932
4933 BLOCK_COMMENT("} CopyRawMemory_AlignedDisjoint");
4934
4935 int block_end = offset();
4936 return block_end - block_start;
4937 }
4938
4939 //-------------------------------------------------
4940 // Constants (scalar and oop) in constant pool
4941 //-------------------------------------------------
4942
4943 // Add a non-relocated constant to the CP.
4944 int MacroAssembler::store_const_in_toc(AddressLiteral& val) {
4945 long value = val.value();
4946 address tocPos = long_constant(value);
4947
4948 if (tocPos != nullptr) {
4949 int tocOffset = (int)(tocPos - code()->consts()->start());
4950 return tocOffset;
4951 }
4952 // Address_constant returned null, so no constant entry has been created.
4953 // In that case, we return a "fatal" offset, just in case that subsequently
4954 // generated access code is executed.
4955 return -1;
4956 }
4957
4958 // Returns the TOC offset where the address is stored.
4959 // Add a relocated constant to the CP.
4960 int MacroAssembler::store_oop_in_toc(AddressLiteral& oop) {
4961 // Use RelocationHolder::none for the constant pool entry.
4962 // Otherwise we will end up with a failing NativeCall::verify(x),
4963 // where x is the address of the constant pool entry.
4964 address tocPos = address_constant((address)oop.value(), RelocationHolder::none);
4965
4966 if (tocPos != nullptr) {
4967 int tocOffset = (int)(tocPos - code()->consts()->start());
4968 RelocationHolder rsp = oop.rspec();
4969 Relocation *rel = rsp.reloc();
4970
4971 // Store toc_offset in relocation, used by call_far_patchable.
4972 if ((relocInfo::relocType)rel->type() == relocInfo::runtime_call_w_cp_type) {
4973 ((runtime_call_w_cp_Relocation *)(rel))->set_constant_pool_offset(tocOffset);
4974 }
4975 // Relocate at the load's pc.
4976 relocate(rsp);
4977
4978 return tocOffset;
4979 }
4980 // Address_constant returned null, so no constant entry has been created
4981 // in that case, we return a "fatal" offset, just in case that subsequently
4982 // generated access code is executed.
4983 return -1;
4984 }
4985
4986 bool MacroAssembler::load_const_from_toc(Register dst, AddressLiteral& a, Register Rtoc) {
4987 int tocOffset = store_const_in_toc(a);
4988 if (tocOffset == -1) return false;
4989 address tocPos = tocOffset + code()->consts()->start();
4990 assert((address)code()->consts()->start() != nullptr, "Please add CP address");
4991 relocate(a.rspec());
4992 load_long_pcrelative(dst, tocPos);
4993 return true;
4994 }
4995
4996 bool MacroAssembler::load_oop_from_toc(Register dst, AddressLiteral& a, Register Rtoc) {
4997 int tocOffset = store_oop_in_toc(a);
4998 if (tocOffset == -1) return false;
4999 address tocPos = tocOffset + code()->consts()->start();
5000 assert((address)code()->consts()->start() != nullptr, "Please add CP address");
5001
5002 load_addr_pcrelative(dst, tocPos);
5003 return true;
5004 }
5005
5006 // If the instruction sequence at the given pc is a load_const_from_toc
5007 // sequence, return the value currently stored at the referenced position
5008 // in the TOC.
5009 intptr_t MacroAssembler::get_const_from_toc(address pc) {
5010
5011 assert(is_load_const_from_toc(pc), "must be load_const_from_pool");
5012
5013 long offset = get_load_const_from_toc_offset(pc);
5014 address dataLoc = nullptr;
5015 if (is_load_const_from_toc_pcrelative(pc)) {
5016 dataLoc = pc + offset;
5017 } else {
5018 CodeBlob* cb = CodeCache::find_blob(pc);
5019 assert(cb && cb->is_nmethod(), "sanity");
5020 nmethod* nm = (nmethod*)cb;
5021 dataLoc = nm->ctable_begin() + offset;
5022 }
5023 return *(intptr_t *)dataLoc;
5024 }
5025
5026 // If the instruction sequence at the given pc is a load_const_from_toc
5027 // sequence, copy the passed-in new_data value into the referenced
5028 // position in the TOC.
5029 void MacroAssembler::set_const_in_toc(address pc, unsigned long new_data, CodeBlob *cb) {
5030 assert(is_load_const_from_toc(pc), "must be load_const_from_pool");
5031
5032 long offset = MacroAssembler::get_load_const_from_toc_offset(pc);
5033 address dataLoc = nullptr;
5034 if (is_load_const_from_toc_pcrelative(pc)) {
5035 dataLoc = pc+offset;
5036 } else {
5037 nmethod* nm = CodeCache::find_nmethod(pc);
5038 assert((cb == nullptr) || (nm == (nmethod*)cb), "instruction address should be in CodeBlob");
5039 dataLoc = nm->ctable_begin() + offset;
5040 }
5041 if (*(unsigned long *)dataLoc != new_data) { // Prevent cache invalidation: update only if necessary.
5042 *(unsigned long *)dataLoc = new_data;
5043 }
5044 }
5045
5046 // Dynamic TOC. Getter must only be called if "a" is a load_const_from_toc
5047 // site. Verify by calling is_load_const_from_toc() before!!
5048 // Offset is +/- 2**32 -> use long.
5049 long MacroAssembler::get_load_const_from_toc_offset(address a) {
5050 assert(is_load_const_from_toc_pcrelative(a), "expected pc relative load");
5051 // expected code sequence:
5052 // z_lgrl(t, simm32); len = 6
5053 unsigned long inst;
5054 unsigned int len = get_instruction(a, &inst);
5055 return get_pcrel_offset(inst);
5056 }
5057
5058 //**********************************************************************************
5059 // inspection of generated instruction sequences for a particular pattern
5060 //**********************************************************************************
5061
5062 bool MacroAssembler::is_load_const_from_toc_pcrelative(address a) {
5063 #ifdef ASSERT
5064 unsigned long inst;
5065 unsigned int len = get_instruction(a+2, &inst);
5066 if ((len == 6) && is_load_pcrelative_long(a) && is_call_pcrelative_long(inst)) {
5067 const int range = 128;
5068 Assembler::dump_code_range(tty, a, range, "instr(a) == z_lgrl && instr(a+2) == z_brasl");
5069 VM_Version::z_SIGSEGV();
5070 }
5071 #endif
5072 // expected code sequence:
5073 // z_lgrl(t, relAddr32); len = 6
5074 //TODO: verify accessed data is in CP, if possible.
5075 return is_load_pcrelative_long(a); // TODO: might be too general. Currently, only lgrl is used.
5076 }
5077
5078 bool MacroAssembler::is_load_const_from_toc_call(address a) {
5079 return is_load_const_from_toc(a) && is_call_byregister(a + load_const_from_toc_size());
5080 }
5081
5082 bool MacroAssembler::is_load_const_call(address a) {
5083 return is_load_const(a) && is_call_byregister(a + load_const_size());
5084 }
5085
5086 //-------------------------------------------------
5087 // Emitters for some really CICS instructions
5088 //-------------------------------------------------
5089
5090 void MacroAssembler::move_long_ext(Register dst, Register src, unsigned int pad) {
5091 assert(dst->encoding()%2==0, "must be an even/odd register pair");
5092 assert(src->encoding()%2==0, "must be an even/odd register pair");
5093 assert(pad<256, "must be a padding BYTE");
5094
5095 Label retry;
5096 bind(retry);
5097 Assembler::z_mvcle(dst, src, pad);
5098 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5099 }
5100
5101 void MacroAssembler::compare_long_ext(Register left, Register right, unsigned int pad) {
5102 assert(left->encoding() % 2 == 0, "must be an even/odd register pair");
5103 assert(right->encoding() % 2 == 0, "must be an even/odd register pair");
5104 assert(pad<256, "must be a padding BYTE");
5105
5106 Label retry;
5107 bind(retry);
5108 Assembler::z_clcle(left, right, pad, Z_R0);
5109 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5110 }
5111
5112 void MacroAssembler::compare_long_uni(Register left, Register right, unsigned int pad) {
5113 assert(left->encoding() % 2 == 0, "must be an even/odd register pair");
5114 assert(right->encoding() % 2 == 0, "must be an even/odd register pair");
5115 assert(pad<=0xfff, "must be a padding HALFWORD");
5116 assert(VM_Version::has_ETF2(), "instruction must be available");
5117
5118 Label retry;
5119 bind(retry);
5120 Assembler::z_clclu(left, right, pad, Z_R0);
5121 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5122 }
5123
5124 void MacroAssembler::search_string(Register end, Register start) {
5125 assert(end->encoding() != 0, "end address must not be in R0");
5126 assert(start->encoding() != 0, "start address must not be in R0");
5127
5128 Label retry;
5129 bind(retry);
5130 Assembler::z_srst(end, start);
5131 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5132 }
5133
5134 void MacroAssembler::search_string_uni(Register end, Register start) {
5135 assert(end->encoding() != 0, "end address must not be in R0");
5136 assert(start->encoding() != 0, "start address must not be in R0");
5137 assert(VM_Version::has_ETF3(), "instruction must be available");
5138
5139 Label retry;
5140 bind(retry);
5141 Assembler::z_srstu(end, start);
5142 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5143 }
5144
5145 void MacroAssembler::kmac(Register srcBuff) {
5146 assert(srcBuff->encoding() != 0, "src buffer address can't be in Z_R0");
5147 assert(srcBuff->encoding() % 2 == 0, "src buffer/len must be an even/odd register pair");
5148
5149 Label retry;
5150 bind(retry);
5151 Assembler::z_kmac(Z_R0, srcBuff);
5152 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5153 }
5154
5155 void MacroAssembler::kimd(Register srcBuff) {
5156 assert(srcBuff->encoding() != 0, "src buffer address can't be in Z_R0");
5157 assert(srcBuff->encoding() % 2 == 0, "src buffer/len must be an even/odd register pair");
5158
5159 Label retry;
5160 bind(retry);
5161 Assembler::z_kimd(Z_R0, srcBuff);
5162 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5163 }
5164
5165 void MacroAssembler::klmd(Register srcBuff) {
5166 assert(srcBuff->encoding() != 0, "src buffer address can't be in Z_R0");
5167 assert(srcBuff->encoding() % 2 == 0, "src buffer/len must be an even/odd register pair");
5168
5169 Label retry;
5170 bind(retry);
5171 Assembler::z_klmd(Z_R0, srcBuff);
5172 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5173 }
5174
5175 void MacroAssembler::km(Register dstBuff, Register srcBuff) {
5176 // DstBuff and srcBuff are allowed to be the same register (encryption in-place).
5177 // DstBuff and srcBuff storage must not overlap destructively, and neither must overlap the parameter block.
5178 assert(srcBuff->encoding() != 0, "src buffer address can't be in Z_R0");
5179 assert(dstBuff->encoding() % 2 == 0, "dst buffer addr must be an even register");
5180 assert(srcBuff->encoding() % 2 == 0, "src buffer addr/len must be an even/odd register pair");
5181
5182 Label retry;
5183 bind(retry);
5184 Assembler::z_km(dstBuff, srcBuff);
5185 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5186 }
5187
5188 void MacroAssembler::kmc(Register dstBuff, Register srcBuff) {
5189 // DstBuff and srcBuff are allowed to be the same register (encryption in-place).
5190 // DstBuff and srcBuff storage must not overlap destructively, and neither must overlap the parameter block.
5191 assert(srcBuff->encoding() != 0, "src buffer address can't be in Z_R0");
5192 assert(dstBuff->encoding() % 2 == 0, "dst buffer addr must be an even register");
5193 assert(srcBuff->encoding() % 2 == 0, "src buffer addr/len must be an even/odd register pair");
5194
5195 Label retry;
5196 bind(retry);
5197 Assembler::z_kmc(dstBuff, srcBuff);
5198 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5199 }
5200
5201 void MacroAssembler::kmctr(Register dstBuff, Register ctrBuff, Register srcBuff) {
5202 // DstBuff and srcBuff are allowed to be the same register (encryption in-place).
5203 // DstBuff and srcBuff storage must not overlap destructively, and neither must overlap the parameter block.
5204 assert(srcBuff->encoding() != 0, "src buffer address can't be in Z_R0");
5205 assert(dstBuff->encoding() != 0, "dst buffer address can't be in Z_R0");
5206 assert(ctrBuff->encoding() != 0, "ctr buffer address can't be in Z_R0");
5207 assert(ctrBuff->encoding() % 2 == 0, "ctr buffer addr must be an even register");
5208 assert(dstBuff->encoding() % 2 == 0, "dst buffer addr must be an even register");
5209 assert(srcBuff->encoding() % 2 == 0, "src buffer addr/len must be an even/odd register pair");
5210
5211 Label retry;
5212 bind(retry);
5213 Assembler::z_kmctr(dstBuff, ctrBuff, srcBuff);
5214 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5215 }
5216
5217 void MacroAssembler::cksm(Register crcBuff, Register srcBuff) {
5218 assert(srcBuff->encoding() % 2 == 0, "src buffer addr/len must be an even/odd register pair");
5219
5220 Label retry;
5221 bind(retry);
5222 Assembler::z_cksm(crcBuff, srcBuff);
5223 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5224 }
5225
5226 void MacroAssembler::translate_oo(Register r1, Register r2, uint m3) {
5227 assert(r1->encoding() % 2 == 0, "dst addr/src len must be an even/odd register pair");
5228 assert((m3 & 0b1110) == 0, "Unused mask bits must be zero");
5229
5230 Label retry;
5231 bind(retry);
5232 Assembler::z_troo(r1, r2, m3);
5233 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5234 }
5235
5236 void MacroAssembler::translate_ot(Register r1, Register r2, uint m3) {
5237 assert(r1->encoding() % 2 == 0, "dst addr/src len must be an even/odd register pair");
5238 assert((m3 & 0b1110) == 0, "Unused mask bits must be zero");
5239
5240 Label retry;
5241 bind(retry);
5242 Assembler::z_trot(r1, r2, m3);
5243 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5244 }
5245
5246 void MacroAssembler::translate_to(Register r1, Register r2, uint m3) {
5247 assert(r1->encoding() % 2 == 0, "dst addr/src len must be an even/odd register pair");
5248 assert((m3 & 0b1110) == 0, "Unused mask bits must be zero");
5249
5250 Label retry;
5251 bind(retry);
5252 Assembler::z_trto(r1, r2, m3);
5253 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5254 }
5255
5256 void MacroAssembler::translate_tt(Register r1, Register r2, uint m3) {
5257 assert(r1->encoding() % 2 == 0, "dst addr/src len must be an even/odd register pair");
5258 assert((m3 & 0b1110) == 0, "Unused mask bits must be zero");
5259
5260 Label retry;
5261 bind(retry);
5262 Assembler::z_trtt(r1, r2, m3);
5263 Assembler::z_brc(Assembler::bcondOverflow /* CC==3 (iterate) */, retry);
5264 }
5265
5266 //---------------------------------------
5267 // Helpers for Intrinsic Emitters
5268 //---------------------------------------
5269
5270 /**
5271 * uint32_t crc;
5272 * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
5273 */
5274 void MacroAssembler::fold_byte_crc32(Register crc, Register val, Register table, Register tmp) {
5275 assert_different_registers(crc, table, tmp);
5276 assert_different_registers(val, table);
5277 if (crc == val) { // Must rotate first to use the unmodified value.
5278 rotate_then_insert(tmp, val, 56-2, 63-2, 2, true); // Insert byte 7 of val, shifted left by 2, into byte 6..7 of tmp, clear the rest.
5279 z_srl(crc, 8); // Unsigned shift, clear leftmost 8 bits.
5280 } else {
5281 z_srl(crc, 8); // Unsigned shift, clear leftmost 8 bits.
5282 rotate_then_insert(tmp, val, 56-2, 63-2, 2, true); // Insert byte 7 of val, shifted left by 2, into byte 6..7 of tmp, clear the rest.
5283 }
5284 z_x(crc, Address(table, tmp, 0));
5285 }
5286
5287 /**
5288 * uint32_t crc;
5289 * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
5290 */
5291 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
5292 fold_byte_crc32(crc, crc, table, tmp);
5293 }
5294
5295 /**
5296 * Emits code to update CRC-32 with a byte value according to constants in table.
5297 *
5298 * @param [in,out]crc Register containing the crc.
5299 * @param [in]val Register containing the byte to fold into the CRC.
5300 * @param [in]table Register containing the table of crc constants.
5301 *
5302 * uint32_t crc;
5303 * val = crc_table[(val ^ crc) & 0xFF];
5304 * crc = val ^ (crc >> 8);
5305 */
5306 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
5307 z_xr(val, crc);
5308 fold_byte_crc32(crc, val, table, val);
5309 }
5310
5311
5312 /**
5313 * @param crc register containing existing CRC (32-bit)
5314 * @param buf register pointing to input byte buffer (byte*)
5315 * @param len register containing number of bytes
5316 * @param table register pointing to CRC table
5317 */
5318 void MacroAssembler::update_byteLoop_crc32(Register crc, Register buf, Register len, Register table, Register data) {
5319 assert_different_registers(crc, buf, len, table, data);
5320
5321 Label L_mainLoop, L_done;
5322 const int mainLoop_stepping = 1;
5323
5324 // Process all bytes in a single-byte loop.
5325 z_ltr(len, len);
5326 z_brnh(L_done);
5327
5328 bind(L_mainLoop);
5329 z_llgc(data, Address(buf, (intptr_t)0));// Current byte of input buffer (zero extended). Avoids garbage in upper half of register.
5330 add2reg(buf, mainLoop_stepping); // Advance buffer position.
5331 update_byte_crc32(crc, data, table);
5332 z_brct(len, L_mainLoop); // Iterate.
5333
5334 bind(L_done);
5335 }
5336
5337 /**
5338 * Emits code to update CRC-32 with a 4-byte value according to constants in table.
5339 * Implementation according to jdk/src/share/native/java/util/zip/zlib-1.2.8/crc32.c.
5340 *
5341 */
5342 void MacroAssembler::update_1word_crc32(Register crc, Register buf, Register table, int bufDisp, int bufInc,
5343 Register t0, Register t1, Register t2, Register t3) {
5344 // This is what we implement (the DOBIG4 part):
5345 //
5346 // #define DOBIG4 c ^= *++buf4; \
5347 // c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
5348 // crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
5349 // #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
5350 // Pre-calculate (constant) column offsets, use columns 4..7 for big-endian.
5351 const int ix0 = 4*(4*CRC32_COLUMN_SIZE);
5352 const int ix1 = 5*(4*CRC32_COLUMN_SIZE);
5353 const int ix2 = 6*(4*CRC32_COLUMN_SIZE);
5354 const int ix3 = 7*(4*CRC32_COLUMN_SIZE);
5355
5356 // XOR crc with next four bytes of buffer.
5357 lgr_if_needed(t0, crc);
5358 z_x(t0, Address(buf, bufDisp));
5359 if (bufInc != 0) {
5360 add2reg(buf, bufInc);
5361 }
5362
5363 // Chop crc into 4 single-byte pieces, shifted left 2 bits, to form the table indices.
5364 rotate_then_insert(t3, t0, 56-2, 63-2, 2, true); // ((c >> 0) & 0xff) << 2
5365 rotate_then_insert(t2, t0, 56-2, 63-2, 2-8, true); // ((c >> 8) & 0xff) << 2
5366 rotate_then_insert(t1, t0, 56-2, 63-2, 2-16, true); // ((c >> 16) & 0xff) << 2
5367 rotate_then_insert(t0, t0, 56-2, 63-2, 2-24, true); // ((c >> 24) & 0xff) << 2
5368
5369 // XOR indexed table values to calculate updated crc.
5370 z_ly(t2, Address(table, t2, (intptr_t)ix1));
5371 z_ly(t0, Address(table, t0, (intptr_t)ix3));
5372 z_xy(t2, Address(table, t3, (intptr_t)ix0));
5373 z_xy(t0, Address(table, t1, (intptr_t)ix2));
5374 z_xr(t0, t2); // Now t0 contains the updated CRC value.
5375 lgr_if_needed(crc, t0);
5376 }
5377
5378 /**
5379 * @param crc register containing existing CRC (32-bit)
5380 * @param buf register pointing to input byte buffer (byte*)
5381 * @param len register containing number of bytes
5382 * @param table register pointing to CRC table
5383 *
5384 * uses Z_R10..Z_R13 as work register. Must be saved/restored by caller!
5385 */
5386 void MacroAssembler::kernel_crc32_1word(Register crc, Register buf, Register len, Register table,
5387 Register t0, Register t1, Register t2, Register t3,
5388 bool invertCRC) {
5389 assert_different_registers(crc, buf, len, table);
5390
5391 Label L_mainLoop, L_tail;
5392 Register data = t0;
5393 Register ctr = Z_R0;
5394 const int mainLoop_stepping = 4;
5395 const int log_stepping = exact_log2(mainLoop_stepping);
5396
5397 // Don't test for len <= 0 here. This pathological case should not occur anyway.
5398 // Optimizing for it by adding a test and a branch seems to be a waste of CPU cycles.
5399 // The situation itself is detected and handled correctly by the conditional branches
5400 // following aghi(len, -stepping) and aghi(len, +stepping).
5401
5402 if (invertCRC) {
5403 not_(crc, noreg, false); // 1s complement of crc
5404 }
5405
5406 // Check for short (<4 bytes) buffer.
5407 z_srag(ctr, len, log_stepping);
5408 z_brnh(L_tail);
5409
5410 z_lrvr(crc, crc); // Revert byte order because we are dealing with big-endian data.
5411 rotate_then_insert(len, len, 64-log_stepping, 63, 0, true); // #bytes for tailLoop
5412
5413 BIND(L_mainLoop);
5414 update_1word_crc32(crc, buf, table, 0, mainLoop_stepping, crc, t1, t2, t3);
5415 z_brct(ctr, L_mainLoop); // Iterate.
5416
5417 z_lrvr(crc, crc); // Revert byte order back to original.
5418
5419 // Process last few (<8) bytes of buffer.
5420 BIND(L_tail);
5421 update_byteLoop_crc32(crc, buf, len, table, data);
5422
5423 if (invertCRC) {
5424 not_(crc, noreg, false); // 1s complement of crc
5425 }
5426 }
5427
5428 /**
5429 * @param crc register containing existing CRC (32-bit)
5430 * @param buf register pointing to input byte buffer (byte*)
5431 * @param len register containing number of bytes
5432 * @param table register pointing to CRC table
5433 */
5434 void MacroAssembler::kernel_crc32_1byte(Register crc, Register buf, Register len, Register table,
5435 Register t0, Register t1, Register t2, Register t3,
5436 bool invertCRC) {
5437 assert_different_registers(crc, buf, len, table);
5438 Register data = t0;
5439
5440 if (invertCRC) {
5441 not_(crc, noreg, false); // 1s complement of crc
5442 }
5443
5444 update_byteLoop_crc32(crc, buf, len, table, data);
5445
5446 if (invertCRC) {
5447 not_(crc, noreg, false); // 1s complement of crc
5448 }
5449 }
5450
5451 void MacroAssembler::kernel_crc32_singleByte(Register crc, Register buf, Register len, Register table, Register tmp,
5452 bool invertCRC) {
5453 assert_different_registers(crc, buf, len, table, tmp);
5454
5455 if (invertCRC) {
5456 not_(crc, noreg, false); // 1s complement of crc
5457 }
5458
5459 z_llgc(tmp, Address(buf, (intptr_t)0)); // Current byte of input buffer (zero extended). Avoids garbage in upper half of register.
5460 update_byte_crc32(crc, tmp, table);
5461
5462 if (invertCRC) {
5463 not_(crc, noreg, false); // 1s complement of crc
5464 }
5465 }
5466
5467 void MacroAssembler::kernel_crc32_singleByteReg(Register crc, Register val, Register table,
5468 bool invertCRC) {
5469 assert_different_registers(crc, val, table);
5470
5471 if (invertCRC) {
5472 not_(crc, noreg, false); // 1s complement of crc
5473 }
5474
5475 update_byte_crc32(crc, val, table);
5476
5477 if (invertCRC) {
5478 not_(crc, noreg, false); // 1s complement of crc
5479 }
5480 }
5481
5482 //
5483 // Code for BigInteger::multiplyToLen() intrinsic.
5484 //
5485
5486 // dest_lo += src1 + src2
5487 // dest_hi += carry1 + carry2
5488 // Z_R7 is destroyed !
5489 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo,
5490 Register src1, Register src2) {
5491 clear_reg(Z_R7);
5492 z_algr(dest_lo, src1);
5493 z_alcgr(dest_hi, Z_R7);
5494 z_algr(dest_lo, src2);
5495 z_alcgr(dest_hi, Z_R7);
5496 }
5497
5498 // Multiply 64 bit by 64 bit first loop.
5499 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart,
5500 Register x_xstart,
5501 Register y, Register y_idx,
5502 Register z,
5503 Register carry,
5504 Register product,
5505 Register idx, Register kdx) {
5506 // jlong carry, x[], y[], z[];
5507 // for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx--, kdx--) {
5508 // huge_128 product = y[idx] * x[xstart] + carry;
5509 // z[kdx] = (jlong)product;
5510 // carry = (jlong)(product >>> 64);
5511 // }
5512 // z[xstart] = carry;
5513
5514 Label L_first_loop, L_first_loop_exit;
5515 Label L_one_x, L_one_y, L_multiply;
5516
5517 z_aghi(xstart, -1);
5518 z_brl(L_one_x); // Special case: length of x is 1.
5519
5520 // Load next two integers of x.
5521 z_sllg(Z_R1_scratch, xstart, LogBytesPerInt);
5522 mem2reg_opt(x_xstart, Address(x, Z_R1_scratch, 0));
5523
5524
5525 bind(L_first_loop);
5526
5527 z_aghi(idx, -1);
5528 z_brl(L_first_loop_exit);
5529 z_aghi(idx, -1);
5530 z_brl(L_one_y);
5531
5532 // Load next two integers of y.
5533 z_sllg(Z_R1_scratch, idx, LogBytesPerInt);
5534 mem2reg_opt(y_idx, Address(y, Z_R1_scratch, 0));
5535
5536
5537 bind(L_multiply);
5538
5539 Register multiplicand = product->successor();
5540 Register product_low = multiplicand;
5541
5542 lgr_if_needed(multiplicand, x_xstart);
5543 z_mlgr(product, y_idx); // multiplicand * y_idx -> product::multiplicand
5544 clear_reg(Z_R7);
5545 z_algr(product_low, carry); // Add carry to result.
5546 z_alcgr(product, Z_R7); // Add carry of the last addition.
5547 add2reg(kdx, -2);
5548
5549 // Store result.
5550 z_sllg(Z_R7, kdx, LogBytesPerInt);
5551 reg2mem_opt(product_low, Address(z, Z_R7, 0));
5552 lgr_if_needed(carry, product);
5553 z_bru(L_first_loop);
5554
5555
5556 bind(L_one_y); // Load one 32 bit portion of y as (0,value).
5557
5558 clear_reg(y_idx);
5559 mem2reg_opt(y_idx, Address(y, (intptr_t) 0), false);
5560 z_bru(L_multiply);
5561
5562
5563 bind(L_one_x); // Load one 32 bit portion of x as (0,value).
5564
5565 clear_reg(x_xstart);
5566 mem2reg_opt(x_xstart, Address(x, (intptr_t) 0), false);
5567 z_bru(L_first_loop);
5568
5569 bind(L_first_loop_exit);
5570 }
5571
5572 // Multiply 64 bit by 64 bit and add 128 bit.
5573 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y,
5574 Register z,
5575 Register yz_idx, Register idx,
5576 Register carry, Register product,
5577 int offset) {
5578 // huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
5579 // z[kdx] = (jlong)product;
5580
5581 Register multiplicand = product->successor();
5582 Register product_low = multiplicand;
5583
5584 z_sllg(Z_R7, idx, LogBytesPerInt);
5585 mem2reg_opt(yz_idx, Address(y, Z_R7, offset));
5586
5587 lgr_if_needed(multiplicand, x_xstart);
5588 z_mlgr(product, yz_idx); // multiplicand * yz_idx -> product::multiplicand
5589 mem2reg_opt(yz_idx, Address(z, Z_R7, offset));
5590
5591 add2_with_carry(product, product_low, carry, yz_idx);
5592
5593 z_sllg(Z_R7, idx, LogBytesPerInt);
5594 reg2mem_opt(product_low, Address(z, Z_R7, offset));
5595
5596 }
5597
5598 // Multiply 128 bit by 128 bit. Unrolled inner loop.
5599 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart,
5600 Register y, Register z,
5601 Register yz_idx, Register idx,
5602 Register jdx,
5603 Register carry, Register product,
5604 Register carry2) {
5605 // jlong carry, x[], y[], z[];
5606 // int kdx = ystart+1;
5607 // for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
5608 // huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
5609 // z[kdx+idx+1] = (jlong)product;
5610 // jlong carry2 = (jlong)(product >>> 64);
5611 // product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
5612 // z[kdx+idx] = (jlong)product;
5613 // carry = (jlong)(product >>> 64);
5614 // }
5615 // idx += 2;
5616 // if (idx > 0) {
5617 // product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
5618 // z[kdx+idx] = (jlong)product;
5619 // carry = (jlong)(product >>> 64);
5620 // }
5621
5622 Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
5623
5624 // scale the index
5625 lgr_if_needed(jdx, idx);
5626 and_imm(jdx, 0xfffffffffffffffcL);
5627 rshift(jdx, 2);
5628
5629
5630 bind(L_third_loop);
5631
5632 z_aghi(jdx, -1);
5633 z_brl(L_third_loop_exit);
5634 add2reg(idx, -4);
5635
5636 multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
5637 lgr_if_needed(carry2, product);
5638
5639 multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
5640 lgr_if_needed(carry, product);
5641 z_bru(L_third_loop);
5642
5643
5644 bind(L_third_loop_exit); // Handle any left-over operand parts.
5645
5646 and_imm(idx, 0x3);
5647 z_brz(L_post_third_loop_done);
5648
5649 Label L_check_1;
5650
5651 z_aghi(idx, -2);
5652 z_brl(L_check_1);
5653
5654 multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
5655 lgr_if_needed(carry, product);
5656
5657
5658 bind(L_check_1);
5659
5660 add2reg(idx, 0x2);
5661 and_imm(idx, 0x1);
5662 z_aghi(idx, -1);
5663 z_brl(L_post_third_loop_done);
5664
5665 Register multiplicand = product->successor();
5666 Register product_low = multiplicand;
5667
5668 z_sllg(Z_R7, idx, LogBytesPerInt);
5669 clear_reg(yz_idx);
5670 mem2reg_opt(yz_idx, Address(y, Z_R7, 0), false);
5671 lgr_if_needed(multiplicand, x_xstart);
5672 z_mlgr(product, yz_idx); // multiplicand * yz_idx -> product::multiplicand
5673 clear_reg(yz_idx);
5674 mem2reg_opt(yz_idx, Address(z, Z_R7, 0), false);
5675
5676 add2_with_carry(product, product_low, yz_idx, carry);
5677
5678 z_sllg(Z_R7, idx, LogBytesPerInt);
5679 reg2mem_opt(product_low, Address(z, Z_R7, 0), false);
5680 rshift(product_low, 32);
5681
5682 lshift(product, 32);
5683 z_ogr(product_low, product);
5684 lgr_if_needed(carry, product_low);
5685
5686 bind(L_post_third_loop_done);
5687 }
5688
5689 void MacroAssembler::multiply_to_len(Register x, Register xlen,
5690 Register y, Register ylen,
5691 Register z,
5692 Register tmp1, Register tmp2,
5693 Register tmp3, Register tmp4,
5694 Register tmp5) {
5695 ShortBranchVerifier sbv(this);
5696
5697 assert_different_registers(x, xlen, y, ylen, z,
5698 tmp1, tmp2, tmp3, tmp4, tmp5, Z_R1_scratch, Z_R7);
5699 assert_different_registers(x, xlen, y, ylen, z,
5700 tmp1, tmp2, tmp3, tmp4, tmp5, Z_R8);
5701
5702 z_stmg(Z_R7, Z_R13, _z_abi(gpr7), Z_SP);
5703
5704 const Register idx = tmp1;
5705 const Register kdx = tmp2;
5706 const Register xstart = tmp3;
5707
5708 const Register y_idx = tmp4;
5709 const Register carry = tmp5;
5710 const Register product = Z_R0_scratch;
5711 const Register x_xstart = Z_R8;
5712
5713 // First Loop.
5714 //
5715 // final static long LONG_MASK = 0xffffffffL;
5716 // int xstart = xlen - 1;
5717 // int ystart = ylen - 1;
5718 // long carry = 0;
5719 // for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
5720 // long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
5721 // z[kdx] = (int)product;
5722 // carry = product >>> 32;
5723 // }
5724 // z[xstart] = (int)carry;
5725 //
5726
5727 lgr_if_needed(idx, ylen); // idx = ylen
5728 z_agrk(kdx, xlen, ylen); // kdx = xlen + ylen
5729 clear_reg(carry); // carry = 0
5730
5731 Label L_done;
5732
5733 lgr_if_needed(xstart, xlen);
5734 z_aghi(xstart, -1);
5735 z_brl(L_done);
5736
5737 multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
5738
5739 NearLabel L_second_loop;
5740 compare64_and_branch(kdx, RegisterOrConstant((intptr_t) 0), bcondEqual, L_second_loop);
5741
5742 NearLabel L_carry;
5743 z_aghi(kdx, -1);
5744 z_brz(L_carry);
5745
5746 // Store lower 32 bits of carry.
5747 z_sllg(Z_R1_scratch, kdx, LogBytesPerInt);
5748 reg2mem_opt(carry, Address(z, Z_R1_scratch, 0), false);
5749 rshift(carry, 32);
5750 z_aghi(kdx, -1);
5751
5752
5753 bind(L_carry);
5754
5755 // Store upper 32 bits of carry.
5756 z_sllg(Z_R1_scratch, kdx, LogBytesPerInt);
5757 reg2mem_opt(carry, Address(z, Z_R1_scratch, 0), false);
5758
5759 // Second and third (nested) loops.
5760 //
5761 // for (int i = xstart-1; i >= 0; i--) { // Second loop
5762 // carry = 0;
5763 // for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
5764 // long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
5765 // (z[k] & LONG_MASK) + carry;
5766 // z[k] = (int)product;
5767 // carry = product >>> 32;
5768 // }
5769 // z[i] = (int)carry;
5770 // }
5771 //
5772 // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
5773
5774 const Register jdx = tmp1;
5775
5776 bind(L_second_loop);
5777
5778 clear_reg(carry); // carry = 0;
5779 lgr_if_needed(jdx, ylen); // j = ystart+1
5780
5781 z_aghi(xstart, -1); // i = xstart-1;
5782 z_brl(L_done);
5783
5784 // Use free slots in the current stackframe instead of push/pop.
5785 Address zsave(Z_SP, _z_abi(carg_1));
5786 reg2mem_opt(z, zsave);
5787
5788
5789 Label L_last_x;
5790
5791 z_sllg(Z_R1_scratch, xstart, LogBytesPerInt);
5792 load_address(z, Address(z, Z_R1_scratch, 4)); // z = z + k - j
5793 z_aghi(xstart, -1); // i = xstart-1;
5794 z_brl(L_last_x);
5795
5796 z_sllg(Z_R1_scratch, xstart, LogBytesPerInt);
5797 mem2reg_opt(x_xstart, Address(x, Z_R1_scratch, 0));
5798
5799
5800 Label L_third_loop_prologue;
5801
5802 bind(L_third_loop_prologue);
5803
5804 Address xsave(Z_SP, _z_abi(carg_2));
5805 Address xlensave(Z_SP, _z_abi(carg_3));
5806 Address ylensave(Z_SP, _z_abi(carg_4));
5807
5808 reg2mem_opt(x, xsave);
5809 reg2mem_opt(xstart, xlensave);
5810 reg2mem_opt(ylen, ylensave);
5811
5812
5813 multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
5814
5815 mem2reg_opt(z, zsave);
5816 mem2reg_opt(x, xsave);
5817 mem2reg_opt(xlen, xlensave); // This is the decrement of the loop counter!
5818 mem2reg_opt(ylen, ylensave);
5819
5820 add2reg(tmp3, 1, xlen);
5821 z_sllg(Z_R1_scratch, tmp3, LogBytesPerInt);
5822 reg2mem_opt(carry, Address(z, Z_R1_scratch, 0), false);
5823 z_aghi(tmp3, -1);
5824 z_brl(L_done);
5825
5826 rshift(carry, 32);
5827 z_sllg(Z_R1_scratch, tmp3, LogBytesPerInt);
5828 reg2mem_opt(carry, Address(z, Z_R1_scratch, 0), false);
5829 z_bru(L_second_loop);
5830
5831 // Next infrequent code is moved outside loops.
5832 bind(L_last_x);
5833
5834 clear_reg(x_xstart);
5835 mem2reg_opt(x_xstart, Address(x, (intptr_t) 0), false);
5836 z_bru(L_third_loop_prologue);
5837
5838 bind(L_done);
5839
5840 z_lmg(Z_R7, Z_R13, _z_abi(gpr7), Z_SP);
5841 }
5842
5843 void MacroAssembler::asm_assert(branch_condition cond, const char* msg, int id, bool is_static) {
5844 #ifdef ASSERT
5845 Label ok;
5846 z_brc(cond, ok);
5847 is_static ? stop_static(msg, id) : stop(msg, id);
5848 bind(ok);
5849 #endif // ASSERT
5850 }
5851
5852 // Assert if CC indicates "not equal" (check_equal==true) or "equal" (check_equal==false).
5853 void MacroAssembler::asm_assert(bool check_equal, const char *msg, int id) {
5854 #ifdef ASSERT
5855 asm_assert(check_equal ? bcondEqual : bcondNotEqual, msg, id);
5856 #endif // ASSERT
5857 }
5858
5859 void MacroAssembler::asm_assert_mems_zero(bool check_equal, bool allow_relocation, int size, int64_t mem_offset,
5860 Register mem_base, const char* msg, int id) {
5861 #ifdef ASSERT
5862 switch (size) {
5863 case 4:
5864 load_and_test_int(Z_R0, Address(mem_base, mem_offset));
5865 break;
5866 case 8:
5867 load_and_test_long(Z_R0, Address(mem_base, mem_offset));
5868 break;
5869 default:
5870 ShouldNotReachHere();
5871 }
5872 // if relocation is not allowed then stop_static() will be called otherwise call stop()
5873 asm_assert(check_equal ? bcondEqual : bcondNotEqual, msg, id, !allow_relocation);
5874 #endif // ASSERT
5875 }
5876
5877 // Check the condition
5878 // expected_size == FP - SP
5879 // after transformation:
5880 // expected_size - FP + SP == 0
5881 // Destroys Register expected_size if no tmp register is passed.
5882 void MacroAssembler::asm_assert_frame_size(Register expected_size, Register tmp, const char* msg, int id) {
5883 #ifdef ASSERT
5884 lgr_if_needed(tmp, expected_size);
5885 z_algr(tmp, Z_SP);
5886 z_slg(tmp, 0, Z_R0, Z_SP);
5887 asm_assert(bcondEqual, msg, id);
5888 #endif // ASSERT
5889 }
5890
5891 #ifdef ASSERT
5892 bool is_excluded(Register excluded_register[], Register reg, int n) {
5893 for (int i = 0; i < n; i++) {
5894 if (excluded_register[i] == reg) {
5895 return true;
5896 }
5897 }
5898 return false;
5899 }
5900
5901 void MacroAssembler::clobber_volatile_registers(Register excluded_register[], int n) {
5902 const int magic_number = 0xbadbad;
5903
5904 for (int i = 0; i < 6 /* R0 to R5 */; i++) {
5905 Register reg = as_Register(i);
5906 if (!is_excluded(excluded_register, reg, n)) {
5907 load_const_optimized(reg, magic_number);
5908 }
5909 }
5910 }
5911
5912 void MacroAssembler::clobber_nonvolatile_registers() {
5913 BLOCK_COMMENT("clobber_nonvolatile_registers {");
5914 static const Register regs[] = {
5915 Z_R6,
5916 Z_R7,
5917 // don't zap Z_thread (Z_R8)
5918 Z_R9,
5919 Z_R10,
5920 Z_R11,
5921 Z_R12,
5922 Z_R13
5923 };
5924 Register bad = regs[0];
5925 load_const_optimized(bad, 0xbad0101babe11111);
5926 for (uint32_t i = 1; i < (sizeof(regs) / sizeof(Register)); i++) {
5927 z_lgr(regs[i], bad);
5928 }
5929 BLOCK_COMMENT("} clobber_nonvolatile_registers");
5930 }
5931 #endif // ASSERT
5932
5933 // Save and restore functions: Exclude Z_R0.
5934 void MacroAssembler::save_volatile_regs(Register dst, int offset, bool include_fp, bool include_flags) {
5935 z_stmg(Z_R1, Z_R5, offset, dst); offset += 5 * BytesPerWord;
5936 if (include_fp) {
5937 z_std(Z_F0, Address(dst, offset)); offset += BytesPerWord;
5938 z_std(Z_F1, Address(dst, offset)); offset += BytesPerWord;
5939 z_std(Z_F2, Address(dst, offset)); offset += BytesPerWord;
5940 z_std(Z_F3, Address(dst, offset)); offset += BytesPerWord;
5941 z_std(Z_F4, Address(dst, offset)); offset += BytesPerWord;
5942 z_std(Z_F5, Address(dst, offset)); offset += BytesPerWord;
5943 z_std(Z_F6, Address(dst, offset)); offset += BytesPerWord;
5944 z_std(Z_F7, Address(dst, offset)); offset += BytesPerWord;
5945 }
5946 if (include_flags) {
5947 Label done;
5948 z_mvi(Address(dst, offset), 2); // encoding: equal
5949 z_bre(done);
5950 z_mvi(Address(dst, offset), 4); // encoding: higher
5951 z_brh(done);
5952 z_mvi(Address(dst, offset), 1); // encoding: lower
5953 bind(done);
5954 }
5955 }
5956 void MacroAssembler::restore_volatile_regs(Register src, int offset, bool include_fp, bool include_flags) {
5957 z_lmg(Z_R1, Z_R5, offset, src); offset += 5 * BytesPerWord;
5958 if (include_fp) {
5959 z_ld(Z_F0, Address(src, offset)); offset += BytesPerWord;
5960 z_ld(Z_F1, Address(src, offset)); offset += BytesPerWord;
5961 z_ld(Z_F2, Address(src, offset)); offset += BytesPerWord;
5962 z_ld(Z_F3, Address(src, offset)); offset += BytesPerWord;
5963 z_ld(Z_F4, Address(src, offset)); offset += BytesPerWord;
5964 z_ld(Z_F5, Address(src, offset)); offset += BytesPerWord;
5965 z_ld(Z_F6, Address(src, offset)); offset += BytesPerWord;
5966 z_ld(Z_F7, Address(src, offset)); offset += BytesPerWord;
5967 }
5968 if (include_flags) {
5969 z_cli(Address(src, offset), 2); // see encoding above
5970 }
5971 }
5972
5973 // Plausibility check for oops.
5974 void MacroAssembler::verify_oop(Register oop, const char* msg) {
5975 if (!VerifyOops) return;
5976
5977 BLOCK_COMMENT("verify_oop {");
5978 unsigned int nbytes_save = (5 + 8 + 1) * BytesPerWord;
5979 address entry_addr = StubRoutines::verify_oop_subroutine_entry_address();
5980
5981 save_return_pc();
5982
5983 // Push frame, but preserve flags
5984 z_lgr(Z_R0, Z_SP);
5985 z_lay(Z_SP, -((int64_t)nbytes_save + frame::z_abi_160_size), Z_SP);
5986 z_stg(Z_R0, _z_abi(callers_sp), Z_SP);
5987
5988 save_volatile_regs(Z_SP, frame::z_abi_160_size, true, true);
5989
5990 lgr_if_needed(Z_ARG2, oop);
5991 load_const_optimized(Z_ARG1, (address)msg);
5992 load_const_optimized(Z_R1, entry_addr);
5993 z_lg(Z_R1, 0, Z_R1);
5994 call_c(Z_R1);
5995
5996 restore_volatile_regs(Z_SP, frame::z_abi_160_size, true, true);
5997 pop_frame();
5998 restore_return_pc();
5999
6000 BLOCK_COMMENT("} verify_oop ");
6001 }
6002
6003 void MacroAssembler::verify_oop_addr(Address addr, const char* msg) {
6004 if (!VerifyOops) return;
6005
6006 BLOCK_COMMENT("verify_oop {");
6007 unsigned int nbytes_save = (5 + 8) * BytesPerWord;
6008 address entry_addr = StubRoutines::verify_oop_subroutine_entry_address();
6009
6010 save_return_pc();
6011 unsigned int frame_size = push_frame_abi160(nbytes_save); // kills Z_R0
6012 save_volatile_regs(Z_SP, frame::z_abi_160_size, true, false);
6013
6014 z_lg(Z_ARG2, addr.plus_disp(frame_size));
6015 load_const_optimized(Z_ARG1, (address)msg);
6016 load_const_optimized(Z_R1, entry_addr);
6017 z_lg(Z_R1, 0, Z_R1);
6018 call_c(Z_R1);
6019
6020 restore_volatile_regs(Z_SP, frame::z_abi_160_size, true, false);
6021 pop_frame();
6022 restore_return_pc();
6023
6024 BLOCK_COMMENT("} verify_oop ");
6025 }
6026
6027 const char* MacroAssembler::stop_types[] = {
6028 "stop",
6029 "untested",
6030 "unimplemented",
6031 "shouldnotreachhere"
6032 };
6033
6034 static void stop_on_request(const char* tp, const char* msg) {
6035 tty->print("Z assembly code requires stop: (%s) %s\n", tp, msg);
6036 guarantee(false, "Z assembly code requires stop: %s", msg);
6037 }
6038
6039 void MacroAssembler::stop(int type, const char* msg, int id) {
6040 BLOCK_COMMENT(err_msg("stop: %s {", msg));
6041
6042 // Setup arguments.
6043 load_const(Z_ARG1, (void*) stop_types[type%stop_end]);
6044 load_const(Z_ARG2, (void*) msg);
6045 get_PC(Z_R14); // Following code pushes a frame without entering a new function. Use current pc as return address.
6046 save_return_pc(); // Saves return pc Z_R14.
6047 push_frame_abi160(0);
6048 call_VM_leaf(CAST_FROM_FN_PTR(address, stop_on_request), Z_ARG1, Z_ARG2);
6049 // The plain disassembler does not recognize illtrap. It instead displays
6050 // a 32-bit value. Issuing two illtraps assures the disassembler finds
6051 // the proper beginning of the next instruction.
6052 z_illtrap(id); // Illegal instruction.
6053 z_illtrap(id); // Illegal instruction.
6054
6055 BLOCK_COMMENT(" } stop");
6056 }
6057
6058 // Special version of stop() for code size reduction.
6059 // Reuses the previously generated call sequence, if any.
6060 // Generates the call sequence on its own, if necessary.
6061 // Note: This code will work only in non-relocatable code!
6062 // The relative address of the data elements (arg1, arg2) must not change.
6063 // The reentry point must not move relative to it's users. This prerequisite
6064 // should be given for "hand-written" code, if all chain calls are in the same code blob.
6065 // Generated code must not undergo any transformation, e.g. ShortenBranches, to be safe.
6066 address MacroAssembler::stop_chain(address reentry, int type, const char* msg, int id, bool allow_relocation) {
6067 BLOCK_COMMENT(err_msg("stop_chain(%s,%s): %s {", reentry==nullptr?"init":"cont", allow_relocation?"reloc ":"static", msg));
6068
6069 // Setup arguments.
6070 if (allow_relocation) {
6071 // Relocatable version (for comparison purposes). Remove after some time.
6072 load_const(Z_ARG1, (void*) stop_types[type%stop_end]);
6073 load_const(Z_ARG2, (void*) msg);
6074 } else {
6075 load_absolute_address(Z_ARG1, (address)stop_types[type%stop_end]);
6076 load_absolute_address(Z_ARG2, (address)msg);
6077 }
6078 if ((reentry != nullptr) && RelAddr::is_in_range_of_RelAddr16(reentry, pc())) {
6079 BLOCK_COMMENT("branch to reentry point:");
6080 z_brc(bcondAlways, reentry);
6081 } else {
6082 BLOCK_COMMENT("reentry point:");
6083 reentry = pc(); // Re-entry point for subsequent stop calls.
6084 save_return_pc(); // Saves return pc Z_R14.
6085 push_frame_abi160(0);
6086 if (allow_relocation) {
6087 reentry = nullptr; // Prevent reentry if code relocation is allowed.
6088 call_VM_leaf(CAST_FROM_FN_PTR(address, stop_on_request), Z_ARG1, Z_ARG2);
6089 } else {
6090 call_VM_leaf_static(CAST_FROM_FN_PTR(address, stop_on_request), Z_ARG1, Z_ARG2);
6091 }
6092 z_illtrap(id); // Illegal instruction as emergency stop, should the above call return.
6093 }
6094 BLOCK_COMMENT(" } stop_chain");
6095
6096 return reentry;
6097 }
6098
6099 // Special version of stop() for code size reduction.
6100 // Assumes constant relative addresses for data and runtime call.
6101 void MacroAssembler::stop_static(int type, const char* msg, int id) {
6102 stop_chain(nullptr, type, msg, id, false);
6103 }
6104
6105 void MacroAssembler::stop_subroutine() {
6106 unimplemented("stop_subroutine", 710);
6107 }
6108
6109 // Prints msg to stdout from within generated code..
6110 void MacroAssembler::warn(const char* msg) {
6111 RegisterSaver::save_live_registers(this, RegisterSaver::all_registers, Z_R14);
6112 load_absolute_address(Z_R1, (address) warning);
6113 load_absolute_address(Z_ARG1, (address) msg);
6114 (void) call(Z_R1);
6115 RegisterSaver::restore_live_registers(this, RegisterSaver::all_registers);
6116 }
6117
6118 #ifndef PRODUCT
6119
6120 // Write pattern 0x0101010101010101 in region [low-before, high+after].
6121 void MacroAssembler::zap_from_to(Register low, Register high, Register val, Register addr, int before, int after) {
6122 if (!ZapEmptyStackFields) return;
6123 BLOCK_COMMENT("zap memory region {");
6124 load_const_optimized(val, 0x0101010101010101);
6125 int size = before + after;
6126 if (low == high && size < 5 && size > 0) {
6127 int offset = -before*BytesPerWord;
6128 for (int i = 0; i < size; ++i) {
6129 z_stg(val, Address(low, offset));
6130 offset +=(1*BytesPerWord);
6131 }
6132 } else {
6133 add2reg(addr, -before*BytesPerWord, low);
6134 if (after) {
6135 #ifdef ASSERT
6136 jlong check = after * BytesPerWord;
6137 assert(Immediate::is_simm32(check) && Immediate::is_simm32(-check), "value not encodable !");
6138 #endif
6139 add2reg(high, after * BytesPerWord);
6140 }
6141 NearLabel loop;
6142 bind(loop);
6143 z_stg(val, Address(addr));
6144 add2reg(addr, 8);
6145 compare64_and_branch(addr, high, bcondNotHigh, loop);
6146 if (after) {
6147 add2reg(high, -after * BytesPerWord);
6148 }
6149 }
6150 BLOCK_COMMENT("} zap memory region");
6151 }
6152 #endif // !PRODUCT
6153
6154 // Implements fast-locking.
6155 // - obj: the object to be locked, contents preserved.
6156 // - temp1, temp2: temporary registers, contents destroyed.
6157 // Note: make sure Z_R1 is not manipulated here when C2 compiler is in play
6158 void MacroAssembler::fast_lock(Register basic_lock, Register obj, Register temp1, Register temp2, Label& slow) {
6159
6160 assert_different_registers(basic_lock, obj, temp1, temp2);
6161
6162 Label push;
6163 const Register top = temp1;
6164 const Register mark = temp2;
6165 const int mark_offset = oopDesc::mark_offset_in_bytes();
6166 const ByteSize ls_top_offset = JavaThread::lock_stack_top_offset();
6167
6168 // Preload the markWord. It is important that this is the first
6169 // instruction emitted as it is part of C1's null check semantics.
6170 z_lg(mark, Address(obj, mark_offset));
6171
6172 if (UseObjectMonitorTable) {
6173 // Clear cache in case fast locking succeeds or we need to take the slow-path.
6174 const Address om_cache_addr = Address(basic_lock, BasicObjectLock::lock_offset() + in_ByteSize((BasicLock::object_monitor_cache_offset_in_bytes())));
6175 z_mvghi(om_cache_addr, 0);
6176 }
6177
6178 if (DiagnoseSyncOnValueBasedClasses != 0) {
6179 load_klass(temp1, obj);
6180 z_tm(Address(temp1, Klass::misc_flags_offset()), KlassFlags::_misc_is_value_based_class);
6181 z_brnaz(slow);
6182 }
6183
6184 // First we need to check if the lock-stack has room for pushing the object reference.
6185 z_lgf(top, Address(Z_thread, ls_top_offset));
6186
6187 compareU32_and_branch(top, (unsigned)LockStack::end_offset(), bcondNotLow, slow);
6188
6189 // The underflow check is elided. The recursive check will always fail
6190 // when the lock stack is empty because of the _bad_oop_sentinel field.
6191
6192 // Check for recursion:
6193 z_aghi(top, -oopSize);
6194 z_cg(obj, Address(Z_thread, top));
6195 z_bre(push);
6196
6197 // Check header for monitor (0b10).
6198 z_tmll(mark, markWord::monitor_value);
6199 branch_optimized(bcondNotAllZero, slow);
6200
6201 { // Try to lock. Transition lock bits 0b01 => 0b00
6202 const Register locked_obj = top;
6203 z_oill(mark, markWord::unlocked_value);
6204 z_lgr(locked_obj, mark);
6205 // Clear lock-bits from locked_obj (locked state)
6206 z_xilf(locked_obj, markWord::unlocked_value);
6207 z_csg(mark, locked_obj, mark_offset, obj);
6208 branch_optimized(Assembler::bcondNotEqual, slow);
6209 }
6210
6211 bind(push);
6212
6213 // After successful lock, push object on lock-stack
6214 z_lgf(top, Address(Z_thread, ls_top_offset));
6215 z_stg(obj, Address(Z_thread, top));
6216 z_alsi(in_bytes(ls_top_offset), Z_thread, oopSize);
6217 }
6218
6219 // Implements fast-unlocking.
6220 // - obj: the object to be unlocked
6221 // - temp1, temp2: temporary registers, will be destroyed
6222 // - Z_R1_scratch: will be killed in case of Interpreter & C1 Compiler
6223 void MacroAssembler::fast_unlock(Register obj, Register temp1, Register temp2, Label& slow) {
6224
6225 assert_different_registers(obj, temp1, temp2);
6226
6227 Label unlocked, push_and_slow;
6228 const Register mark = temp1;
6229 const Register top = temp2;
6230 const int mark_offset = oopDesc::mark_offset_in_bytes();
6231 const ByteSize ls_top_offset = JavaThread::lock_stack_top_offset();
6232
6233 #ifdef ASSERT
6234 {
6235 // The following checks rely on the fact that LockStack is only ever modified by
6236 // its owning thread, even if the lock got inflated concurrently; removal of LockStack
6237 // entries after inflation will happen delayed in that case.
6238
6239 // Check for lock-stack underflow.
6240 NearLabel stack_ok;
6241 z_lgf(top, Address(Z_thread, ls_top_offset));
6242 compareU32_and_branch(top, (unsigned)LockStack::start_offset(), bcondNotLow, stack_ok);
6243 stop("Lock-stack underflow");
6244 bind(stack_ok);
6245 }
6246 #endif // ASSERT
6247
6248 // Check if obj is top of lock-stack.
6249 z_lgf(top, Address(Z_thread, ls_top_offset));
6250 z_aghi(top, -oopSize);
6251 z_cg(obj, Address(Z_thread, top));
6252 branch_optimized(bcondNotEqual, slow);
6253
6254 // pop object from lock-stack
6255 #ifdef ASSERT
6256 const Register temp_top = temp1; // mark is not yet loaded, but be careful
6257 z_agrk(temp_top, top, Z_thread);
6258 z_xc(0, oopSize-1, temp_top, 0, temp_top); // wipe out lock-stack entry
6259 #endif // ASSERT
6260 z_alsi(in_bytes(ls_top_offset), Z_thread, -oopSize); // pop object
6261
6262 // The underflow check is elided. The recursive check will always fail
6263 // when the lock stack is empty because of the _bad_oop_sentinel field.
6264
6265 // Check if recursive. (this is a check for the 2nd object on the stack)
6266 z_aghi(top, -oopSize);
6267 z_cg(obj, Address(Z_thread, top));
6268 branch_optimized(bcondEqual, unlocked);
6269
6270 // Not recursive. Check header for monitor (0b10).
6271 z_lg(mark, Address(obj, mark_offset));
6272 z_tmll(mark, markWord::monitor_value);
6273 z_brnaz(push_and_slow);
6274
6275 #ifdef ASSERT
6276 // Check header not unlocked (0b01).
6277 NearLabel not_unlocked;
6278 z_tmll(mark, markWord::unlocked_value);
6279 z_braz(not_unlocked);
6280 stop("fast_unlock already unlocked");
6281 bind(not_unlocked);
6282 #endif // ASSERT
6283
6284 { // Try to unlock. Transition lock bits 0b00 => 0b01
6285 Register unlocked_obj = top;
6286 z_lgr(unlocked_obj, mark);
6287 z_oill(unlocked_obj, markWord::unlocked_value);
6288 z_csg(mark, unlocked_obj, mark_offset, obj);
6289 branch_optimized(Assembler::bcondEqual, unlocked);
6290 }
6291
6292 bind(push_and_slow);
6293
6294 // Restore lock-stack and handle the unlock in runtime.
6295 z_lgf(top, Address(Z_thread, ls_top_offset));
6296 DEBUG_ONLY(z_stg(obj, Address(Z_thread, top));)
6297 z_alsi(in_bytes(ls_top_offset), Z_thread, oopSize);
6298 // set CC to NE
6299 z_ltgr(obj, obj); // object shouldn't be null at this point
6300 branch_optimized(bcondAlways, slow);
6301
6302 bind(unlocked);
6303 }
6304
6305 void MacroAssembler::compiler_fast_lock_object(Register obj, Register box, Register tmp1, Register tmp2) {
6306 assert_different_registers(obj, box, tmp1, tmp2, Z_R0_scratch);
6307
6308 // Handle inflated monitor.
6309 NearLabel inflated;
6310 // Finish fast lock successfully. MUST reach to with flag == NE
6311 NearLabel locked;
6312 // Finish fast lock unsuccessfully. MUST branch to with flag == EQ
6313 NearLabel slow_path;
6314
6315 if (UseObjectMonitorTable) {
6316 // Clear cache in case fast locking succeeds or we need to take the slow-path.
6317 z_mvghi(Address(box, BasicLock::object_monitor_cache_offset_in_bytes()), 0);
6318 }
6319
6320 if (DiagnoseSyncOnValueBasedClasses != 0) {
6321 load_klass(tmp1, obj);
6322 z_tm(Address(tmp1, Klass::misc_flags_offset()), KlassFlags::_misc_is_value_based_class);
6323 z_brne(slow_path);
6324 }
6325
6326 const Register mark = tmp1;
6327 const int mark_offset = oopDesc::mark_offset_in_bytes();
6328 const ByteSize ls_top_offset = JavaThread::lock_stack_top_offset();
6329
6330 BLOCK_COMMENT("compiler_fast_locking {");
6331 { // Fast locking
6332
6333 // Push lock to the lock stack and finish successfully. MUST reach to with flag == EQ
6334 NearLabel push;
6335
6336 const Register top = tmp2;
6337
6338 // Check if lock-stack is full.
6339 z_lgf(top, Address(Z_thread, ls_top_offset));
6340 compareU32_and_branch(top, (unsigned) LockStack::end_offset() - 1, bcondHigh, slow_path);
6341
6342 // The underflow check is elided. The recursive check will always fail
6343 // when the lock stack is empty because of the _bad_oop_sentinel field.
6344
6345 // Check if recursive.
6346 z_aghi(top, -oopSize);
6347 z_cg(obj, Address(Z_thread, top));
6348 z_bre(push);
6349
6350 // Check for monitor (0b10)
6351 z_lg(mark, Address(obj, mark_offset));
6352 z_tmll(mark, markWord::monitor_value);
6353 z_brnaz(inflated);
6354
6355 // not inflated
6356
6357 { // Try to lock. Transition lock bits 0b01 => 0b00
6358 assert(mark_offset == 0, "required to avoid a lea");
6359 const Register locked_obj = top;
6360 z_oill(mark, markWord::unlocked_value);
6361 z_lgr(locked_obj, mark);
6362 // Clear lock-bits from locked_obj (locked state)
6363 z_xilf(locked_obj, markWord::unlocked_value);
6364 z_csg(mark, locked_obj, mark_offset, obj);
6365 branch_optimized(Assembler::bcondNotEqual, slow_path);
6366 }
6367
6368 bind(push);
6369
6370 // After successful lock, push object on lock-stack.
6371 z_lgf(top, Address(Z_thread, ls_top_offset));
6372 z_stg(obj, Address(Z_thread, top));
6373 z_alsi(in_bytes(ls_top_offset), Z_thread, oopSize);
6374
6375 z_cgr(obj, obj); // set the CC to EQ, as it could be changed by alsi
6376 z_bru(locked);
6377 }
6378 BLOCK_COMMENT("} compiler_fast_locking");
6379
6380 BLOCK_COMMENT("handle_inflated_monitor_locking {");
6381 { // Handle inflated monitor.
6382 bind(inflated);
6383
6384 const Register tmp1_monitor = tmp1;
6385 // Offsets into the current thread's object monitor cache (omc).
6386 const ByteSize thr_omc_offset = JavaThread::om_cache_offset();
6387 const ByteSize omc_monitor_offset = OMCache::monitor_offset();
6388 const ByteSize omc_obj_offset = OMCache::obj_offset();
6389
6390 if (!UseObjectMonitorTable) {
6391 assert(tmp1_monitor == mark, "should be the same here");
6392 } else {
6393 const Register tmp1_bucket = tmp1;
6394 const Register hash = Z_R0_scratch;
6395 NearLabel monitor_found;
6396
6397 // Save the mark, we might need it to extract the hash.
6398 z_lgr(hash, mark);
6399
6400 // Look for the monitor in the current thread's object monitor cache (omc).
6401
6402 z_lg(tmp1_monitor, Address(Z_thread, thr_omc_offset + omc_monitor_offset));
6403 z_cg(obj, Address(Z_thread, thr_omc_offset + omc_obj_offset));
6404 z_bre(monitor_found);
6405
6406 // Get the hash code.
6407 z_srlg(hash, hash, markWord::hash_shift);
6408
6409 // Get the table and calculate the bucket's address.
6410 load_const_optimized(tmp2, ObjectMonitorTable::current_table_address());
6411 z_lg(tmp2, Address(tmp2));
6412 z_ng(hash, Address(tmp2, ObjectMonitorTable::table_capacity_mask_offset()));
6413 z_lg(tmp1_bucket, Address(tmp2, ObjectMonitorTable::table_buckets_offset()));
6414 z_sllg(hash, hash, LogBytesPerWord);
6415 z_agr(tmp1_bucket, hash);
6416
6417 // Read the monitor from the bucket.
6418 z_lg(tmp1_monitor, Address(tmp1_bucket));
6419
6420 // Check if the monitor in the bucket is special (empty, tombstone or removed).
6421 z_clgfi(tmp1_monitor, ObjectMonitorTable::SpecialPointerValues::below_is_special);
6422 z_brl(slow_path);
6423
6424 // Check if object matches.
6425 z_lg(tmp2, Address(tmp1_monitor, ObjectMonitor::object_offset()));
6426 BarrierSetAssembler* bs_asm = BarrierSet::barrier_set()->barrier_set_assembler();
6427 bs_asm->try_peek_weak_handle_in_nmethod(this, tmp2, tmp2, Z_R0_scratch, slow_path);
6428 z_cgr(obj, tmp2);
6429 z_brne(slow_path);
6430
6431 // Store the monitor in the current thread's object monitor cache (omc).
6432 z_stg(tmp1_monitor, Address(Z_thread, thr_omc_offset + omc_monitor_offset));
6433 z_stg(obj, Address(Z_thread, thr_omc_offset + omc_obj_offset));
6434
6435 bind(monitor_found);
6436 }
6437 NearLabel monitor_locked;
6438 // lock the monitor
6439
6440 const Register zero = tmp2;
6441
6442 const ByteSize monitor_tag = in_ByteSize(UseObjectMonitorTable ? 0 : checked_cast<int>(markWord::monitor_value));
6443 const Address owner_address(tmp1_monitor, ObjectMonitor::owner_offset() - monitor_tag);
6444 const Address recursions_address(tmp1_monitor, ObjectMonitor::recursions_offset() - monitor_tag);
6445
6446
6447 // Try to CAS owner (no owner => current thread's _monitor_owner_id).
6448 // If csg succeeds then CR=EQ, otherwise, register zero is filled
6449 // with the current owner.
6450 z_lghi(zero, 0);
6451 z_lg(Z_R0_scratch, Address(Z_thread, JavaThread::monitor_owner_id_offset()));
6452 z_csg(zero, Z_R0_scratch, owner_address);
6453 z_bre(monitor_locked);
6454
6455 // Check if recursive.
6456 z_cgr(Z_R0_scratch, zero); // zero contains the owner from z_csg instruction
6457 z_brne(slow_path);
6458
6459 // Recursive
6460 z_agsi(recursions_address, 1ll);
6461
6462 bind(monitor_locked);
6463 if (UseObjectMonitorTable) {
6464 // Cache the monitor for unlock.
6465 z_stg(tmp1_monitor, Address(box, BasicLock::object_monitor_cache_offset_in_bytes()));
6466 }
6467 // set the CC now
6468 z_cgr(obj, obj);
6469 }
6470 BLOCK_COMMENT("} handle_inflated_monitor_locking");
6471
6472 bind(locked);
6473
6474 #ifdef ASSERT
6475 // Check that locked label is reached with flag == EQ.
6476 NearLabel flag_correct;
6477 z_bre(flag_correct);
6478 stop("CC is not set to EQ, it should be - lock");
6479 #endif // ASSERT
6480
6481 bind(slow_path);
6482
6483 #ifdef ASSERT
6484 // Check that slow_path label is reached with flag == NE.
6485 z_brne(flag_correct);
6486 stop("CC is not set to NE, it should be - lock");
6487 bind(flag_correct);
6488 #endif // ASSERT
6489
6490 // C2 uses the value of flag (NE vs EQ) to determine the continuation.
6491 }
6492
6493 void MacroAssembler::compiler_fast_unlock_object(Register obj, Register box, Register tmp1, Register tmp2) {
6494 assert_different_registers(obj, box, tmp1, tmp2);
6495
6496 // Handle inflated monitor.
6497 NearLabel inflated, inflated_load_mark;
6498 // Finish fast unlock successfully. MUST reach to with flag == EQ.
6499 NearLabel unlocked;
6500 // Finish fast unlock unsuccessfully. MUST branch to with flag == NE.
6501 NearLabel slow_path;
6502
6503 const Register mark = tmp1;
6504 const Register top = tmp2;
6505 const int mark_offset = oopDesc::mark_offset_in_bytes();
6506 const ByteSize ls_top_offset = JavaThread::lock_stack_top_offset();
6507
6508 BLOCK_COMMENT("compiler_fast_unlock {");
6509 { // Fast Unlock
6510 NearLabel push_and_slow_path;
6511
6512 // Check if obj is top of lock-stack.
6513 z_lgf(top, Address(Z_thread, ls_top_offset));
6514
6515 z_aghi(top, -oopSize);
6516 z_cg(obj, Address(Z_thread, top));
6517 branch_optimized(bcondNotEqual, inflated_load_mark);
6518
6519 // Pop lock-stack.
6520 #ifdef ASSERT
6521 const Register temp_top = tmp1; // let's not kill top here, we can use for recursive check
6522 z_agrk(temp_top, top, Z_thread);
6523 z_xc(0, oopSize-1, temp_top, 0, temp_top); // wipe out lock-stack entry
6524 #endif
6525 z_alsi(in_bytes(ls_top_offset), Z_thread, -oopSize); // pop object
6526
6527 // The underflow check is elided. The recursive check will always fail
6528 // when the lock stack is empty because of the _bad_oop_sentinel field.
6529
6530 // Check if recursive.
6531 z_aghi(top, -oopSize);
6532 z_cg(obj, Address(Z_thread, top));
6533 z_bre(unlocked);
6534
6535 // Not recursive
6536
6537 // Check for monitor (0b10).
6538 // Because we got here by popping (meaning we pushed in locked)
6539 // there will be no monitor in the box. So we need to push back the obj
6540 // so that the runtime can fix any potential anonymous owner.
6541 z_lg(mark, Address(obj, mark_offset));
6542 z_tmll(mark, markWord::monitor_value);
6543 if (!UseObjectMonitorTable) {
6544 z_brnaz(inflated);
6545 } else {
6546 z_brnaz(push_and_slow_path);
6547 }
6548
6549 #ifdef ASSERT
6550 // Check header not unlocked (0b01).
6551 NearLabel not_unlocked;
6552 z_tmll(mark, markWord::unlocked_value);
6553 z_braz(not_unlocked);
6554 stop("fast_unlock already unlocked");
6555 bind(not_unlocked);
6556 #endif // ASSERT
6557
6558 { // Try to unlock. Transition lock bits 0b00 => 0b01
6559 Register unlocked_obj = top;
6560 z_lgr(unlocked_obj, mark);
6561 z_oill(unlocked_obj, markWord::unlocked_value);
6562 z_csg(mark, unlocked_obj, mark_offset, obj);
6563 branch_optimized(Assembler::bcondEqual, unlocked);
6564 }
6565
6566 bind(push_and_slow_path);
6567 // Restore lock-stack and handle the unlock in runtime.
6568 z_lgf(top, Address(Z_thread, ls_top_offset));
6569 DEBUG_ONLY(z_stg(obj, Address(Z_thread, top));)
6570 z_alsi(in_bytes(ls_top_offset), Z_thread, oopSize);
6571 // set CC to NE
6572 z_ltgr(obj, obj); // object is not null here
6573 z_bru(slow_path);
6574 }
6575 BLOCK_COMMENT("} compiler_fast_unlock");
6576
6577 { // Handle inflated monitor.
6578
6579 bind(inflated_load_mark);
6580
6581 z_lg(mark, Address(obj, mark_offset));
6582
6583 #ifdef ASSERT
6584 z_tmll(mark, markWord::monitor_value);
6585 z_brnaz(inflated);
6586 stop("Fast Unlock not monitor");
6587 #endif // ASSERT
6588
6589 bind(inflated);
6590
6591 #ifdef ASSERT
6592 NearLabel check_done, loop;
6593 z_lgf(top, Address(Z_thread, ls_top_offset));
6594 bind(loop);
6595 z_aghi(top, -oopSize);
6596 compareU32_and_branch(top, in_bytes(JavaThread::lock_stack_base_offset()),
6597 bcondLow, check_done);
6598 z_cg(obj, Address(Z_thread, top));
6599 z_brne(loop);
6600 stop("Fast Unlock lock on stack");
6601 bind(check_done);
6602 #endif // ASSERT
6603
6604 const Register tmp1_monitor = tmp1;
6605
6606 if (!UseObjectMonitorTable) {
6607 assert(tmp1_monitor == mark, "should be the same here");
6608 } else {
6609 // Uses ObjectMonitorTable. Look for the monitor in our BasicLock on the stack.
6610 z_lg(tmp1_monitor, Address(box, BasicLock::object_monitor_cache_offset_in_bytes()));
6611 // null check with ZF == 0, no valid pointer below alignof(ObjectMonitor*)
6612 z_cghi(tmp1_monitor, alignof(ObjectMonitor*));
6613
6614 z_brl(slow_path);
6615 }
6616
6617 // mark contains the tagged ObjectMonitor*.
6618 const Register monitor = mark;
6619
6620 const ByteSize monitor_tag = in_ByteSize(UseObjectMonitorTable ? 0 : checked_cast<int>(markWord::monitor_value));
6621 const Address recursions_address{monitor, ObjectMonitor::recursions_offset() - monitor_tag};
6622 const Address succ_address{monitor, ObjectMonitor::succ_offset() - monitor_tag};
6623 const Address entry_list_address{monitor, ObjectMonitor::entry_list_offset() - monitor_tag};
6624 const Address owner_address{monitor, ObjectMonitor::owner_offset() - monitor_tag};
6625
6626 NearLabel not_recursive;
6627 const Register recursions = tmp2;
6628
6629 // Check if recursive.
6630 load_and_test_long(recursions, recursions_address);
6631 z_bre(not_recursive); // if 0 then jump, it's not recursive locking
6632
6633 // Recursive unlock
6634 z_agsi(recursions_address, -1ll);
6635 z_cgr(monitor, monitor); // set the CC to EQUAL
6636 z_bru(unlocked);
6637
6638 bind(not_recursive);
6639
6640 NearLabel set_eq_unlocked;
6641
6642 // Set owner to null.
6643 // Release to satisfy the JMM
6644 z_release();
6645 z_lghi(tmp2, 0);
6646 z_stg(tmp2 /*=0*/, owner_address);
6647 // We need a full fence after clearing owner to avoid stranding.
6648 z_fence();
6649
6650 // Check if the entry_list is empty.
6651 load_and_test_long(tmp2, entry_list_address);
6652 z_bre(unlocked); // If so we are done.
6653
6654 // Check if there is a successor.
6655 load_and_test_long(tmp2, succ_address);
6656 z_brne(set_eq_unlocked); // If so we are done.
6657
6658 // Save the monitor pointer in the current thread, so we can try to
6659 // reacquire the lock in SharedRuntime::monitor_exit_helper().
6660 if (!UseObjectMonitorTable) {
6661 z_xilf(monitor, markWord::monitor_value);
6662 }
6663 z_stg(monitor, Address(Z_thread, JavaThread::unlocked_inflated_monitor_offset()));
6664
6665 z_ltgr(obj, obj); // Set flag = NE
6666 z_bru(slow_path);
6667
6668 bind(set_eq_unlocked);
6669 z_cr(tmp2, tmp2); // Set flag = EQ
6670 }
6671
6672 bind(unlocked);
6673
6674 #ifdef ASSERT
6675 // Check that unlocked label is reached with flag == EQ.
6676 NearLabel flag_correct;
6677 z_bre(flag_correct);
6678 stop("CC is not set to EQ, it should be - unlock");
6679 #endif // ASSERT
6680
6681 bind(slow_path);
6682
6683 #ifdef ASSERT
6684 // Check that slow_path label is reached with flag == NE.
6685 z_brne(flag_correct);
6686 stop("CC is not set to NE, it should be - unlock");
6687 bind(flag_correct);
6688 #endif // ASSERT
6689
6690 // C2 uses the value of flag (NE vs EQ) to determine the continuation.
6691 }
6692
6693 void MacroAssembler::pop_count_int(Register r_dst, Register r_src, Register r_tmp) {
6694 BLOCK_COMMENT("pop_count_int {");
6695
6696 assert(r_tmp != noreg, "temp register required for pop_count_int, as code may run on machine older than z15");
6697 assert_different_registers(r_dst, r_tmp); // if r_src is same as r_tmp, it should be fine
6698
6699 if (VM_Version::has_MiscInstrExt3()) {
6700 pop_count_int_with_ext3(r_dst, r_src);
6701 } else {
6702 pop_count_int_without_ext3(r_dst, r_src, r_tmp);
6703 }
6704
6705 BLOCK_COMMENT("} pop_count_int");
6706 }
6707
6708 void MacroAssembler::pop_count_long(Register r_dst, Register r_src, Register r_tmp) {
6709 BLOCK_COMMENT("pop_count_long {");
6710
6711 assert(r_tmp != noreg, "temp register required for pop_count_long, as code may run on machine older than z15");
6712 assert_different_registers(r_dst, r_tmp); // if r_src is same as r_tmp, it should be fine
6713
6714 if (VM_Version::has_MiscInstrExt3()) {
6715 pop_count_long_with_ext3(r_dst, r_src);
6716 } else {
6717 pop_count_long_without_ext3(r_dst, r_src, r_tmp);
6718 }
6719
6720 BLOCK_COMMENT("} pop_count_long");
6721 }
6722
6723 void MacroAssembler::pop_count_int_without_ext3(Register r_dst, Register r_src, Register r_tmp) {
6724 BLOCK_COMMENT("pop_count_int_without_ext3 {");
6725
6726 assert(r_tmp != noreg, "temp register required for popcnt, for machines < z15");
6727 assert_different_registers(r_dst, r_tmp); // if r_src is same as r_tmp, it should be fine
6728
6729 z_popcnt(r_dst, r_src, 0);
6730 z_srlg(r_tmp, r_dst, 16);
6731 z_alr(r_dst, r_tmp);
6732 z_srlg(r_tmp, r_dst, 8);
6733 z_alr(r_dst, r_tmp);
6734 z_llgcr(r_dst, r_dst);
6735
6736 BLOCK_COMMENT("} pop_count_int_without_ext3");
6737 }
6738
6739 void MacroAssembler::pop_count_long_without_ext3(Register r_dst, Register r_src, Register r_tmp) {
6740 BLOCK_COMMENT("pop_count_long_without_ext3 {");
6741
6742 assert(r_tmp != noreg, "temp register required for popcnt, for machines < z15");
6743 assert_different_registers(r_dst, r_tmp); // if r_src is same as r_tmp, it should be fine
6744
6745 z_popcnt(r_dst, r_src, 0);
6746 z_ahhlr(r_dst, r_dst, r_dst);
6747 z_sllg(r_tmp, r_dst, 16);
6748 z_algr(r_dst, r_tmp);
6749 z_sllg(r_tmp, r_dst, 8);
6750 z_algr(r_dst, r_tmp);
6751 z_srlg(r_dst, r_dst, 56);
6752
6753 BLOCK_COMMENT("} pop_count_long_without_ext3");
6754 }
6755
6756 void MacroAssembler::pop_count_long_with_ext3(Register r_dst, Register r_src) {
6757 BLOCK_COMMENT("pop_count_long_with_ext3 {");
6758
6759 guarantee(VM_Version::has_MiscInstrExt3(),
6760 "this hardware doesn't support miscellaneous-instruction-extensions facility 3, still pop_count_long_with_ext3 is used");
6761 z_popcnt(r_dst, r_src, 8);
6762
6763 BLOCK_COMMENT("} pop_count_long_with_ext3");
6764 }
6765
6766 void MacroAssembler::pop_count_int_with_ext3(Register r_dst, Register r_src) {
6767 BLOCK_COMMENT("pop_count_int_with_ext3 {");
6768
6769 guarantee(VM_Version::has_MiscInstrExt3(),
6770 "this hardware doesn't support miscellaneous-instruction-extensions facility 3, still pop_count_long_with_ext3 is used");
6771 z_llgfr(r_dst, r_src);
6772 z_popcnt(r_dst, r_dst, 8);
6773
6774 BLOCK_COMMENT("} pop_count_int_with_ext3");
6775 }
6776
6777 void MacroAssembler::post_call_nop() {
6778 // Make inline again when loom is always enabled.
6779 if (!Continuations::enabled()) {
6780 return;
6781 }
6782 nop();
6783 // TODO:
6784 // 1. https://bugs.openjdk.org/browse/JDK-8300002
6785 // 2. https://bugs.openjdk.org/browse/JDK-8290965
6786 }
6787
6788 void MacroAssembler::push_cont_fastpath() {
6789 BLOCK_COMMENT("push_cont_fastpath {");
6790 if (!Continuations::enabled()) return;
6791 NearLabel done;
6792 z_clg(Z_SP, Address(Z_thread, JavaThread::cont_fastpath_offset()));
6793 z_brnh(done); // bcondNotHigh -> less than equal
6794 z_stg(Z_SP, Address(Z_thread, JavaThread::cont_fastpath_offset()));
6795 bind(done);
6796 BLOCK_COMMENT("} push_cont_fastpath");
6797 }
6798
6799 void MacroAssembler::pop_cont_fastpath() {
6800 BLOCK_COMMENT("pop_cont_fastpath {");
6801 if (!Continuations::enabled()) return;
6802 NearLabel done;
6803 z_clg(Z_SP, Address(Z_thread, JavaThread::cont_fastpath_offset()));
6804 z_brl(done);
6805 z_mvghi(Address(Z_thread, JavaThread::cont_fastpath_offset()), 0);
6806 bind(done);
6807 BLOCK_COMMENT("} pop_cont_fastpath");
6808 }
6809
6810 // LOAD HALFWORD IMMEDIATE ON CONDITION (32 <- 16)
6811 void MacroAssembler::load_on_condition_imm_32(Register dst, int64_t i2, branch_condition cc) {
6812 if (VM_Version::has_LoadStoreConditional2()) { // z_lochi works on z13 or above
6813 assert(Assembler::is_simm16(i2), "sanity");
6814 z_lochi(dst, i2, cc);
6815 } else {
6816 NearLabel done;
6817 z_brc(Assembler::inverse_condition(cc), done);
6818 z_lhi(dst, i2);
6819 bind(done);
6820 }
6821 }
6822
6823 // LOAD HALFWORD IMMEDIATE ON CONDITION (64 <- 16)
6824 void MacroAssembler::load_on_condition_imm_64(Register dst, int64_t i2, branch_condition cc) {
6825 if (VM_Version::has_LoadStoreConditional2()) { // z_locghi works on z13 or above
6826 assert(Assembler::is_simm16(i2), "sanity");
6827 z_locghi(dst, i2, cc);
6828 } else {
6829 NearLabel done;
6830 z_brc(Assembler::inverse_condition(cc), done);
6831 z_lghi(dst, i2);
6832 bind(done);
6833 }
6834 }
6835
6836 // Handle the receiver type profile update given the "recv" klass.
6837 //
6838 // Normally updates the ReceiverData (RD) that starts at "mdp" + "mdp_offset".
6839 // If there are no matching or claimable receiver entries in RD, updates
6840 // the polymorphic counter.
6841 //
6842 // This code expected to run by either the interpreter or JIT-ed code, without
6843 // extra synchronization. For safety, receiver cells are claimed atomically, which
6844 // avoids grossly misrepresenting the profiles under concurrent updates. For speed,
6845 // counter updates are not atomic.
6846 //
6847 void MacroAssembler::profile_receiver_type(Register recv, Register mdp, int mdp_offset, Register scratch) {
6848 Register r0_tmp = Z_R0_scratch; // cannot be used in address calculation
6849 assert_different_registers(recv, mdp, scratch, r0_tmp);
6850
6851 int base_receiver_offset = in_bytes(ReceiverTypeData::receiver_offset(0));
6852 int end_receiver_offset = in_bytes(ReceiverTypeData::receiver_offset(ReceiverTypeData::row_limit()));
6853 int poly_count_offset = in_bytes(CounterData::count_offset());
6854 int receiver_step = in_bytes(ReceiverTypeData::receiver_offset(1)) - base_receiver_offset;
6855 int receiver_to_count_step = in_bytes(ReceiverTypeData::receiver_count_offset(0)) - base_receiver_offset;
6856
6857 // Adjust for MDP offsets.
6858 base_receiver_offset += mdp_offset;
6859 end_receiver_offset += mdp_offset;
6860 poly_count_offset += mdp_offset;
6861
6862 #ifdef ASSERT
6863 // We are about to walk the MDO slots without asking for offsets.
6864 // Check that our math hits all the right spots.
6865 for (uint c = 0; c < ReceiverTypeData::row_limit(); c++) {
6866 int real_recv_offset = mdp_offset + in_bytes(ReceiverTypeData::receiver_offset(c));
6867 int real_count_offset = mdp_offset + in_bytes(ReceiverTypeData::receiver_count_offset(c));
6868 int offset = base_receiver_offset + receiver_step*c;
6869 int count_offset = offset + receiver_to_count_step;
6870 assert(offset == real_recv_offset, "receiver slot math");
6871 assert(count_offset == real_count_offset, "receiver count math");
6872 }
6873 int real_poly_count_offset = mdp_offset + in_bytes(CounterData::count_offset());
6874 assert(poly_count_offset == real_poly_count_offset, "poly counter math");
6875 #endif
6876
6877 // Corner case: no profile table. Increment poly counter and exit.
6878 if (ReceiverTypeData::row_limit() == 0) {
6879 add2mem_64(Address(mdp, poly_count_offset), DataLayout::counter_increment, scratch);
6880 return;
6881 }
6882
6883 NearLabel L_loop_search_receiver, L_loop_search_empty;
6884 NearLabel L_restart, L_found_recv, L_found_empty, L_count_update;
6885 Register offset = scratch;
6886
6887 // The code here recognizes three major cases:
6888 // A. Fastest: receiver found in the table
6889 // B. Fast: no receiver in the table, and the table is full
6890 // C. Slow: no receiver in the table, free slots in the table
6891 //
6892 // The case A performance is most important, as perfectly-behaved code would end up
6893 // there, especially with larger TypeProfileWidth. The case B performance is
6894 // important as well, this is where bulk of code would land for normally megamorphic
6895 // cases. The case C performance is not essential, its job is to deal with installation
6896 // races, we optimize for code density instead. Case C needs to make sure that receiver
6897 // rows are only claimed once. This makes sure we never overwrite a row for another
6898 // receiver and never duplicate the receivers in the list, making profile type-accurate.
6899 //
6900 // It is very tempting to handle these cases in a single loop, and claim the first slot
6901 // without checking the rest of the table. But, profiling code should tolerate free slots
6902 // in the table, as class unloading can clear them. After such cleanup, the receiver
6903 // we need might be _after_ the free slot. Therefore, we need to let at least full scan
6904 // to complete, before trying to install new slots. Splitting the code in several tight
6905 // loops also helpfully optimizes for cases A and B.
6906 //
6907 // This code is effectively:
6908 //
6909 // restart:
6910 // // Fastest: receiver is already installed
6911 // for (i = 0; i < receiver_count(); i++) {
6912 // if (receiver(i) == recv) goto found_recv(i);
6913 // }
6914 //
6915 // // Fast: no receiver, but profile is not full
6916 // for (i = 0; i < receiver_count(); i++) {
6917 // if (receiver(i) == null) goto found_null(i);
6918 // }
6919 // goto polymorphic
6920 //
6921 // // Slow: try to install receiver
6922 // found_null(i):
6923 // CAS(&receiver(i), null, recv);
6924 // goto restart
6925 //
6926 // polymorphic:
6927 // count++;
6928 // return
6929 //
6930 // found_recv(i):
6931 // *receiver_count(i)++
6932 //
6933
6934 bind(L_restart);
6935
6936 // Fastest: receiver is already installed
6937 load_const_optimized(offset, base_receiver_offset);
6938
6939 bind(L_loop_search_receiver);
6940 z_cg(recv, Address(mdp, offset));
6941 z_bre(L_found_recv);
6942 add2reg(offset, receiver_step);
6943 compare64_and_branch(offset, end_receiver_offset, bcondNotEqual, L_loop_search_receiver);
6944
6945 // Fast: no receiver, but profile is not full
6946 load_const_optimized(offset, base_receiver_offset);
6947
6948 bind(L_loop_search_empty);
6949 z_ltg(r0_tmp, Address(mdp, offset));
6950 z_brz(L_found_empty);
6951 add2reg(offset, receiver_step);
6952 compare64_and_branch(offset, end_receiver_offset, bcondNotEqual, L_loop_search_empty);
6953
6954 // Slow: Receiver is not found and table is full.
6955 // Increment polymorphic counter instead of receiver slot.
6956 load_const_optimized(offset, poly_count_offset);
6957 z_bru(L_count_update);
6958
6959 // Slowest: try to install receiver
6960 bind(L_found_empty);
6961
6962 {
6963 // Atomically swing receiver slot: null -> recv.
6964 // Use compare-and-swap to claim the slot.
6965 Register receiver_addr = offset;
6966 z_agr(receiver_addr, mdp); // receiver_addr = mdp + offset
6967
6968 // r0_tmp is used as expected value (0), recv is the new value
6969 z_lghi(r0_tmp, 0);
6970 z_csg(r0_tmp, recv, 0, receiver_addr);
6971 }
6972
6973 // CAS success means the slot now has the receiver we want. CAS failure means
6974 // something had claimed the slot concurrently: it can be the same receiver we want,
6975 // or something else. Since this is a slow path, we can optimize for code density,
6976 // and just restart the search from the beginning.
6977 z_bru(L_restart);
6978
6979 // Found a receiver, convert its slot offset to corresponding count offset.
6980 bind(L_found_recv);
6981 add2reg(offset, receiver_to_count_step);
6982
6983 // Finally, update the counter
6984 bind(L_count_update);
6985 z_agr(offset, mdp);
6986 add2mem_64(Address(offset), DataLayout::counter_increment, r0_tmp);
6987 }
6988
6989 // Unimplemented methods for inline types.
6990 int MacroAssembler::store_inline_type_fields_to_buf(ciInlineKlass* vk, bool from_interpreter) {
6991 Unimplemented();
6992 }
6993
6994 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[]) {
6995 Unimplemented();
6996 }
6997
6998 bool MacroAssembler::unpack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index,
6999 VMReg from, int& from_index, VMRegPair* to, int to_count, int& to_index,
7000 RegState reg_state[]) {
7001 Unimplemented();
7002 }
7003
7004 bool MacroAssembler::pack_inline_helper(const GrowableArray<SigEntry>* sig, int& sig_index, int vtarg_index,
7005 VMRegPair* from, int from_count, int& from_index, VMReg to,
7006 RegState reg_state[], Register val_array) {
7007 Unimplemented();
7008 }
7009
7010 int MacroAssembler::extend_stack_for_inline_args(int args_on_stack) {
7011 Unimplemented();
7012 }
7013
7014 VMReg MacroAssembler::spill_reg_for(VMReg reg) {
7015 Unimplemented();
7016 }