1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/codeBuffer.hpp"
  27 #include "asm/macroAssembler.hpp"
  28 #include "asm/macroAssembler.inline.hpp"
  29 #include "runtime/atomic.hpp"
  30 #include "runtime/icache.hpp"
  31 #include "runtime/os.hpp"
  32 #include "runtime/thread.hpp"
  33 #include "utilities/macros.hpp"
  34 #if INCLUDE_SHENANDOAHGC
  35 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
  36 #endif
  37 
  38 
  39 // Implementation of AbstractAssembler
  40 //
  41 // The AbstractAssembler is generating code into a CodeBuffer. To make code generation faster,
  42 // the assembler keeps a copy of the code buffers boundaries & modifies them when
  43 // emitting bytes rather than using the code buffers accessor functions all the time.
  44 // The code buffer is updated via set_code_end(...) after emitting a whole instruction.
  45 
  46 AbstractAssembler::AbstractAssembler(CodeBuffer* code) {
  47   if (code == NULL)  return;
  48   CodeSection* cs = code->insts();
  49   cs->clear_mark();   // new assembler kills old mark
  50   if (cs->start() == NULL)  {
  51     vm_exit_out_of_memory(0, OOM_MMAP_ERROR, "CodeCache: no room for %s", code->name());
  52   }
  53   _code_section = cs;
  54   _oop_recorder= code->oop_recorder();
  55   DEBUG_ONLY( _short_branch_delta = 0; )
  56 }
  57 
  58 void AbstractAssembler::set_code_section(CodeSection* cs) {
  59   assert(cs->outer() == code_section()->outer(), "sanity");
  60   assert(cs->is_allocated(), "need to pre-allocate this section");
  61   cs->clear_mark();  // new assembly into this section kills old mark
  62   _code_section = cs;
  63 }
  64 
  65 // Inform CodeBuffer that incoming code and relocation will be for stubs
  66 address AbstractAssembler::start_a_stub(int required_space) {
  67   CodeBuffer*  cb = code();
  68   CodeSection* cs = cb->stubs();
  69   assert(_code_section == cb->insts(), "not in insts?");
  70   if (cs->maybe_expand_to_ensure_remaining(required_space)
  71       && cb->blob() == NULL) {
  72     return NULL;
  73   }
  74   set_code_section(cs);
  75   return pc();
  76 }
  77 
  78 // Inform CodeBuffer that incoming code and relocation will be code
  79 // Should not be called if start_a_stub() returned NULL
  80 void AbstractAssembler::end_a_stub() {
  81   assert(_code_section == code()->stubs(), "not in stubs?");
  82   set_code_section(code()->insts());
  83 }
  84 
  85 // Inform CodeBuffer that incoming code and relocation will be for stubs
  86 address AbstractAssembler::start_a_const(int required_space, int required_align) {
  87   CodeBuffer*  cb = code();
  88   CodeSection* cs = cb->consts();
  89   assert(_code_section == cb->insts() || _code_section == cb->stubs(), "not in insts/stubs?");
  90   address end = cs->end();
  91   int pad = -(intptr_t)end & (required_align-1);
  92   if (cs->maybe_expand_to_ensure_remaining(pad + required_space)) {
  93     if (cb->blob() == NULL)  return NULL;
  94     end = cs->end();  // refresh pointer
  95   }
  96   if (pad > 0) {
  97     while (--pad >= 0) { *end++ = 0; }
  98     cs->set_end(end);
  99   }
 100   set_code_section(cs);
 101   return end;
 102 }
 103 
 104 // Inform CodeBuffer that incoming code and relocation will be code
 105 // in section cs (insts or stubs).
 106 void AbstractAssembler::end_a_const(CodeSection* cs) {
 107   assert(_code_section == code()->consts(), "not in consts?");
 108   set_code_section(cs);
 109 }
 110 
 111 void AbstractAssembler::flush() {
 112   ICache::invalidate_range(addr_at(0), offset());
 113 }
 114 
 115 void AbstractAssembler::bind(Label& L) {
 116   if (L.is_bound()) {
 117     // Assembler can bind a label more than once to the same place.
 118     guarantee(L.loc() == locator(), "attempt to redefine label");
 119     return;
 120   }
 121   L.bind_loc(locator());
 122   L.patch_instructions((MacroAssembler*)this);
 123 }
 124 
 125 void AbstractAssembler::generate_stack_overflow_check(int frame_size_in_bytes) {
 126   if (UseStackBanging) {
 127     // Each code entry causes one stack bang n pages down the stack where n
 128     // is configurable by StackShadowPages.  The setting depends on the maximum
 129     // depth of VM call stack or native before going back into java code,
 130     // since only java code can raise a stack overflow exception using the
 131     // stack banging mechanism.  The VM and native code does not detect stack
 132     // overflow.
 133     // The code in JavaCalls::call() checks that there is at least n pages
 134     // available, so all entry code needs to do is bang once for the end of
 135     // this shadow zone.
 136     // The entry code may need to bang additional pages if the framesize
 137     // is greater than a page.
 138 
 139     const int page_size = os::vm_page_size();
 140     int bang_end = (int)JavaThread::stack_shadow_zone_size();
 141 
 142     // This is how far the previous frame's stack banging extended.
 143     const int bang_end_safe = bang_end;
 144 
 145     if (frame_size_in_bytes > page_size) {
 146       bang_end += frame_size_in_bytes;
 147     }
 148 
 149     int bang_offset = bang_end_safe;
 150     while (bang_offset <= bang_end) {
 151       // Need at least one stack bang at end of shadow zone.
 152       bang_stack_with_offset(bang_offset);
 153       bang_offset += page_size;
 154     }
 155   } // end (UseStackBanging)
 156 }
 157 
 158 void Label::add_patch_at(CodeBuffer* cb, int branch_loc, const char* file, int line) {
 159   assert(_loc == -1, "Label is unbound");
 160   // Don't add patch locations during scratch emit.
 161   if (cb->insts()->scratch_emit()) { return; }
 162   if (_patch_index < PatchCacheSize) {
 163     _patches[_patch_index] = branch_loc;
 164 #ifdef ASSERT
 165     _lines[_patch_index] = line;
 166     _files[_patch_index] = file;
 167 #endif
 168   } else {
 169     if (_patch_overflow == NULL) {
 170       _patch_overflow = cb->create_patch_overflow();
 171     }
 172     _patch_overflow->push(branch_loc);
 173   }
 174   ++_patch_index;
 175 }
 176 
 177 void Label::patch_instructions(MacroAssembler* masm) {
 178   assert(is_bound(), "Label is bound");
 179   CodeBuffer* cb = masm->code();
 180   int target_sect = CodeBuffer::locator_sect(loc());
 181   address target = cb->locator_address(loc());
 182   while (_patch_index > 0) {
 183     --_patch_index;
 184     int branch_loc;
 185     int line = 0;
 186     const char* file = NULL;
 187     if (_patch_index >= PatchCacheSize) {
 188       branch_loc = _patch_overflow->pop();
 189     } else {
 190       branch_loc = _patches[_patch_index];
 191 #ifdef ASSERT
 192       line = _lines[_patch_index];
 193       file = _files[_patch_index];
 194 #endif
 195     }
 196     int branch_sect = CodeBuffer::locator_sect(branch_loc);
 197     address branch = cb->locator_address(branch_loc);
 198     if (branch_sect == CodeBuffer::SECT_CONSTS) {
 199       // The thing to patch is a constant word.
 200       *(address*)branch = target;
 201       continue;
 202     }
 203 
 204 #ifdef ASSERT
 205     // Cross-section branches only work if the
 206     // intermediate section boundaries are frozen.
 207     if (target_sect != branch_sect) {
 208       for (int n = MIN2(target_sect, branch_sect),
 209                nlimit = (target_sect + branch_sect) - n;
 210            n < nlimit; n++) {
 211         CodeSection* cs = cb->code_section(n);
 212         assert(cs->is_frozen(), "cross-section branch needs stable offsets");
 213       }
 214     }
 215 #endif //ASSERT
 216 
 217     // Push the target offset into the branch instruction.
 218     masm->pd_patch_instruction(branch, target, file, line);
 219   }
 220 }
 221 
 222 struct DelayedConstant {
 223   typedef void (*value_fn_t)();
 224   BasicType type;
 225   intptr_t value;
 226   value_fn_t value_fn;
 227   // This limit of 20 is generous for initial uses.
 228   // The limit needs to be large enough to store the field offsets
 229   // into classes which do not have statically fixed layouts.
 230   // (Initial use is for method handle object offsets.)
 231   // Look for uses of "delayed_value" in the source code
 232   // and make sure this number is generous enough to handle all of them.
 233   enum { DC_LIMIT = 20 };
 234   static DelayedConstant delayed_constants[DC_LIMIT];
 235   static DelayedConstant* add(BasicType type, value_fn_t value_fn);
 236   bool match(BasicType t, value_fn_t cfn) {
 237     return type == t && value_fn == cfn;
 238   }
 239   static void update_all();
 240 };
 241 
 242 DelayedConstant DelayedConstant::delayed_constants[DC_LIMIT];
 243 // Default C structure initialization rules have the following effect here:
 244 // = { { (BasicType)0, (intptr_t)NULL }, ... };
 245 
 246 DelayedConstant* DelayedConstant::add(BasicType type,
 247                                       DelayedConstant::value_fn_t cfn) {
 248   for (int i = 0; i < DC_LIMIT; i++) {
 249     DelayedConstant* dcon = &delayed_constants[i];
 250     if (dcon->match(type, cfn))
 251       return dcon;
 252     if (dcon->value_fn == NULL) {
 253         dcon->value_fn = cfn;
 254         dcon->type = type;
 255         return dcon;
 256     }
 257   }
 258   // If this assert is hit (in pre-integration testing!) then re-evaluate
 259   // the comment on the definition of DC_LIMIT.
 260   guarantee(false, "too many delayed constants");
 261   return NULL;
 262 }
 263 
 264 void DelayedConstant::update_all() {
 265   for (int i = 0; i < DC_LIMIT; i++) {
 266     DelayedConstant* dcon = &delayed_constants[i];
 267     if (dcon->value_fn != NULL && dcon->value == 0) {
 268       typedef int     (*int_fn_t)();
 269       typedef address (*address_fn_t)();
 270       switch (dcon->type) {
 271       case T_INT:     dcon->value = (intptr_t) ((int_fn_t)    dcon->value_fn)(); break;
 272       case T_ADDRESS: dcon->value = (intptr_t) ((address_fn_t)dcon->value_fn)(); break;
 273       default:        break;
 274       }
 275     }
 276   }
 277 }
 278 
 279 RegisterOrConstant AbstractAssembler::delayed_value(int(*value_fn)(), Register tmp, int offset) {
 280   intptr_t val = (intptr_t) (*value_fn)();
 281   if (val != 0)  return val + offset;
 282   return delayed_value_impl(delayed_value_addr(value_fn), tmp, offset);
 283 }
 284 RegisterOrConstant AbstractAssembler::delayed_value(address(*value_fn)(), Register tmp, int offset) {
 285   intptr_t val = (intptr_t) (*value_fn)();
 286   if (val != 0)  return val + offset;
 287   return delayed_value_impl(delayed_value_addr(value_fn), tmp, offset);
 288 }
 289 intptr_t* AbstractAssembler::delayed_value_addr(int(*value_fn)()) {
 290   DelayedConstant* dcon = DelayedConstant::add(T_INT, (DelayedConstant::value_fn_t) value_fn);
 291   return &dcon->value;
 292 }
 293 intptr_t* AbstractAssembler::delayed_value_addr(address(*value_fn)()) {
 294   DelayedConstant* dcon = DelayedConstant::add(T_ADDRESS, (DelayedConstant::value_fn_t) value_fn);
 295   return &dcon->value;
 296 }
 297 void AbstractAssembler::update_delayed_values() {
 298   DelayedConstant::update_all();
 299 }
 300 
 301 void AbstractAssembler::block_comment(const char* comment) {
 302   if (sect() == CodeBuffer::SECT_INSTS) {
 303     code_section()->outer()->block_comment(offset(), comment);
 304   }
 305 }
 306 
 307 const char* AbstractAssembler::code_string(const char* str) {
 308   if (sect() == CodeBuffer::SECT_INSTS || sect() == CodeBuffer::SECT_STUBS) {
 309     return code_section()->outer()->code_string(str);
 310   }
 311   return NULL;
 312 }
 313 
 314 bool MacroAssembler::needs_explicit_null_check(intptr_t offset) {
 315   // Exception handler checks the nmethod's implicit null checks table
 316   // only when this method returns false.
 317 #ifdef AARCH64
 318   // AArch64 addresses passed from the signal handler may have
 319   // their top 8 bits zeroed. That affects the case where
 320   // Shenandoah tries to load a Brooks pointer via a null oop.
 321   const uintptr_t address_bits = (uintptr_t)0xfffffffffffful;
 322 #else
 323   const uintptr_t address_bits = ~(uintptr_t)0;
 324 #endif
 325 #ifdef _LP64
 326   if (UseCompressedOops && Universe::narrow_oop_base() != NULL) {
 327     assert (Universe::heap() != NULL, "java heap should be initialized");
 328     // The first page after heap_base is unmapped and
 329     // the 'offset' is equal to [heap_base + offset] for
 330     // narrow oop implicit null checks.
 331     uintptr_t base = (uintptr_t)Universe::narrow_oop_base();
 332     int adj = 0;
 333 #if INCLUDE_SHENANDOAHGC
 334     if (UseShenandoahGC) {
 335       adj = ShenandoahBrooksPointer::byte_offset();
 336       assert(adj < 0, "no need for positive adjustments");
 337     }
 338 #endif
 339     if ((uintptr_t)((offset - adj) & address_bits) >= base) {
 340       // Normalize offset for the next check.
 341       offset = (intptr_t)(pointer_delta((void*)offset, (void*)base, 1));
 342     }
 343   }
 344 #endif
 345 
 346 #if INCLUDE_SHENANDOAHGC
 347   if (UseShenandoahGC && ((offset & address_bits) == (ShenandoahBrooksPointer::byte_offset() & address_bits))) {
 348     return false;
 349   }
 350 #endif
 351 
 352   return offset < 0 || os::vm_page_size() <= offset;
 353 }