virtual bool _onStart() {
        xa=0, ya=0, za=0;
        gc=0;

        Info() << "Initializing I2C";
        if (i2c.openDevice("/dev/i2c-1") < 0) {
            Error() << "Unable to open i2c device";
            return false;
        }

        Info() << "Initializing sensors";
        if (l3gd20h.initialize() < 0) {
            Error() << "Unable to initialize gyroscope";
            return 255;
        }

        l3gd20h.onData = [&](float x, float y, float z) {
            xa += x; ya += y; za +=z;
            gc++;
        };

        if (l3gd20h.start(L3GD20H_RATE_OCTA) < 0) {
            Error() << "Unable to start gyroscope data colection";
            return 255;
        }

        Info() << "Initializing timers";
        stats_timer.onTimeout = [&]() {
            float epoll_mono, callback_mono, epoll_cpu, callback_cpu;
            _event_poller->getTimings(epoll_mono, callback_mono, epoll_cpu, callback_cpu);
            Info() << "Real Time: epoll" << epoll_mono << "callbacks" << callback_mono
                   << "ratio" << roundTo(epoll_mono / (epoll_mono + callback_mono) * 100, 0.1) << "%"
                   << "/" << roundTo(callback_mono / (epoll_mono + callback_mono) * 100, 0.1) << "%";
            Info() << "CPU Time: epoll" << epoll_cpu << "callbacks" << callback_cpu
                   << "ratio" << roundTo(epoll_cpu / (epoll_cpu + callback_cpu) * 100, 0.1) << "%"
                   << "/" << roundTo(callback_cpu / (epoll_cpu + callback_cpu) * 100, 0.1) << "%";
        };
        stats_timer.start(5000);

        l3gd20h_timer.onTimeout = [&]() {
            Info() << "Gyroscope XYZ" << xa / gc << ya / gc << za / gc
                   << "samples: " << gc;
            xa = ya = za = 0;
            gc = 0;
        };
        l3gd20h_timer.start(1000);

        return Application::_onStart();
    }
vector<ERL_NIF_TERM> LiberationCoding::doEncode(ERL_NIF_TERM dataBin) {
    int *bitmatrix = liberation_coding_bitmatrix(k, w);
    int **smart = jerasure_smart_bitmatrix_to_schedule(k, m, w, bitmatrix);

    char* dataBlocks[k];
    char* codeBlocks[m];

    ErlNifBinary data;
    enif_inspect_binary(env, dataBin, &data);

    size_t dataSize = data.size;
    size_t blockSize = roundTo((roundTo(dataSize, k*w) / (k*w)), 16) * w;

    size_t offset = 0;
    size_t remain = dataSize;
    int filled = 0;
    while(remain >= blockSize) {
        dataBlocks[filled] = (char*)data.data + offset;
        offset += blockSize;
        remain -= blockSize;
        filled++;
    }
    ErlNifBinary tmp;
    enif_alloc_binary((k + m - filled) * blockSize + 16, &tmp);
    size_t align = (((size_t)data.data & 0x0f) - ((size_t)tmp.data & 0x0f) + 16) & 0x0f;
    char* alignedHead = (char*)tmp.data + align;
    memcpy(alignedHead, data.data + filled * blockSize, dataSize - filled * blockSize);
    offset = 0;
    for(int i = filled; i < k + m; ++i, offset += blockSize) {
        (i < k) ? dataBlocks[i] = alignedHead + offset:
            codeBlocks[i - k] = alignedHead + offset;
    }

    jerasure_schedule_encode(k, m, w, smart, dataBlocks, codeBlocks, blockSize, blockSize / w);

    vector<ERL_NIF_TERM> blockList;
    for(int i = 0; i < filled; ++i) {
        blockList.push_back(enif_make_sub_binary(env, dataBin, i * blockSize, blockSize));
    }
    ERL_NIF_TERM tmpBin = enif_make_binary(env, &tmp);
    offset = 0;
    for(int i = filled; i < k + m; ++i, offset += blockSize) {
        blockList.push_back(enif_make_sub_binary(env, tmpBin, offset + align, blockSize));
    }

    jerasure_free_schedule(smart);
    free(bitmatrix);
    return blockList;
}
bool KinematicsSolver::solveTranscendal(double a, double b, double c,
		double* theta) {
	/*
	 * Solution for Transcendal Eqn
	 * aCos(x) + bSin(x) = c;
	 */

	if (DBL_EQ(a, 0) && !DBL_EQ(b, 0) ) {
		// then Sin(x) = c/b;
		theta[0] = asin(c/b);
		theta[1] = M_PI - theta[0];

		return true; // solved!
	}

	if (DBL_EQ(b, 0) && !DBL_EQ(a, 0) ) {
		// then Cos(x) = c/a;
		theta[0] = acos(c/a);
		theta[1] = -theta[0];

		return true; // solved!
	}

	double denom = roundTo(a + c, 0.0);
	double rootTerm = roundTo(pow(b, 2) + pow(a, 2) - pow(c, 2) , 0);

	// TODO: Check for denom == 0 or rootTerm < 0 first???
	// check for a + c = 0;
	if (DBL_EQ(denom, 0) ) {
		theta[0] = M_PI; //u1 and u2 will be +180. -180 resp
		theta[1] = -M_PI;

		return true; // solved! :)
	}

	if (rootTerm < 0) {
		//cout<<"Error!: Solution did not converge" << endl;
		return false; // solution is imaginary and hence does not converge :(
	}

	rootTerm = sqrt(rootTerm);

	//distinct solutions possible

	theta[0] = 2 * atan( (b + rootTerm ) / denom);
	theta[1] = 2 * atan( (b - rootTerm ) / denom);

	return true; // solved!
}
Exemple #4
0
void MonitorBar::calculateVMRegion(int32 startAddr, int32 size, 
                       fint& in_core_percentage, fint& oldlen) {
  int32 pagesize = OS::get_page_size();
  int32 start    = startAddr & ~(pagesize - 1);
  int32 end      = roundTo(startAddr + size, pagesize);
  int32 npages   = (end - start) / pagesize;
# define PSIZE 4096
  static char m[PSIZE]; // shouldn't use (m)alloc - in int handler!
  int32 incore   = 0;

  if (npages != 0) {
    int32 remaining = npages;
    while (start < end) {
      int32 len = end - start;  // len = size of area in bytes
      int32 n = remaining;              // n = size of area in pages
      if (len > PSIZE * pagesize) {
        len = PSIZE * pagesize;
        n   = PSIZE;
      }
      if (OS::min_core((caddr_t)start, len, m)) {
        perror("monitor: OS::min_core failed! ");
      } else {
        for (int32 i = 0; i < n; i++) {
          if (m[i] & 1) incore++;
        }
      }
      start  += len;
      remaining -= n;
    }
    fint percent = (100 * incore + npages / 2) / npages;
    if (in_core_percentage != percent) oldlen = -1;  // time to update
    in_core_percentage = percent;
  }
# undef PSIZE
}
Exemple #5
0
nmethod* nmethod::new_nmethod(AbstractCompiler* c, bool generateDebugCode) {
  // This grossness is brought to you by the great way in which C++
  // handles non-standard allocation...
  Assembler* instsA = c->instructions();
  iLen  = roundTo(instsA->instsEnd - instsA->instsStart, oopSize);
  ilLen = (char*) instsA->locsEnd - (char*) instsA->locsStart;

  sLen = c->scopeDescRecorder()->size();

  depsStart = c->L->deps->start();
  depsEndArg = c->L->deps->end();
  dLen = (char*) depsEndArg - (char*) depsStart;

  // This assertion is tempting, but zombie nmethods created in the conversion
  // break it because they are obsolete.
  // A dependency from the method to the nmethod would be cleaner, but
  // would take more space -- dmu 7/39
  //  
  //  assert (      dLen > 0
  //            ||  c->L->selector == VMString[DO_IT],
  //          "all nmethods must have some dependencies");
  
  nmethod* nm = new nmethod(c, generateDebugCode);
  Memory->code->used_per_compiler[c->nmName()] += nm->size();
  return nm;
}
oop doubleByteArrayKlass::allocateObjectSize(int size, bool permit_scavenge, bool tenured) {
  klassOop k        = as_klassOop();
  int      ni_size  = non_indexable_size();
  int      obj_size = ni_size + 1 + roundTo(size * 2, oopSize) / oopSize;
  // allocate
  oop* result = tenured ?
    Universe::allocate_tenured(obj_size, permit_scavenge) :
    Universe::allocate(obj_size, (memOop*)&k, permit_scavenge);
  if (result == NULL) return NULL;
  doubleByteArrayOop obj = as_doubleByteArrayOop(result);
  // header
  memOop(obj)->initialize_header(true, k);
  // instance variables
  memOop(obj)->initialize_body(memOopDesc::header_size(), ni_size);
  // indexables
  oop* base = (oop*) obj->addr();
  oop* end  = base + obj_size;
  // %optimized 'obj->set_length(size)'
  base[ni_size] = as_smiOop(size);
  // %optimized 'for (int index = 1; index <= size; index++)
  //               obj->doubleByte_at_put(index, 0)'
  base = &base[ni_size+1];
  while (base < end) *base++ = (oop) 0;
  return obj;
}
PRIM_DECL_2(doubleByteArrayPrimitives::allocateSize, oop receiver, oop argument) {
  PROLOGUE_2("allocateSize", receiver, argument)
  assert(receiver->is_klass() && klassOop(receiver)->klass_part()->oop_is_doubleByteArray(),
         "receiver must double byte array class");
  if (!argument->is_smi())
    markSymbol(vmSymbols::first_argument_has_wrong_type());

  if (smiOop(argument)->value() < 0)
    return markSymbol(vmSymbols::negative_size());

  klassOop k        = klassOop(receiver);
  int      ni_size  = k->klass_part()->non_indexable_size();
  int      obj_size = ni_size + 1 + roundTo(smiOop(argument)->value() * 2, oopSize) / oopSize;
  // allocate
  doubleByteArrayOop obj = as_doubleByteArrayOop(Universe::allocate(obj_size, (memOop*)&k));
  // header
  memOop(obj)->initialize_header(true, k);
  // instance variables
  memOop(obj)->initialize_body(memOopDesc::header_size(), ni_size);
  // indexables
  oop* base = (oop*) obj->addr();
  oop* end  = base + obj_size;
  // %optimized 'obj->set_length(size)'
  base[ni_size] = argument;
  // %optimized 'for (int index = 1; index <= size; index++)
  //               obj->doubleByte_at_put(index, 0)'
  base = &base[ni_size+1];
  while (base < end) *base++ = (oop) 0;
  return obj;
}
/**
 * record audio from the Androids input channel, this stores only the incoming audio
 * not the remaining audio processed / generated by the engine
 *
 * aRecording        {bool} toggles the recording state
 * aMaxBuffers        {int} the total recorded buffer size to store in memory
 *                          before writing the recorded contents as .WAV file into
 *                          the given output directory.
 * aOutputDirectory {char*} name of the folder to write each snippet into
 */
void SequencerController::setRecordingFromDeviceState( bool aRecording, int aMaxBuffers, char* aOutputFile )
{
    // in case Sequencer was recording its output, halt recording of output
    if ( AudioEngine::recordOutputToDisk )
        setRecordingState( false, 0, ( char* ) "\0" );

    bool wasRecording              = AudioEngine::recordInputToDisk;
    AudioEngine::recordInputToDisk = aRecording;

    if ( AudioEngine::recordInputToDisk )
    {
        DiskWriter::prepare(
            std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ),
            AudioEngineProps::INPUT_CHANNELS
        );
    }
    else if ( wasRecording )
    {
        // recording halted, write currently recording snippet into file
        // and concatenate all recorded snippets into the requested output file name
        // we can do this synchronously as this method is called from outside the
        // rendering thread and thus won't lead to buffer under runs

        DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false );

        if ( DiskWriter::finish())
            Notifier::broadcast( Notifications::RECORDING_COMPLETED );
    }
}
PRIM_DECL_2(doubleValueArrayPrimitives::allocateSize, oop receiver, oop argument) {
  PROLOGUE_2("allocateSize", receiver, argument)
  assert(receiver->is_klass() && klassOop(receiver)->klass_part()->oop_is_doubleValueArray(),
         "receiver must double byte array class");
  if (!argument->is_smi())
    markSymbol(vmSymbols::first_argument_has_wrong_type());

  if (smiOop(argument)->value() < 0)
    return markSymbol(vmSymbols::negative_size());

  int length = smiOop(argument)->value();

  klassOop k        = klassOop(receiver);
  int      ni_size  = k->klass_part()->non_indexable_size();
  int      obj_size = ni_size + 1 + roundTo(length * sizeof(double), oopSize) / oopSize;
  // allocate
  doubleValueArrayOop obj = as_doubleValueArrayOop(Universe::allocate(obj_size, (memOop*)&k));
  // header
  memOop(obj)->initialize_header(true, k);
  // instance variables
  memOop(obj)->initialize_body(memOopDesc::header_size(), ni_size);
  obj->set_length(length);
  for (int index = 1; index <= length; index++) {
    obj->double_at_put(index, 0.0);
  }
  return obj;
}
Exemple #10
0
void space::read_snapshot(FILE* snap, char *bottom, char *top)
{
   objs_bottom = (oop*)bottom;
      objs_top = objs_bottom + (old_objs_top - old_objs_bottom);
     bytes_top = (oop*)top;
  bytes_bottom = bytes_top - (old_bytes_top - old_bytes_bottom);

  if (objs_top >= bytes_bottom)
    snap_error("space too small to read in snapshot");
               
  if (page_aligned) {
    char    *objs_page_end = OS::idealized_page_end(   objs_top);
    char *bytes_page_start = OS::idealized_page_start(bytes_bottom);
    if (fseek(snap, roundTo(ftell(snap), idealized_page_size), SEEK_SET) < 0)
      snap_error("seek failed");
    if (bytes_page_start <= objs_page_end)           
      OS::Mmap(objs_bottom, bytes_top, snap);
    else {
      OS::Mmap(objs_bottom, objs_page_end, snap);
      OS::Mmap(bytes_page_start, bytes_top, snap);
    }
  } else {
    OS::FRead_mem_swap(objs_bottom, objs_top, snap);
    OS::FRead_mem(bytes_bottom, bytes_top, snap);
  }    
}
bool KinematicsSolver::solveTheta21(double t3, double F1) {
	//Let out T3

	double _f2 = DH_a3 * sin(t3) + DH_d4 * cos(t3);
	double F2 = roundTo(_f2, 0);

	/*
	 * Transcendal Equation 
	 * g3 = z = s2sin(alpha1)F1 + c2sin(alpha1)F2 
	 * F2 c2 + F1 s2 = z
	 * 
	 * here sin alpha1 = -1
	 */
	double* t2= new double[2];

	if (!solveTranscendal(F2, F1, -pos(3), t2)) {
		return false;
	}

	bool solved = false;
	if (checkJointValidity(t2[0], JL2)) {
		solved = solved || solveTheta1(t3, t2[0], F1, F2);
	}

	if (!sameAngles(t2)) {
		if (checkJointValidity(t2[1], JL2)) {
			solved = solved || solveTheta1(t3, t2[1], F1, F2);
		}
	}
	return solved;
}
bool KinematicsSolver::solveTheta1(double t3, double t2, double F1, double F2) {
	//cout << "T2: " << t2 << endl;
	try {
		double G1 = roundTo( (cos(t2) * F1 - sin(t2) * F2) + DH_a1, 0);
		//cout << endl << "G1 is " << G1;

		if(DBL_EQ(G1, 0)) {
			return solveTheta56(t3, t2, 0);
		}

		Matrix G(2, 2);
		G.Row(1) << G1 << 0;
		G.Row(2) << 0 << G1;

		ColumnVector p(2);
		p(1) = pos(1);
		p(2) = pos(2);

		ColumnVector tmp = G.i() * p;

		double __tmp1 = roundTo(tmp(1), 0);
		double __tmp2 = roundTo(tmp(2), 0);

		double t1 = atan2(__tmp2, __tmp1);

		//cout << "T1: " << t1 << endl;

		bool solved = false;

		if (checkJointValidity(t1, JL1)) {
			if(checkTheta123(t1, t2, t3)) {
				//cout<< "Thetas 123: " << t1 << " " << t2 << " " << t3 << endl;
				solved = solved || solveTheta56(t3, t2, t1);
			}
		}

		return solved;
	} catch (Exception e) {
		cout << e.what() << endl;
	}

	return false;
}
Exemple #13
0
char* OS::allocate_idealized_page_aligned(int32 &size, const char *name,
                                          caddr_t desiredAddress, 
                                          bool mustAllocate) {
  size= roundTo(size, idealized_page_size);
  assert(idealized_page_size % get_page_size() == 0, "page size mismatch");
  char* b = allocate_heap_aligned(desiredAddress, size, idealized_page_size,
                                    name, mustAllocate);
  if (b == NULL) size= 0;
  return b;
}
Exemple #14
0
string utils::printNumber(double number, double error) {
	ostringstream result;
	const short numberMagnitude = magnitude(number);
	const short errorMagnitude = magnitude(error);
	number = roundTo(number, pow(10, errorMagnitude - 1));
	error = roundTo(error, pow(10, errorMagnitude - 1));

	// Use scientific notation
	if (numberMagnitude > 4 || numberMagnitude < -3) {
		result << toString(number / pow(10, numberMagnitude), numberMagnitude - errorMagnitude + 2)
			<< "*10^" << numberMagnitude << " #pm "
			<< toString(error / pow(10, numberMagnitude), 2) << "*10^" << numberMagnitude;
	}
	// Use fixed notation
	else {
		result << toString(number, numberMagnitude - errorMagnitude + 2)
			<< " #pm " << toString(error, 2);
	}
	return result.str();
}
Exemple #15
0
  void MachineCache::flush_instruction_cache_range(void* s, void* e) {
    MakeDataExecutable(s, (char*)e - (char*)s);

    // Could make this more efficient by depending on cache characteristics,
    // e.g. I-cache line size.  Also, should be a nop on machines without
    // split I/D caches (everything up to SS-2).

    const fint cacheLineSize = 8; // a guess

    char* start = (char*) ((int)s & ~(cacheLineSize - 1));
    char* end   = (char*) roundTo((int)e, cacheLineSize);
    for ( ; start < end; start += cacheLineSize) {
      FlushInstruction(start);  // FLUSH inst flushes (at least) a doubleword
    }
  }
Exemple #16
0
void space::write_snapshot(FILE* file) {
  OS::set_access_before_writing_space(objs_bottom, objs_top, bytes_bottom, bytes_top);
  if (page_aligned) {
    char *objs_page_end=    OS::idealized_page_end(   objs_top);
    char *bytes_page_start= OS::idealized_page_start(bytes_bottom);
    fseek(file, roundTo(ftell(file), idealized_page_size), SEEK_SET);
    if (bytes_page_start <= objs_page_end)
      OS::FWrite_mem(objs_bottom, bytes_top, file);
    else {
      OS::FWrite_mem(objs_bottom, objs_page_end, file);
      OS::FWrite_mem(bytes_page_start, bytes_top, file);
    }
  } else {
    OS::FWrite_mem(objs_bottom, objs_top, file);
    OS::FWrite_mem(bytes_bottom, bytes_top, file);
  }
  OS::reset_access_after_writing_space(objs_bottom, objs_top, bytes_bottom, bytes_top);
}
Exemple #17
0
void Projector::saveXML(ofXml &xml) {
    // color
    xml.setAttribute("brightness", ofToString(roundTo(brightness, .001)));
    xml.setAttribute("contrast", ofToString(roundTo(contrast, .001)));
    xml.setAttribute("saturation", ofToString(roundTo(hue, .001)) +  "," + ofToString(roundTo(saturation, .001)) +  "," + ofToString(roundTo(lightness, .001))  );

    //camera
    xml.setAttribute("position", ofToString(roundTo(cameraPosition.x, .01)) +  "," + ofToString(roundTo(cameraPosition.y, .01)) +  "," + ofToString(roundTo(cameraPosition.z, .01)) );
    xml.setAttribute("orientation", ofToString(roundTo(cameraOrientation.x, .01)) +  "," + ofToString(roundTo(cameraOrientation.y, .01)) +  "," + ofToString(roundTo(cameraOrientation.z, .01)) );
    xml.setAttribute("fov", ofToString(roundTo(cameraFov, .01)));
    xml.setAttribute("offset", ofToString(roundTo(cameraOffset.x, .001)) +  "," + ofToString(roundTo(cameraOffset.y, .001)) );
    
    // plane
    plane.save(xml);
	curves.save(projectorStartingIndex);
    mask.save(projectorStartingIndex);    
}
oop byteArrayKlass::allocateObjectSize(int size) {
  klassOop k        = as_klassOop();
  int      ni_size  = non_indexable_size();
  int      obj_size = ni_size + 1 + roundTo(size, oopSize) / oopSize;
  // allocate
  byteArrayOop obj = as_byteArrayOop(Universe::allocate(obj_size, (memOop*)&k));
  // header
  memOop(obj)->initialize_header(true, k);
  // instance variables
  memOop(obj)->initialize_body(memOopDesc::header_size(), ni_size);
  // indexables
  oop* base = (oop*) obj->addr();
  oop* end  = base + obj_size;
  // %optimized 'obj->set_length(size)'
  base[ni_size] = as_smiOop(size);
  // %optimized 'for (int index = 1; index <= size; index++)
  //               obj->byte_at_put(index, '\000')'
  base = &base[ni_size+1];
  while (base < end) *base++ = (oop) 0;
  return obj;
}
std::vector<double> GenerateKernel(double sigma, int kernelSize, int sampleCount)
{
	int samplesPerBin = ceil(sampleCount / kernelSize);
	if(samplesPerBin % 2 == 0)
		++samplesPerBin;
	double weightSum = 0;
	int kernelLeft = -floor(kernelSize/2);

	std::vector<std::pair<double, double> > outsideSamplesLeft  = calcSamplesForRange(-5 * sigma, kernelLeft - 0.5, sigma, samplesPerBin);
	std::vector<std::pair<double, double> > outsideSamplesRight = calcSamplesForRange(-kernelLeft+0.5, 5 * sigma, sigma, samplesPerBin);

	std::vector<std::pair<std::vector<std::pair<double, double> >, double> > allSamples;
	allSamples.push_back(std::make_pair(outsideSamplesLeft, 0.0));

	for(int tap=0; tap<kernelSize; ++tap)
	{
		double left = kernelLeft - 0.5 + tap;

		std::vector<std::pair<double, double> > tapSamples = calcSamplesForRange(left, left+1, sigma, samplesPerBin);
		double tapWeight = integrateSimphson(tapSamples);
		allSamples.push_back(std::make_pair(tapSamples, tapWeight));
		weightSum += tapWeight;
	}

	allSamples.push_back(std::make_pair(outsideSamplesRight, 0.0));

	for(int i=0; i<allSamples.size(); ++i)
	{
		allSamples[i].second = roundTo(allSamples[i].second / weightSum, 6);
	}

	std::vector<double> weights;
	for(int i=1; i<allSamples.size()-1; ++i)
	{
		weights.push_back(allSamples[i].second);
	}
	return weights;
}
Exemple #20
0
void CodeGen::fixupFrame(RegisterState* s) {
  // window size adjustment
  assert(haveStackFrame, "should have stack frame");
  assert(is_end_of_enter(prologueAddr), "enter?");  

  // must include permanents and stack: local slots, blocks and stack
  _number_of_memory_locals                = s->stackDepth;  

  fint    min_space_to_reserve = s->stackDepth + s->argDepth + s->rcvrDepth + num_extra_locals_for_runtime;
  fint    min_space_from_incoming_rcvr_to_outgoing_rcvr = min_space_to_reserve + ircvr_offset /*pc, ebp*/;
  fint actual_space_from_incoming_rcvr_to_outgoing_rcvr = roundTo(min_space_from_incoming_rcvr_to_outgoing_rcvr, frame_word_alignment);
  fint actual_space_to_reserve = min_space_to_reserve 
                               + actual_space_from_incoming_rcvr_to_outgoing_rcvr
                                  - min_space_from_incoming_rcvr_to_outgoing_rcvr;
  frameSize = actual_space_from_incoming_rcvr_to_outgoing_rcvr;
  assert((frameSize & (frame_word_alignment - 1))  == 0, "alignment");
  set_space_reserved_by_enter_instruction(prologueAddr, actual_space_to_reserve);
  
  if (number_of_memory_locals()  >  sizeof(RegisterString) * BitsPerByte) {
    // must clear extra stack locations:
    Label patches(a.printing);
    a.saveExcursion( callPatchAddr );
    a.jmp(&patches);
    DefinedLabel return_from_patches(a.printing);
    assert(a.addr() == endCallPatchAddr, "???");
    a.endExcursion();
    
    a.Comment("zero locations not in mask()");
    patches.define();
    for ( fint i = sizeof(RegisterString) * BitsPerByte;  i < number_of_memory_locals();  ++i) {
      Location r;  int32 d;  OperandType t;
      reg_disp_type_of_loc(&r, &d, &t, StackLocation_for_index(i));
      a.movl(0, NumberOperand, r, d, t);
    }
    a.jmp(&return_from_patches);
  }
}
 // Return the oop size for a doubleValueArrayOop
 int object_size(int number_of_doubleValues) const {
   return   non_indexable_size() + 1
          + roundTo(number_of_doubleValues * sizeof(double), oopSize) / oopSize;
 }
Exemple #22
0
      ||   r == (char*)      &MakeOld_stub_returnPC;
}

fint volatile_register_sp_or_fp_offset(char* r) {
  return
           r == (char*)  &SendMessage_stub_returnPC  ?    SendMessage_stub_volatile_register_sp_offset
        :  r == (char*)&SendDIMessage_stub_returnPC  ?  SendDIMessage_stub_volatile_register_sp_offset
        :  r == (char*)    &Recompile_stub_returnPC  ?      Recompile_stub_volatile_register_sp_offset
        :  r == (char*)      &MakeOld_stub_returnPC  ?        MakeOld_stub_volatile_register_sp_offset
        :  r == (char*)&SaveSelfNonVolRegs_returnPC  ?  SaveSelfNonVolRegs_volatile_register_fp_offset
        :  0;
}

 
// Duplicated in runtime_asm_gcc.s:
fint ReturnTrap_frame_size = roundTo(linkage_area_size + HandleReturnTrap_arg_count + NumLocalNonVolRegisters, frame_word_alignment);

// Not implemented on PPC:
char* DIRecompile_stub_returnPC = NULL;

oop failure_oop_for_restarting_uncommon_prim() {
  assert(SaveOutgoingArgumentsOfPatchedFrames, "PPC needs this");
  warning("untested: failure_oop_for_restarting_uncommon_prim");
  return OutgoingArgsOfReturnTrapOrRecompileFrame->obj_at(0);
}


void fillRegisterValue(Location loc, oop b) {
  warning("untested");
  OutgoingArgsOfReturnTrapOrRecompileFrame->obj_at_put(loc - ReceiverReg, b);
}
Exemple #23
0
void
BDecimalSpinner::SetValueFromText()
{
	SetValue(roundTo(atof(TextView()->Text()), Precision()));
}
Exemple #24
0
  nmethod* SICompiler::compile() {
    EventMarker em("SIC-compiling %#lx %#lx", L->selector(), NULL);
    ShowCompileInMonitor sc(L->selector(), "SIC", recompilee != NULL);

    // cannot recompile uncommon branches in DI nmethods & top nmethod yet 
    FlagSetting fs2(SICDeferUncommonBranches,
                    SICDeferUncommonBranches &&
                    diLink == NULL && L->adeps->length() == 0 &&
                    L->selector() != VMString[DO_IT]);
    // don't use uncommon traps when recompiling because of trap
    useUncommonTraps = 
      SICDeferUncommonBranches && !currentProcess->isUncommon();
    
    // don't inline into doIt
    FlagSetting fs3(Inline, Inline && L->selector() != VMString[DO_IT]);

    # if TARGET_ARCH != I386_ARCH // no FastMapTest possible on I386
      // don't use fast map loads if this nmethod trapped a lot
      FlagSetting fs4(FastMapTest, FastMapTest &&
                      (recompilee == NULL ||
                      recompilee->flags.trapCount < MapLoadTrapLimit));
    # endif

    FlagSetting fs5(PrintCompilation, PrintCompilation || PrintSICCompilation);
    timer t;
    
    FlagSetting fs6(verifyOften, SICDebug || CheckAssertions);
    
    if(PrintCompilation || PrintLongCompilation ||
       PrintCompilationStatistics || VMSICLongProfiling) {
      t.start();
    }
    if (PrintCompilation || PrintSICCode) {
      lprintf("*SIC-%s%scompiling %s%s: (SICCompilationCount=%d)",
              currentProcess->isUncommon() ? "uncommon-" : "",
              recompilee ? "re" : "",
              sprintName( (methodMap*) method()->map(), L->selector()),
              sprintValueMethod( L->receiver ),
              (void*)SICCompilationCount);
    }

    topScope->genCode();
    
    buildBBs();
    if (verifyOften) bbIterator->verify(false); 
    
    bbIterator->eliminateUnreachableNodes(); // needed for removeUptoMerge to work

    // compute exposed blocks and up-level accessed vars
    bbIterator->computeExposedBlocks();
    bbIterator->computeUplevelAccesses();

    // make defs & uses and insert flush nodes for uplevel-accessed vars
    bbIterator->makeUses();

    // added verify here cause want to catch unreachable merge preds 
    // before elimination -- dmu
    if (verifyOften) bbIterator->verify(); 

    if (SICLocalCopyPropagate) {
      bbIterator->localCopyPropagate();
      if (verifyOften) bbIterator->verify(); 
    }
    if (SICGlobalCopyPropagate) {
      bbIterator->globalCopyPropagate();
      if (verifyOften) bbIterator->verify(); 
    }
    if (SICEliminateUnneededNodes) {
      bbIterator->eliminateUnneededResults();
      if (verifyOften) bbIterator->verify(); 
    }

    // do after CP to explot common type test source regs
    if (SICOptimizeTypeTests) {
      bbIterator->computeDominators();
      bbIterator->optimizeTypeTests();
      if (verifyOften) bbIterator->verify(); 
    }

    // allocate the temp (i.e. volatile) registers
    bbIterator->allocateTempRegisters();
    // allocate the callee-saved (i.e. non-volatile) registers
    SICAllocator* a = theAllocator;
    a->allocate(bbIterator->globals, topScope->incoming);
    stackLocCount = a->stackTemps;

    // make sure frame size is aligned properly
    int32 frame_size_so_far = frameSize();
    stackLocCount += roundTo(frame_size_so_far, frame_word_alignment) - frame_size_so_far;

    // compute the register masks for inline caches
    bbIterator->computeMasks(stackLocCount, nonRegisterArgCount());
    topScope->computeMasks(regStringToMask(topScope->incoming),
                           stackLocCount, nonRegisterArgCount());

    if (PrintSICCode) {
      print_code(false);
      lprintf("\n\n");
    }

    topScope->describe();    // must come before gen to set scopeInfo   
    genHelper = new SICGenHelper;
    bbIterator->gen();
    assert(theAssembler->verifyLabels(), "undefined labels");

    rec->generate();
    topScope->fixupBlocks();        // must be after rec->gen to know offsets
    if (vscopes) computeMarkers();  // ditto

    nmethod* nm = new_nmethod(this, false);

    if (theAssembler->lastBackpatch >= theAssembler->instsEnd)
      fatal("dangling branch");
    
    em.event.args[1] = nm;
    fint ms = IntervalTimer::dont_use_any_timer ? 0 : t.millisecs();
    if (PrintCompilation || PrintLongCompilation) {
      if (!PrintCompilation && PrintLongCompilation && ms >= MaxCompilePause) {
        lprintf("*SIC-%s%scompiling ",
               currentProcess->isUncommon() ? "uncommon-" : "",
               recompilee ? "re" : "");
        methodMap* mm = method() ? (methodMap*) method()->map() : NULL;
        printName(mm, L->selector());
        lprintf(": %#lx (%ld ms; level %ld)\n", nm, (void*)ms, (void*)nm->level());
      } else if (PrintCompilation) {
        lprintf(": %#lx (%ld ms; level %ld v%d)\n", (void*)nm, (void*)ms,
                (void*)nm->level(), (void*)nm->version());
      }
    }
    if (SICDebug && estimatedSize() > inlineLimit[NmInstrLimit]) {
      float rat = (float)estimatedSize() / (float)nm->instsLen();
      lprintf("*est. size = %ld, true size = %ld, ratio = %4.2f\n",
              (void*)estimatedSize(), (void*)nm->instsLen(),
              *(void**)&rat);
    }
    if (PrintCompilationStatistics) {
      static fint counter = 0;
      lprintf("\n*SIC-time= |%ld| ms; to/co/sc/lo/de= |%ld|%ld|%ld|%ld|%ld| %ld|%ld|%ld| %ld |", 
             (void*)ms, 
             (void*) (nm->instsLen() + nm->scopes->length() +
                      nm->locsLen() + nm->depsLen),
             (void*)nm->instsLen(), 
             (void*)nm->scopes->length(),
             (void*)nm->locsLen(), 
             (void*)nm->depsLen,
             (void*)BasicNode::currentID,
             (void*)bbIterator->bbCount,
             (void*)ncodes,
             (void*)counter++);
    }
#   if GENERATE_DEBUGGING_AIDS
      if (CheckAssertions) {
        //      nm->verify();
      }
#   endif
    return nm;
  }
Exemple #25
0
nmethod::nmethod(AbstractCompiler* c, bool generateDebugCode) {
  CHECK_VTBL_VALUE;
  _instsLen  = roundTo(iLen, oopSize);
  _locsLen   = ilLen;
  depsLen    = dLen;
  // backpointer is just before deps
  depsAddr   = (nmln*)     ((char*)dAddr + sizeof(nmethod*));

  *dBackLinkAddr() = this;
  
  // Copy the nmethodScopes scopeDescs generated by the ScopeDescRecorder
  // to the allocation area.
  c->scopeDescRecorder()->copyTo((VtblPtr_t*)sAddr, (int32)this);
  
  this->scopes = (nmethodScopes*) sAddr;

  oldCount = 0;
  flags.clear();
  flags.isDebug = generateDebugCode;
  setCompiler(c->name());
  flags.isUncommonRecompiled = currentProcess->isUncommon();
    
  verifiedOffset      = c->verifiedOffset();
  diCheckOffset       = c->diCheckOffset();

  frameCreationOffset = c->frameCreationOffset();
  
  rememberLink.init();
  codeTableLink= NULL;
  diLink.init(c->diLink);
  if (diLink.notEmpty()) flags.isDI = true;
  flags.level = c->level();
  if (flags.level >= MaxRecompilationLevels) { // added = zzzz
    warning1("setting invalid nmethod level %ld", flags.level);  // fix this
    flags.level = 0;
  }
  flags.version = c->version();
  if (c->nmName() == nm_nic && ((FCompiler*)c)->isImpure)
    makeImpureNIC();
  key.set_from(c->L->key);
  check_store();
  
  clear_frame_chain();
  assert(c->frameSize() >= 0, "frame size cannot be negative");
  frame_size = c->frameSize();
  _incoming_arg_count = c->incoming_arg_count();
  get_platform_specific_data(c);

  Assembler* instsA = c->instructions();
  copy_bytes(        instsA->instsStart,        insts(), instsLen());
  copy_words((int32*)instsA->locsStart,  (int32*)locs(),  ilLen/4);
  copy_words((int32*)depsStart,          (int32*)deps(),  depsLen/4);
  
  addrDesc *l, *lend;
  for (l = locs(), lend = locsEnd(); l < lend; l++) {
    l->initialShift(this, (char*)insts() - (char*)instsA->instsStart, 0);
  }

  char* bound = Memory->new_gen->boundary();
  for (l = locs(), lend = locsEnd(); l < lend; l++) {
    if (l->isOop())
      OopNCode::check_store(oop(l->referent(this)), bound); // cfront garbage
    else if (l->isSendDesc()) {
      l->asSendDesc(this)->dependency()->init();
    } else if (l->isDIDesc()) {
      l->asDIDesc(this)->dependency()->init();
      flags.isDI = true; 
    }
  }
  
  for (nmln* d = deps(), *dend = depsEnd(); d < dend; d++) {
    d->relocate();
  }
  
  MachineCache::flush_instruction_cache_range(insts(), instsEnd());
  MachineCache::flush_instruction_cache_for_debugging();
  
  if (this == (nmethod*)catchThisOne) warning("caught nmethod");
}
Exemple #26
0
static int getSize(int def) {
  const int blockSize = 4 * K;
  return roundTo(def, blockSize);
}
Exemple #27
0
static int getSize(char* name, int def) {
  const int blockSize = 4 * K;
  int size = GetNumericEnvironmentVariable(name, 1024, def);
  return roundTo(size, blockSize);
}
Exemple #28
0
static int scale_and_adjust(int value) {
  int result = roundTo(value * K, Universe::page_size());
  return result;
}
Exemple #29
0
//Public
QPointF LinkNodeItem::gridSnapOffset() const {
    if (grid_size) return roundTo(sceneCenterPos(), grid_size) - sceneCenterPos();
    else return QPointF();
}
inline double normalize(double x) {
	return roundTo(roundTo(roundTo(x, -1), 1), 0);
}