Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/asm/codeBuffer.cpp
32285 views
/*1* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "asm/codeBuffer.hpp"26#include "compiler/disassembler.hpp"27#include "memory/gcLocker.hpp"28#include "oops/methodData.hpp"29#include "oops/oop.inline.hpp"30#include "utilities/copy.hpp"31#include "utilities/xmlstream.hpp"3233// The structure of a CodeSection:34//35// _start -> +----------------+36// | machine code...|37// _end -> |----------------|38// | |39// | (empty) |40// | |41// | |42// +----------------+43// _limit -> | |44//45// _locs_start -> +----------------+46// |reloc records...|47// |----------------|48// _locs_end -> | |49// | |50// | (empty) |51// | |52// | |53// +----------------+54// _locs_limit -> | |55// The _end (resp. _limit) pointer refers to the first56// unused (resp. unallocated) byte.5758// The structure of the CodeBuffer while code is being accumulated:59//60// _total_start -> \61// _insts._start -> +----------------+62// | |63// | Code |64// | |65// _stubs._start -> |----------------|66// | |67// | Stubs | (also handlers for deopt/exception)68// | |69// _consts._start -> |----------------|70// | |71// | Constants |72// | |73// +----------------+74// + _total_size -> | |75//76// When the code and relocations are copied to the code cache,77// the empty parts of each section are removed, and everything78// is copied into contiguous locations.7980typedef CodeBuffer::csize_t csize_t; // file-local definition8182// External buffer, in a predefined CodeBlob.83// Important: The code_start must be taken exactly, and not realigned.84CodeBuffer::CodeBuffer(CodeBlob* blob) {85initialize_misc("static buffer");86initialize(blob->content_begin(), blob->content_size());87verify_section_allocation();88}8990void CodeBuffer::initialize(csize_t code_size, csize_t locs_size) {91// Compute maximal alignment.92int align = _insts.alignment();93// Always allow for empty slop around each section.94int slop = (int) CodeSection::end_slop();9596assert(blob() == NULL, "only once");97set_blob(BufferBlob::create(_name, code_size + (align+slop) * (SECT_LIMIT+1)));98if (blob() == NULL) {99// The assembler constructor will throw a fatal on an empty CodeBuffer.100return; // caller must test this101}102103// Set up various pointers into the blob.104initialize(_total_start, _total_size);105106assert((uintptr_t)insts_begin() % CodeEntryAlignment == 0, "instruction start not code entry aligned");107108pd_initialize();109110if (locs_size != 0) {111_insts.initialize_locs(locs_size / sizeof(relocInfo));112}113114verify_section_allocation();115}116117118CodeBuffer::~CodeBuffer() {119verify_section_allocation();120121// If we allocate our code buffer from the CodeCache122// via a BufferBlob, and it's not permanent, then123// free the BufferBlob.124// The rest of the memory will be freed when the ResourceObj125// is released.126for (CodeBuffer* cb = this; cb != NULL; cb = cb->before_expand()) {127// Previous incarnations of this buffer are held live, so that internal128// addresses constructed before expansions will not be confused.129cb->free_blob();130}131132// free any overflow storage133delete _overflow_arena;134135// Claim is that stack allocation ensures resources are cleaned up.136// This is resource clean up, let's hope that all were properly copied out.137free_strings();138139#ifdef ASSERT140// Save allocation type to execute assert in ~ResourceObj()141// which is called after this destructor.142assert(_default_oop_recorder.allocated_on_stack(), "should be embedded object");143ResourceObj::allocation_type at = _default_oop_recorder.get_allocation_type();144Copy::fill_to_bytes(this, sizeof(*this), badResourceValue);145ResourceObj::set_allocation_type((address)(&_default_oop_recorder), at);146#endif147}148149void CodeBuffer::initialize_oop_recorder(OopRecorder* r) {150assert(_oop_recorder == &_default_oop_recorder && _default_oop_recorder.is_unused(), "do this once");151DEBUG_ONLY(_default_oop_recorder.freeze()); // force unused OR to be frozen152_oop_recorder = r;153}154155void CodeBuffer::initialize_section_size(CodeSection* cs, csize_t size) {156assert(cs != &_insts, "insts is the memory provider, not the consumer");157csize_t slop = CodeSection::end_slop(); // margin between sections158int align = cs->alignment();159assert(is_power_of_2(align), "sanity");160address start = _insts._start;161address limit = _insts._limit;162address middle = limit - size;163middle -= (intptr_t)middle & (align-1); // align the division point downward164guarantee(middle - slop > start, "need enough space to divide up");165_insts._limit = middle - slop; // subtract desired space, plus slop166cs->initialize(middle, limit - middle);167assert(cs->start() == middle, "sanity");168assert(cs->limit() == limit, "sanity");169// give it some relocations to start with, if the main section has them170if (_insts.has_locs()) cs->initialize_locs(1);171}172173void CodeBuffer::freeze_section(CodeSection* cs) {174CodeSection* next_cs = (cs == consts())? NULL: code_section(cs->index()+1);175csize_t frozen_size = cs->size();176if (next_cs != NULL) {177frozen_size = next_cs->align_at_start(frozen_size);178}179address old_limit = cs->limit();180address new_limit = cs->start() + frozen_size;181relocInfo* old_locs_limit = cs->locs_limit();182relocInfo* new_locs_limit = cs->locs_end();183// Patch the limits.184cs->_limit = new_limit;185cs->_locs_limit = new_locs_limit;186cs->_frozen = true;187if (!next_cs->is_allocated() && !next_cs->is_frozen()) {188// Give remaining buffer space to the following section.189next_cs->initialize(new_limit, old_limit - new_limit);190next_cs->initialize_shared_locs(new_locs_limit,191old_locs_limit - new_locs_limit);192}193}194195void CodeBuffer::set_blob(BufferBlob* blob) {196_blob = blob;197if (blob != NULL) {198address start = blob->content_begin();199address end = blob->content_end();200// Round up the starting address.201int align = _insts.alignment();202start += (-(intptr_t)start) & (align-1);203_total_start = start;204_total_size = end - start;205} else {206#ifdef ASSERT207// Clean out dangling pointers.208_total_start = badAddress;209_consts._start = _consts._end = badAddress;210_insts._start = _insts._end = badAddress;211_stubs._start = _stubs._end = badAddress;212#endif //ASSERT213}214}215216void CodeBuffer::free_blob() {217if (_blob != NULL) {218BufferBlob::free(_blob);219set_blob(NULL);220}221}222223const char* CodeBuffer::code_section_name(int n) {224#ifdef PRODUCT225return NULL;226#else //PRODUCT227switch (n) {228case SECT_CONSTS: return "consts";229case SECT_INSTS: return "insts";230case SECT_STUBS: return "stubs";231default: return NULL;232}233#endif //PRODUCT234}235236int CodeBuffer::section_index_of(address addr) const {237for (int n = 0; n < (int)SECT_LIMIT; n++) {238const CodeSection* cs = code_section(n);239if (cs->allocates(addr)) return n;240}241return SECT_NONE;242}243244int CodeBuffer::locator(address addr) const {245for (int n = 0; n < (int)SECT_LIMIT; n++) {246const CodeSection* cs = code_section(n);247if (cs->allocates(addr)) {248return locator(addr - cs->start(), n);249}250}251return -1;252}253254address CodeBuffer::locator_address(int locator) const {255if (locator < 0) return NULL;256address start = code_section(locator_sect(locator))->start();257return start + locator_pos(locator);258}259260bool CodeBuffer::is_backward_branch(Label& L) {261return L.is_bound() && insts_end() <= locator_address(L.loc());262}263264address CodeBuffer::decode_begin() {265address begin = _insts.start();266if (_decode_begin != NULL && _decode_begin > begin)267begin = _decode_begin;268return begin;269}270271272GrowableArray<int>* CodeBuffer::create_patch_overflow() {273if (_overflow_arena == NULL) {274_overflow_arena = new (mtCode) Arena(mtCode);275}276return new (_overflow_arena) GrowableArray<int>(_overflow_arena, 8, 0, 0);277}278279280// Helper function for managing labels and their target addresses.281// Returns a sensible address, and if it is not the label's final282// address, notes the dependency (at 'branch_pc') on the label.283address CodeSection::target(Label& L, address branch_pc) {284if (L.is_bound()) {285int loc = L.loc();286if (index() == CodeBuffer::locator_sect(loc)) {287return start() + CodeBuffer::locator_pos(loc);288} else {289return outer()->locator_address(loc);290}291} else {292assert(allocates2(branch_pc), "sanity");293address base = start();294int patch_loc = CodeBuffer::locator(branch_pc - base, index());295L.add_patch_at(outer(), patch_loc);296297// Need to return a pc, doesn't matter what it is since it will be298// replaced during resolution later.299// Don't return NULL or badAddress, since branches shouldn't overflow.300// Don't return base either because that could overflow displacements301// for shorter branches. It will get checked when bound.302return branch_pc;303}304}305306void CodeSection::relocate(address at, RelocationHolder const& spec, int format) {307Relocation* reloc = spec.reloc();308relocInfo::relocType rtype = (relocInfo::relocType) reloc->type();309if (rtype == relocInfo::none) return;310311// The assertion below has been adjusted, to also work for312// relocation for fixup. Sometimes we want to put relocation313// information for the next instruction, since it will be patched314// with a call.315assert(start() <= at && at <= end()+1,316"cannot relocate data outside code boundaries");317318if (!has_locs()) {319// no space for relocation information provided => code cannot be320// relocated. Make sure that relocate is only called with rtypes321// that can be ignored for this kind of code.322assert(rtype == relocInfo::none ||323rtype == relocInfo::runtime_call_type ||324rtype == relocInfo::internal_word_type||325rtype == relocInfo::section_word_type ||326rtype == relocInfo::external_word_type,327"code needs relocation information");328// leave behind an indication that we attempted a relocation329DEBUG_ONLY(_locs_start = _locs_limit = (relocInfo*)badAddress);330return;331}332333// Advance the point, noting the offset we'll have to record.334csize_t offset = at - locs_point();335set_locs_point(at);336337// Test for a couple of overflow conditions; maybe expand the buffer.338relocInfo* end = locs_end();339relocInfo* req = end + relocInfo::length_limit;340// Check for (potential) overflow341if (req >= locs_limit() || offset >= relocInfo::offset_limit()) {342req += (uint)offset / (uint)relocInfo::offset_limit();343if (req >= locs_limit()) {344// Allocate or reallocate.345expand_locs(locs_count() + (req - end));346// reload pointer347end = locs_end();348}349}350351// If the offset is giant, emit filler relocs, of type 'none', but352// each carrying the largest possible offset, to advance the locs_point.353while (offset >= relocInfo::offset_limit()) {354assert(end < locs_limit(), "adjust previous paragraph of code");355*end++ = filler_relocInfo();356offset -= filler_relocInfo().addr_offset();357}358359// If it's a simple reloc with no data, we'll just write (rtype | offset).360(*end) = relocInfo(rtype, offset, format);361362// If it has data, insert the prefix, as (data_prefix_tag | data1), data2.363end->initialize(this, reloc);364}365366void CodeSection::initialize_locs(int locs_capacity) {367assert(_locs_start == NULL, "only one locs init step, please");368// Apply a priori lower limits to relocation size:369csize_t min_locs = MAX2(size() / 16, (csize_t)4);370if (locs_capacity < min_locs) locs_capacity = min_locs;371relocInfo* locs_start = NEW_RESOURCE_ARRAY(relocInfo, locs_capacity);372_locs_start = locs_start;373_locs_end = locs_start;374_locs_limit = locs_start + locs_capacity;375_locs_own = true;376}377378void CodeSection::initialize_shared_locs(relocInfo* buf, int length) {379assert(_locs_start == NULL, "do this before locs are allocated");380// Internal invariant: locs buf must be fully aligned.381// See copy_relocations_to() below.382while ((uintptr_t)buf % HeapWordSize != 0 && length > 0) {383++buf; --length;384}385if (length > 0) {386_locs_start = buf;387_locs_end = buf;388_locs_limit = buf + length;389_locs_own = false;390}391}392393void CodeSection::initialize_locs_from(const CodeSection* source_cs) {394int lcount = source_cs->locs_count();395if (lcount != 0) {396initialize_shared_locs(source_cs->locs_start(), lcount);397_locs_end = _locs_limit = _locs_start + lcount;398assert(is_allocated(), "must have copied code already");399set_locs_point(start() + source_cs->locs_point_off());400}401assert(this->locs_count() == source_cs->locs_count(), "sanity");402}403404void CodeSection::expand_locs(int new_capacity) {405if (_locs_start == NULL) {406initialize_locs(new_capacity);407return;408} else {409int old_count = locs_count();410int old_capacity = locs_capacity();411if (new_capacity < old_capacity * 2)412new_capacity = old_capacity * 2;413relocInfo* locs_start;414if (_locs_own) {415locs_start = REALLOC_RESOURCE_ARRAY(relocInfo, _locs_start, old_capacity, new_capacity);416} else {417locs_start = NEW_RESOURCE_ARRAY(relocInfo, new_capacity);418Copy::conjoint_jbytes(_locs_start, locs_start, old_capacity * sizeof(relocInfo));419_locs_own = true;420}421_locs_start = locs_start;422_locs_end = locs_start + old_count;423_locs_limit = locs_start + new_capacity;424}425}426427428/// Support for emitting the code to its final location.429/// The pattern is the same for all functions.430/// We iterate over all the sections, padding each to alignment.431432csize_t CodeBuffer::total_content_size() const {433csize_t size_so_far = 0;434for (int n = 0; n < (int)SECT_LIMIT; n++) {435const CodeSection* cs = code_section(n);436if (cs->is_empty()) continue; // skip trivial section437size_so_far = cs->align_at_start(size_so_far);438size_so_far += cs->size();439}440return size_so_far;441}442443void CodeBuffer::compute_final_layout(CodeBuffer* dest) const {444address buf = dest->_total_start;445csize_t buf_offset = 0;446assert(dest->_total_size >= total_content_size(), "must be big enough");447448{449// not sure why this is here, but why not...450int alignSize = MAX2((intx) sizeof(jdouble), CodeEntryAlignment);451assert( (dest->_total_start - _insts.start()) % alignSize == 0, "copy must preserve alignment");452}453454const CodeSection* prev_cs = NULL;455CodeSection* prev_dest_cs = NULL;456457for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {458// figure compact layout of each section459const CodeSection* cs = code_section(n);460csize_t csize = cs->size();461462CodeSection* dest_cs = dest->code_section(n);463if (!cs->is_empty()) {464// Compute initial padding; assign it to the previous non-empty guy.465// Cf. figure_expanded_capacities.466csize_t padding = cs->align_at_start(buf_offset) - buf_offset;467if (padding != 0) {468buf_offset += padding;469assert(prev_dest_cs != NULL, "sanity");470prev_dest_cs->_limit += padding;471}472#ifdef ASSERT473if (prev_cs != NULL && prev_cs->is_frozen() && n < (SECT_LIMIT - 1)) {474// Make sure the ends still match up.475// This is important because a branch in a frozen section476// might target code in a following section, via a Label,477// and without a relocation record. See Label::patch_instructions.478address dest_start = buf+buf_offset;479csize_t start2start = cs->start() - prev_cs->start();480csize_t dest_start2start = dest_start - prev_dest_cs->start();481assert(start2start == dest_start2start, "cannot stretch frozen sect");482}483#endif //ASSERT484prev_dest_cs = dest_cs;485prev_cs = cs;486}487488debug_only(dest_cs->_start = NULL); // defeat double-initialization assert489dest_cs->initialize(buf+buf_offset, csize);490dest_cs->set_end(buf+buf_offset+csize);491assert(dest_cs->is_allocated(), "must always be allocated");492assert(cs->is_empty() == dest_cs->is_empty(), "sanity");493494buf_offset += csize;495}496497// Done calculating sections; did it come out to the right end?498assert(buf_offset == total_content_size(), "sanity");499dest->verify_section_allocation();500}501502// Append an oop reference that keeps the class alive.503static void append_oop_references(GrowableArray<oop>* oops, Klass* k) {504oop cl = k->klass_holder();505if (cl != NULL && !oops->contains(cl)) {506oops->append(cl);507}508}509510void CodeBuffer::finalize_oop_references(methodHandle mh) {511No_Safepoint_Verifier nsv;512513GrowableArray<oop> oops;514515// Make sure that immediate metadata records something in the OopRecorder516for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {517// pull code out of each section518CodeSection* cs = code_section(n);519if (cs->is_empty()) continue; // skip trivial section520RelocIterator iter(cs);521while (iter.next()) {522if (iter.type() == relocInfo::metadata_type) {523metadata_Relocation* md = iter.metadata_reloc();524if (md->metadata_is_immediate()) {525Metadata* m = md->metadata_value();526if (oop_recorder()->is_real(m)) {527if (m->is_methodData()) {528m = ((MethodData*)m)->method();529}530if (m->is_method()) {531m = ((Method*)m)->method_holder();532}533if (m->is_klass()) {534append_oop_references(&oops, (Klass*)m);535} else {536// XXX This will currently occur for MDO which don't537// have a backpointer. This has to be fixed later.538m->print();539ShouldNotReachHere();540}541}542}543}544}545}546547if (!oop_recorder()->is_unused()) {548for (int i = 0; i < oop_recorder()->metadata_count(); i++) {549Metadata* m = oop_recorder()->metadata_at(i);550if (oop_recorder()->is_real(m)) {551if (m->is_methodData()) {552m = ((MethodData*)m)->method();553}554if (m->is_method()) {555m = ((Method*)m)->method_holder();556}557if (m->is_klass()) {558append_oop_references(&oops, (Klass*)m);559} else {560m->print();561ShouldNotReachHere();562}563}564}565566}567568// Add the class loader of Method* for the nmethod itself569append_oop_references(&oops, mh->method_holder());570571// Add any oops that we've found572Thread* thread = Thread::current();573for (int i = 0; i < oops.length(); i++) {574oop_recorder()->find_index((jobject)thread->handle_area()->allocate_handle(oops.at(i)));575}576}577578579580csize_t CodeBuffer::total_offset_of(CodeSection* cs) const {581csize_t size_so_far = 0;582for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {583const CodeSection* cur_cs = code_section(n);584if (!cur_cs->is_empty()) {585size_so_far = cur_cs->align_at_start(size_so_far);586}587if (cur_cs->index() == cs->index()) {588return size_so_far;589}590size_so_far += cur_cs->size();591}592ShouldNotReachHere();593return -1;594}595596csize_t CodeBuffer::total_relocation_size() const {597csize_t lsize = copy_relocations_to(NULL); // dry run only598csize_t csize = total_content_size();599csize_t total = RelocIterator::locs_and_index_size(csize, lsize);600return (csize_t) align_size_up(total, HeapWordSize);601}602603csize_t CodeBuffer::copy_relocations_to(CodeBlob* dest) const {604address buf = NULL;605csize_t buf_offset = 0;606csize_t buf_limit = 0;607if (dest != NULL) {608buf = (address)dest->relocation_begin();609buf_limit = (address)dest->relocation_end() - buf;610assert((uintptr_t)buf % HeapWordSize == 0, "buf must be fully aligned");611assert(buf_limit % HeapWordSize == 0, "buf must be evenly sized");612}613// if dest == NULL, this is just the sizing pass614615csize_t code_end_so_far = 0;616csize_t code_point_so_far = 0;617for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {618// pull relocs out of each section619const CodeSection* cs = code_section(n);620assert(!(cs->is_empty() && cs->locs_count() > 0), "sanity");621if (cs->is_empty()) continue; // skip trivial section622relocInfo* lstart = cs->locs_start();623relocInfo* lend = cs->locs_end();624csize_t lsize = (csize_t)( (address)lend - (address)lstart );625csize_t csize = cs->size();626code_end_so_far = cs->align_at_start(code_end_so_far);627628if (lsize > 0) {629// Figure out how to advance the combined relocation point630// first to the beginning of this section.631// We'll insert one or more filler relocs to span that gap.632// (Don't bother to improve this by editing the first reloc's offset.)633csize_t new_code_point = code_end_so_far;634for (csize_t jump;635code_point_so_far < new_code_point;636code_point_so_far += jump) {637jump = new_code_point - code_point_so_far;638relocInfo filler = filler_relocInfo();639if (jump >= filler.addr_offset()) {640jump = filler.addr_offset();641} else { // else shrink the filler to fit642filler = relocInfo(relocInfo::none, jump);643}644if (buf != NULL) {645assert(buf_offset + (csize_t)sizeof(filler) <= buf_limit, "filler in bounds");646*(relocInfo*)(buf+buf_offset) = filler;647}648buf_offset += sizeof(filler);649}650651// Update code point and end to skip past this section:652csize_t last_code_point = code_end_so_far + cs->locs_point_off();653assert(code_point_so_far <= last_code_point, "sanity");654code_point_so_far = last_code_point; // advance past this guy's relocs655}656code_end_so_far += csize; // advance past this guy's instructions too657658// Done with filler; emit the real relocations:659if (buf != NULL && lsize != 0) {660assert(buf_offset + lsize <= buf_limit, "target in bounds");661assert((uintptr_t)lstart % HeapWordSize == 0, "sane start");662if (buf_offset % HeapWordSize == 0) {663// Use wordwise copies if possible:664Copy::disjoint_words((HeapWord*)lstart,665(HeapWord*)(buf+buf_offset),666(lsize + HeapWordSize-1) / HeapWordSize);667} else {668Copy::conjoint_jbytes(lstart, buf+buf_offset, lsize);669}670}671buf_offset += lsize;672}673674// Align end of relocation info in target.675while (buf_offset % HeapWordSize != 0) {676if (buf != NULL) {677relocInfo padding = relocInfo(relocInfo::none, 0);678assert(buf_offset + (csize_t)sizeof(padding) <= buf_limit, "padding in bounds");679*(relocInfo*)(buf+buf_offset) = padding;680}681buf_offset += sizeof(relocInfo);682}683684assert(code_end_so_far == total_content_size(), "sanity");685686// Account for index:687if (buf != NULL) {688RelocIterator::create_index(dest->relocation_begin(),689buf_offset / sizeof(relocInfo),690dest->relocation_end());691}692693return buf_offset;694}695696void CodeBuffer::copy_code_to(CodeBlob* dest_blob) {697#ifndef PRODUCT698if (PrintNMethods && (WizardMode || Verbose)) {699tty->print("done with CodeBuffer:");700((CodeBuffer*)this)->print();701}702#endif //PRODUCT703704CodeBuffer dest(dest_blob);705assert(dest_blob->content_size() >= total_content_size(), "good sizing");706this->compute_final_layout(&dest);707relocate_code_to(&dest);708709// transfer strings and comments from buffer to blob710dest_blob->set_strings(_code_strings);711712// Done moving code bytes; were they the right size?713assert(round_to(dest.total_content_size(), oopSize) == dest_blob->content_size(), "sanity");714715// Flush generated code716ICache::invalidate_range(dest_blob->code_begin(), dest_blob->code_size());717}718719// Move all my code into another code buffer. Consult applicable720// relocs to repair embedded addresses. The layout in the destination721// CodeBuffer is different to the source CodeBuffer: the destination722// CodeBuffer gets the final layout (consts, insts, stubs in order of723// ascending address).724void CodeBuffer::relocate_code_to(CodeBuffer* dest) const {725address dest_end = dest->_total_start + dest->_total_size;726address dest_filled = NULL;727for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {728// pull code out of each section729const CodeSection* cs = code_section(n);730if (cs->is_empty()) continue; // skip trivial section731CodeSection* dest_cs = dest->code_section(n);732assert(cs->size() == dest_cs->size(), "sanity");733csize_t usize = dest_cs->size();734csize_t wsize = align_size_up(usize, HeapWordSize);735assert(dest_cs->start() + wsize <= dest_end, "no overflow");736// Copy the code as aligned machine words.737// This may also include an uninitialized partial word at the end.738Copy::disjoint_words((HeapWord*)cs->start(),739(HeapWord*)dest_cs->start(),740wsize / HeapWordSize);741742if (dest->blob() == NULL) {743// Destination is a final resting place, not just another buffer.744// Normalize uninitialized bytes in the final padding.745Copy::fill_to_bytes(dest_cs->end(), dest_cs->remaining(),746Assembler::code_fill_byte());747}748// Keep track of the highest filled address749dest_filled = MAX2(dest_filled, dest_cs->end() + dest_cs->remaining());750751assert(cs->locs_start() != (relocInfo*)badAddress,752"this section carries no reloc storage, but reloc was attempted");753754// Make the new code copy use the old copy's relocations:755dest_cs->initialize_locs_from(cs);756}757758// Do relocation after all sections are copied.759// This is necessary if the code uses constants in stubs, which are760// relocated when the corresponding instruction in the code (e.g., a761// call) is relocated. Stubs are placed behind the main code762// section, so that section has to be copied before relocating.763for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {764// pull code out of each section765const CodeSection* cs = code_section(n);766if (cs->is_empty()) continue; // skip trivial section767CodeSection* dest_cs = dest->code_section(n);768{ // Repair the pc relative information in the code after the move769RelocIterator iter(dest_cs);770while (iter.next()) {771iter.reloc()->fix_relocation_after_move(this, dest);772}773}774}775776if (dest->blob() == NULL && dest_filled != NULL) {777// Destination is a final resting place, not just another buffer.778// Normalize uninitialized bytes in the final padding.779Copy::fill_to_bytes(dest_filled, dest_end - dest_filled,780Assembler::code_fill_byte());781782}783}784785csize_t CodeBuffer::figure_expanded_capacities(CodeSection* which_cs,786csize_t amount,787csize_t* new_capacity) {788csize_t new_total_cap = 0;789790for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {791const CodeSection* sect = code_section(n);792793if (!sect->is_empty()) {794// Compute initial padding; assign it to the previous section,795// even if it's empty (e.g. consts section can be empty).796// Cf. compute_final_layout797csize_t padding = sect->align_at_start(new_total_cap) - new_total_cap;798if (padding != 0) {799new_total_cap += padding;800assert(n - 1 >= SECT_FIRST, "sanity");801new_capacity[n - 1] += padding;802}803}804805csize_t exp = sect->size(); // 100% increase806if ((uint)exp < 4*K) exp = 4*K; // minimum initial increase807if (sect == which_cs) {808if (exp < amount) exp = amount;809if (StressCodeBuffers) exp = amount; // expand only slightly810} else if (n == SECT_INSTS) {811// scale down inst increases to a more modest 25%812exp = 4*K + ((exp - 4*K) >> 2);813if (StressCodeBuffers) exp = amount / 2; // expand only slightly814} else if (sect->is_empty()) {815// do not grow an empty secondary section816exp = 0;817}818// Allow for inter-section slop:819exp += CodeSection::end_slop();820csize_t new_cap = sect->size() + exp;821if (new_cap < sect->capacity()) {822// No need to expand after all.823new_cap = sect->capacity();824}825new_capacity[n] = new_cap;826new_total_cap += new_cap;827}828829return new_total_cap;830}831832void CodeBuffer::expand(CodeSection* which_cs, csize_t amount) {833#ifndef PRODUCT834if (PrintNMethods && (WizardMode || Verbose)) {835tty->print("expanding CodeBuffer:");836this->print();837}838839if (StressCodeBuffers && blob() != NULL) {840static int expand_count = 0;841if (expand_count >= 0) expand_count += 1;842if (expand_count > 100 && is_power_of_2(expand_count)) {843tty->print_cr("StressCodeBuffers: have expanded %d times", expand_count);844// simulate an occasional allocation failure:845free_blob();846}847}848#endif //PRODUCT849850// Resizing must be allowed851{852if (blob() == NULL) return; // caller must check for blob == NULL853for (int n = 0; n < (int)SECT_LIMIT; n++) {854guarantee(!code_section(n)->is_frozen(), "resizing not allowed when frozen");855}856}857858// Figure new capacity for each section.859csize_t new_capacity[SECT_LIMIT];860csize_t new_total_cap861= figure_expanded_capacities(which_cs, amount, new_capacity);862863// Create a new (temporary) code buffer to hold all the new data864CodeBuffer cb(name(), new_total_cap, 0);865if (cb.blob() == NULL) {866// Failed to allocate in code cache.867free_blob();868return;869}870871// Create an old code buffer to remember which addresses used to go where.872// This will be useful when we do final assembly into the code cache,873// because we will need to know how to warp any internal address that874// has been created at any time in this CodeBuffer's past.875CodeBuffer* bxp = new CodeBuffer(_total_start, _total_size);876bxp->take_over_code_from(this); // remember the old undersized blob877DEBUG_ONLY(this->_blob = NULL); // silence a later assert878bxp->_before_expand = this->_before_expand;879this->_before_expand = bxp;880881// Give each section its required (expanded) capacity.882for (int n = (int)SECT_LIMIT-1; n >= SECT_FIRST; n--) {883CodeSection* cb_sect = cb.code_section(n);884CodeSection* this_sect = code_section(n);885if (new_capacity[n] == 0) continue; // already nulled out886if (n != SECT_INSTS) {887cb.initialize_section_size(cb_sect, new_capacity[n]);888}889assert(cb_sect->capacity() >= new_capacity[n], "big enough");890address cb_start = cb_sect->start();891cb_sect->set_end(cb_start + this_sect->size());892if (this_sect->mark() == NULL) {893cb_sect->clear_mark();894} else {895cb_sect->set_mark(cb_start + this_sect->mark_off());896}897}898899// Move all the code and relocations to the new blob:900relocate_code_to(&cb);901902// Copy the temporary code buffer into the current code buffer.903// Basically, do {*this = cb}, except for some control information.904this->take_over_code_from(&cb);905cb.set_blob(NULL);906907// Zap the old code buffer contents, to avoid mistakenly using them.908debug_only(Copy::fill_to_bytes(bxp->_total_start, bxp->_total_size,909badCodeHeapFreeVal));910911_decode_begin = NULL; // sanity912913// Make certain that the new sections are all snugly inside the new blob.914verify_section_allocation();915916#ifndef PRODUCT917if (PrintNMethods && (WizardMode || Verbose)) {918tty->print("expanded CodeBuffer:");919this->print();920}921#endif //PRODUCT922}923924void CodeBuffer::take_over_code_from(CodeBuffer* cb) {925// Must already have disposed of the old blob somehow.926assert(blob() == NULL, "must be empty");927#ifdef ASSERT928929#endif930// Take the new blob away from cb.931set_blob(cb->blob());932// Take over all the section pointers.933for (int n = 0; n < (int)SECT_LIMIT; n++) {934CodeSection* cb_sect = cb->code_section(n);935CodeSection* this_sect = code_section(n);936this_sect->take_over_code_from(cb_sect);937}938_overflow_arena = cb->_overflow_arena;939// Make sure the old cb won't try to use it or free it.940DEBUG_ONLY(cb->_blob = (BufferBlob*)badAddress);941}942943void CodeBuffer::verify_section_allocation() {944address tstart = _total_start;945if (tstart == badAddress) return; // smashed by set_blob(NULL)946address tend = tstart + _total_size;947if (_blob != NULL) {948949guarantee(tstart >= _blob->content_begin(), "sanity");950guarantee(tend <= _blob->content_end(), "sanity");951}952// Verify disjointness.953for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {954CodeSection* sect = code_section(n);955if (!sect->is_allocated() || sect->is_empty()) continue;956guarantee((intptr_t)sect->start() % sect->alignment() == 0957|| sect->is_empty() || _blob == NULL,958"start is aligned");959for (int m = (int) SECT_FIRST; m < (int) SECT_LIMIT; m++) {960CodeSection* other = code_section(m);961if (!other->is_allocated() || other == sect) continue;962guarantee(!other->contains(sect->start() ), "sanity");963// limit is an exclusive address and can be the start of another964// section.965guarantee(!other->contains(sect->limit() - 1), "sanity");966}967guarantee(sect->end() <= tend, "sanity");968guarantee(sect->end() <= sect->limit(), "sanity");969}970}971972void CodeBuffer::log_section_sizes(const char* name) {973if (xtty != NULL) {974// log info about buffer usage975xtty->print_cr("<blob name='%s' size='%d'>", name, _total_size);976for (int n = (int) CodeBuffer::SECT_FIRST; n < (int) CodeBuffer::SECT_LIMIT; n++) {977CodeSection* sect = code_section(n);978if (!sect->is_allocated() || sect->is_empty()) continue;979xtty->print_cr("<sect index='%d' size='" SIZE_FORMAT "' free='" SIZE_FORMAT "'/>",980n, sect->limit() - sect->start(), sect->limit() - sect->end());981}982xtty->print_cr("</blob>");983}984}985986#ifndef PRODUCT987988void CodeSection::dump() {989address ptr = start();990for (csize_t step; ptr < end(); ptr += step) {991step = end() - ptr;992if (step > jintSize * 4) step = jintSize * 4;993tty->print(INTPTR_FORMAT ": ", p2i(ptr));994while (step > 0) {995tty->print(" " PTR32_FORMAT, *(jint*)ptr);996ptr += jintSize;997}998tty->cr();999}1000}100110021003void CodeSection::decode() {1004Disassembler::decode(start(), end());1005}100610071008void CodeBuffer::block_comment(intptr_t offset, const char * comment) {1009_code_strings.add_comment(offset, comment);1010}10111012const char* CodeBuffer::code_string(const char* str) {1013return _code_strings.add_string(str);1014}10151016class CodeString: public CHeapObj<mtCode> {1017private:1018friend class CodeStrings;1019const char * _string;1020CodeString* _next;1021intptr_t _offset;10221023~CodeString() {1024assert(_next == NULL, "wrong interface for freeing list");1025os::free((void*)_string, mtCode);1026}10271028bool is_comment() const { return _offset >= 0; }10291030public:1031CodeString(const char * string, intptr_t offset = -1)1032: _next(NULL), _offset(offset) {1033_string = os::strdup(string, mtCode);1034}10351036const char * string() const { return _string; }1037intptr_t offset() const { assert(_offset >= 0, "offset for non comment?"); return _offset; }1038CodeString* next() const { return _next; }10391040void set_next(CodeString* next) { _next = next; }10411042CodeString* first_comment() {1043if (is_comment()) {1044return this;1045} else {1046return next_comment();1047}1048}1049CodeString* next_comment() const {1050CodeString* s = _next;1051while (s != NULL && !s->is_comment()) {1052s = s->_next;1053}1054return s;1055}1056};10571058CodeString* CodeStrings::find(intptr_t offset) const {1059CodeString* a = _strings->first_comment();1060while (a != NULL && a->offset() != offset) {1061a = a->next_comment();1062}1063return a;1064}10651066// Convenience for add_comment.1067CodeString* CodeStrings::find_last(intptr_t offset) const {1068CodeString* a = find(offset);1069if (a != NULL) {1070CodeString* c = NULL;1071while (((c = a->next_comment()) != NULL) && (c->offset() == offset)) {1072a = c;1073}1074}1075return a;1076}10771078void CodeStrings::add_comment(intptr_t offset, const char * comment) {1079check_valid();1080CodeString* c = new CodeString(comment, offset);1081CodeString* inspos = (_strings == NULL) ? NULL : find_last(offset);10821083if (inspos) {1084// insert after already existing comments with same offset1085c->set_next(inspos->next());1086inspos->set_next(c);1087} else {1088// no comments with such offset, yet. Insert before anything else.1089c->set_next(_strings);1090_strings = c;1091}1092}10931094void CodeStrings::assign(CodeStrings& other) {1095other.check_valid();1096// Cannot do following because CodeStrings constructor is not alway run!1097assert(is_null(), "Cannot assign onto non-empty CodeStrings");1098_strings = other._strings;1099other.set_null_and_invalidate();1100}11011102// Deep copy of CodeStrings for consistent memory management.1103// Only used for actual disassembly so this is cheaper than reference counting1104// for the "normal" fastdebug case.1105void CodeStrings::copy(CodeStrings& other) {1106other.check_valid();1107check_valid();1108assert(is_null(), "Cannot copy onto non-empty CodeStrings");1109CodeString* n = other._strings;1110CodeString** ps = &_strings;1111while (n != NULL) {1112*ps = new CodeString(n->string(),n->offset());1113ps = &((*ps)->_next);1114n = n->next();1115}1116}11171118void CodeStrings::print_block_comment(outputStream* stream, intptr_t offset) const {1119check_valid();1120if (_strings != NULL) {1121CodeString* c = find(offset);1122while (c && c->offset() == offset) {1123stream->bol();1124stream->print(" ;; ");1125stream->print_cr("%s", c->string());1126c = c->next_comment();1127}1128}1129}11301131// Also sets isNull()1132void CodeStrings::free() {1133CodeString* n = _strings;1134while (n) {1135// unlink the node from the list saving a pointer to the next1136CodeString* p = n->next();1137n->set_next(NULL);1138delete n;1139n = p;1140}1141set_null_and_invalidate();1142}11431144const char* CodeStrings::add_string(const char * string) {1145check_valid();1146CodeString* s = new CodeString(string);1147s->set_next(_strings);1148_strings = s;1149assert(s->string() != NULL, "should have a string");1150return s->string();1151}11521153void CodeBuffer::decode() {1154ttyLocker ttyl;1155Disassembler::decode(decode_begin(), insts_end());1156_decode_begin = insts_end();1157}115811591160void CodeBuffer::skip_decode() {1161_decode_begin = insts_end();1162}116311641165void CodeBuffer::decode_all() {1166ttyLocker ttyl;1167for (int n = 0; n < (int)SECT_LIMIT; n++) {1168// dump contents of each section1169CodeSection* cs = code_section(n);1170tty->print_cr("! %s:", code_section_name(n));1171if (cs != consts())1172cs->decode();1173else1174cs->dump();1175}1176}117711781179void CodeSection::print(const char* name) {1180csize_t locs_size = locs_end() - locs_start();1181tty->print_cr(" %7s.code = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d)%s",1182name, p2i(start()), p2i(end()), p2i(limit()), size(), capacity(),1183is_frozen()? " [frozen]": "");1184tty->print_cr(" %7s.locs = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d) point=%d",1185name, p2i(locs_start()), p2i(locs_end()), p2i(locs_limit()), locs_size, locs_capacity(), locs_point_off());1186if (PrintRelocations) {1187RelocIterator iter(this);1188iter.print();1189}1190}11911192void CodeBuffer::print() {1193if (this == NULL) {1194tty->print_cr("NULL CodeBuffer pointer");1195return;1196}11971198tty->print_cr("CodeBuffer:");1199for (int n = 0; n < (int)SECT_LIMIT; n++) {1200// print each section1201CodeSection* cs = code_section(n);1202cs->print(code_section_name(n));1203}1204}12051206#endif // PRODUCT120712081209