void CoverBond::apply(Particle *p) const { Bond bd(p); core::XYZ ea(bd.get_bonded(0)), eb(bd.get_bonded(1)); core::XYZR r(p); r.set_coordinates(.5*(ea.get_coordinates()+ eb.get_coordinates())); r.set_radius((r.get_coordinates()- ea.get_coordinates()).get_magnitude()); }
template <class T> T ExponentiationPrecomputation<T>::CascadeExponentiate(const Integer &exponent, const ExponentiationPrecomputation<T> &pc2, const Integer &exponent2) const { std::vector<BaseAndExponent<Element> > eb(m_bases.size()+pc2.m_bases.size()); // array of segments of the exponent and precalculated bases Integer temp, e = exponent; unsigned i; for (i=0; i+1<m_bases.size(); i++) { Integer::Divide(eb[i].exponent, temp, e, m_exponentBase); std::swap(temp, e); eb[i].base = m_bases[i]; } eb[i].exponent = e; eb[i].base = m_bases[i]; e = exponent2; for (i=m_bases.size(); i+1<m_bases.size()+pc2.m_bases.size(); i++) { Integer::Divide(eb[i].exponent, temp, e, pc2.m_exponentBase); std::swap(temp, e); eb[i].base = pc2.m_bases[i-m_bases.size()]; } eb[i].exponent = e; eb[i].base = pc2.m_bases[i-m_bases.size()]; return GeneralCascadeMultiplication<Element>(*m_group, eb.begin(), eb.end()); }
void CoverBond::apply_index(Model *m, ParticleIndex pi) const { Bond bd(m, pi); core::XYZ ea(bd.get_bonded(0)), eb(bd.get_bonded(1)); core::XYZR r(m, pi); r.set_coordinates(.5 * (ea.get_coordinates() + eb.get_coordinates())); r.set_radius((r.get_coordinates() - ea.get_coordinates()).get_magnitude()); }
template <class T> ExponentiationPrecomputation<T>::Element ExponentiationPrecomputation<T>::CascadeExponentiate(const Integer &exponent, const ExponentiationPrecomputation<T> &pc2, const Integer &exponent2) const { std::vector<CryptoPair> eb(storage+pc2.storage); // array of segments of the exponent and precalculated bases Integer temp, e = exponent; unsigned i; for (i=0; i+1<storage; i++) { Integer::Divide(eb[i].first, temp, e, exponentBase); std::swap(temp, e); eb[i].second = g[i]; } eb[i].first = e; eb[i].second = g[i]; e = exponent2; for (i=storage; i+1<storage+pc2.storage; i++) { Integer::Divide(eb[i].first, temp, e, exponentBase); std::swap(temp, e); eb[i].second = pc2.g[i-storage]; } eb[i].first = e; eb[i].second = pc2.g[i-storage]; return GeneralCascadeMultiplication<Element>(group, eb.begin(), eb.end()); }
void dotted2nested(BSONObjBuilder& b, const BSONObj& obj){ //use map to sort fields BSONMap sorted = bson2map(obj); EmbeddedBuilder eb(&b); for(BSONMap::const_iterator it=sorted.begin(); it!=sorted.end(); ++it){ eb.appendAs(it->second, it->first); } eb.done(); }
int main(int argc, char **argv) { int i=0; if (Fl::args(argc,argv,i,arg) < argc) Fl::fatal("Options are:\n -2 = 2 windows\n -f = startup fullscreen\n%s",Fl::help); Fl_Single_Window window(300,300+30*NUMB); window.end(); shape_window sw(10,10,window.w()-20,window.h()-30*NUMB-20); #if HAVE_GL sw.mode(FL_RGB); #endif Fl_Window *w; if (twowindow) { // make it's own window sw.resizable(&sw); w = &sw; window.set_modal(); // makes controls stay on top when fullscreen pushed argc--; sw.show(); } else { // otherwise make a subwindow window.add(sw); window.resizable(&sw); w = &window; } window.begin(); int y = window.h()-30*NUMB-5; Fl_Hor_Slider slider(50,y,window.w()-60,30,"Sides:"); slider.clear_flag(FL_ALIGN_MASK); slider.set_flag(FL_ALIGN_LEFT); slider.callback(sides_cb,&sw); slider.value(sw.sides); slider.step(1); slider.range(3,40); y+=30; Fl_Toggle_Light_Button b1(50,y,window.w()-60,30,"Double Buffered"); b1.callback(double_cb,&sw); y+=30; Fl_Toggle_Light_Button b3(50,y,window.w()-60,30,"FullScreen"); b3.callback(fullscreen_cb,w); y+=30; Fl_Button eb(50,y,window.w()-60,30,"Exit"); eb.callback(exit_cb); y+=30; if (initfull) {b3.set(); b3.do_callback();} window.end(); window.show(argc,argv); return Fl::run(); }
int main() { std::vector<Node *> nodes; std::vector<Edge *> edges; N na("a"); N nb("b"); N nc("c"); N nd("d"); E ea(&na, &nb, 6); E eb(&nb, &nc, 5); E ec(&nc, &nd, 4); E ed(&nd, &na, 3); E ee(&na, &nc, 2); E ef(&nb, &nd, 1); nodes.push_back(&na); nodes.push_back(&nb); nodes.push_back(&nc); nodes.push_back(&nd); edges.push_back(&ea); edges.push_back(&eb); edges.push_back(&ec); edges.push_back(&ed); edges.push_back(&ee); edges.push_back(&ef); Kruskal k(nodes, edges); float w = k.solve(); std::cout << "Tree weight: " << std::endl << w << std::endl; std::cout << "Edges: " << std::endl; std::vector<Edge *> mst = k.getEdges(); for (std::vector<Edge *>::iterator it = mst.begin(); it != mst.end(); it++) { N *a = (N *) (*it)->a; N *b = (N *) (*it)->b; std::cout << a->name << " - " << b->name << std::endl; } return 0; }
bool UpdateDriver::createFromQuery(const BSONObj query, BSONObj* newObj) const { // TODO // This moved from ModSet::createNewFromQuery // Check if it can be streamlined BSONObjBuilder bb; EmbeddedBuilder eb(&bb); BSONObjIteratorSorted i(query); while (i.more()) { BSONElement e = i.next(); if (e.fieldName()[0] == '$') // for $atomic and anything else we add continue; if (e.type() == Object && e.embeddedObject().firstElementFieldName()[0] == '$') { // we have something like { x : { $gt : 5 } } // this can be a query piece // or can be a dbref or something int op = e.embeddedObject().firstElement().getGtLtOp(); if (op > 0) { // This means this is a $gt type filter, so don't make it part of the new // object. continue; } if (mongoutils::str::equals(e.embeddedObject().firstElement().fieldName(), "$not")) { // A $not filter operator is not detected in getGtLtOp() and should not // become part of the new object. continue; } } // Skips things we can't store (like dots in field names) // TODO: Find way to check without copy if (!e.wrap().okForStorageAsRoot()) { continue; } eb.appendAs(e , e.fieldName()); } eb.done(); *newObj = bb.obj(); return true; }
static void computeBitmaps(cv::Mat src, cv::Mat& _tb, cv::Mat& _eb) { int histogram[256] = {0}; cv::Size size = src.size(); for (int i = 0; i < size.height; i++) { for (int j = 0; j < size.width; j++) { int c = (unsigned int) src.at<uchar>(i, j); histogram[c] += 1; } } int median_counter = size.height * size.width / 2, threshold = 0; for (int i = 0; i < 256; ++i) { median_counter += histogram[i]; if (median_counter - histogram[i] > 0) { median_counter -= histogram[i]; } else { threshold = i; break; } } cv::Mat_<uchar> tb(size); for (int i = 0; i < size.height; ++i) { for (int j = 0; j < size.width; ++j) { bool cond = src.at<uchar>(i, j) <= threshold; tb.at<uchar>(i, j) = (cond ? 0 : 1); } } _tb = tb; cv::Mat_<uchar> eb(size); for (int i = 0; i < size.height; ++i) { for (int j = 0; j < size.width; ++j) { bool cond = std::abs(src.at<uchar>(i, j) - threshold) <= 4; eb.at<uchar>(i, j) = (cond ? 0 : 1); } } _eb = eb; }
double Prior::sample_alpha(Model* model, const VectorView& y, Rand& rng) { // then use full conditional of alpha to update it size_t nterms = (model->beta).length() - m_e; double a = alpha_; do { // disallow exact zero value if (nterms > 0){ // propose switching sign of alpha and eta (sign of eta has no effect as long // as we actually sample beta; note that eta has symmetric zero mean // distribution); this is metropolis move with deterministic // proposal; no effect is mu_alpha is zero (might as well skip...) if ((a <= 0.0) || log(rng.rand_01()) <= -2.0 * mu_alpha * a){ a = -a; } Vector xb(n); Vector eb(n); xb.set_to_product((model->x).columnblock(m_e, nterms), (model->beta).block(m_e, nterms), false); eb.set_to_product((model->x).columnblock(0, m_e), (model->beta).block(0, m_e), false); eb -= y; // note: this is E * b - y, hence there is minus below in mu formul. double alpha_sigma2 = a * model->sigma2; double var = 1.0 / (1.0 + VectorView::dotproduct(xb, xb) / (a * alpha_sigma2)); double mu = var * (mu_alpha - VectorView::dotproduct(eb, xb) / alpha_sigma2); a = sqrt(var) * rng.rand_normal() + mu; } else { // sample from prior a = rng.rand_normal() + mu_alpha; } } while (a == 0 || a * a == 0); model->mu_beta_computed = false; return a; }
virtual void on_draw() { pixfmt pf(rbuf_window()); typedef agg::pixfmt_alpha_blend_gray<gray_blender, agg::rendering_buffer, 3, 2> pixfmt_r; typedef agg::pixfmt_alpha_blend_gray<gray_blender, agg::rendering_buffer, 3, 1> pixfmt_g; typedef agg::pixfmt_alpha_blend_gray<gray_blender, agg::rendering_buffer, 3, 0> pixfmt_b; pixfmt_r pfr(rbuf_window()); pixfmt_g pfg(rbuf_window()); pixfmt_b pfb(rbuf_window()); agg::renderer_base<pixfmt> rbase(pf); agg::renderer_base<pixfmt_r> rbr(pfr); agg::renderer_base<pixfmt_g> rbg(pfg); agg::renderer_base<pixfmt_b> rbb(pfb); agg::rasterizer_scanline_aa<> ras; agg::scanline_p8 sl; rbase.clear(agg::rgba(1,1,1)); agg::ellipse er(width() / 2 - 0.87*50, height() / 2 - 0.5*50, 100, 100, 100); ras.add_path(er); agg::render_scanlines_aa_solid(ras, sl, rbr, agg::gray8(0, unsigned(m_alpha.value()))); agg::ellipse eg(width() / 2 + 0.87*50, height() / 2 - 0.5*50, 100, 100, 100); ras.add_path(eg); agg::render_scanlines_aa_solid(ras, sl, rbg, agg::gray8(0, unsigned(m_alpha.value()))); agg::ellipse eb(width() / 2, height() / 2 + 50, 100, 100, 100); ras.add_path(eb); agg::render_scanlines_aa_solid(ras, sl, rbb, agg::gray8(0, unsigned(m_alpha.value()))); agg::render_ctrl(ras, sl, rbase, m_alpha); }
CdbDumperHelper::DumpExecuteResult CdbDumperHelper::executeDump(const WatchData &wd, const QtDumperHelper::TypeData& td, bool dumpChildren, QList<WatchData> *result, QString *errorMessage) { QByteArray inBuffer; QStringList extraParameters; // Build parameter list. m_helper.evaluationParameters(wd, td, QtDumperHelper::CdbDebugger, &inBuffer, &extraParameters); QString callCmd; QTextStream str(&callCmd); str << ".call " << m_dumpObjectSymbol << "(2,0," << wd.addr << ',' << (dumpChildren ? 1 : 0); foreach(const QString &e, extraParameters) str << ',' << e; str << ')'; if (dumpDebug) qDebug() << "Query: " << wd.toString() << "\nwith: " << callCmd << '\n'; const char *outputData; // Completely ignore EXCEPTION_ACCESS_VIOLATION crashes in the dumpers. ExceptionBlocker eb(m_coreEngine->interfaces().debugControl, EXCEPTION_ACCESS_VIOLATION, ExceptionBlocker::IgnoreException); if (!eb) { *errorMessage = eb.errorString(); return DumpExecuteCallFailed; } switch (callDumper(callCmd, inBuffer, &outputData, true, errorMessage)) { case CallFailed: return DumpExecuteCallFailed; case CallSyntaxError: return DumpExpressionFailed; case CallOk: break; } if (!QtDumperHelper::parseValue(outputData, result)) { *errorMessage = QLatin1String("Parsing of value query output failed."); return DumpExecuteCallFailed; } return DumpExecuteOk; }
Mesh PetitEtageBusiness::generate() const { MeshBuilder mb; Mesh pebMesh = mb.generationEtage(this); QVector<std::pair<Batiment*,int>> bats; ToitBusiness tb(base, hauteur+hauteurEtage, hauteurEtage, hMax, shrinkMax, aireMin); EtageBusiness eb(base, hauteur+hauteurEtage, hauteurEtage, hMax-1, shrinkMax, aireMin); Division d(base, hauteur+hauteurEtage, hauteurEtage, hMax-1, shrinkMax-1, aireMin); bats.append(std::make_pair(&tb, 2)); if(hMax > 1) { bats.append(std::make_pair(&eb, 70)); if(shrinkMax > 0 && d.getPoly1().area()>aireMin && d.getPoly2().area() > aireMin) { bats.append(std::make_pair(&d, 10)); } } pebMesh.merge(getRandomBatiment(bats)->generate()); return pebMesh; }
void runInteractive(llvm::Module *llvmModule_, ModulePtr module_) { signal(SIGABRT, exceptionHandler); llvmModule = llvmModule_; module = module_; llvm::errs() << "Clay interpreter\n"; llvm::errs() << ":q to exit\n"; llvm::errs() << ":print {identifier} to print an identifier\n"; llvm::errs() << ":modules to list global modules\n"; llvm::errs() << ":globals to list globals\n"; llvm::errs() << "In multi-line mode empty line to exit\n"; llvm::EngineBuilder eb(llvmModule); llvm::TargetOptions targetOptions; targetOptions.JITExceptionHandling = true; eb.setTargetOptions(targetOptions); engine = eb.create(); engine->runStaticConstructorsDestructors(false); setAddTokens(&addTokens); interactiveLoop(); }
void KGameProgress::drawContents(QPainter *p) { QRect cr = contentsRect(), er = cr; fr = cr; QBrush fb(bar_color), eb(backgroundColor()); if (bar_pixmap) fb.setPixmap(*bar_pixmap); if (backgroundPixmap()) eb.setPixmap(*backgroundPixmap()); switch (bar_style) { case Solid: if (orient == Horizontal) { fr.setWidth(recalcValue(cr.width())); er.setLeft(fr.right() + 1); } else { fr.setTop(cr.bottom() - recalcValue(cr.height())); er.setBottom(fr.top() - 1); } p->setBrushOrigin(cr.topLeft()); p->fillRect(fr, fb); p->fillRect(er, eb); break; case Blocked: const int margin = 2; int max, num, dx, dy; if (orient == Horizontal) { fr.setHeight(cr.height() - 2 * margin); fr.setWidth((int)(0.67 * fr.height())); fr.moveTopLeft(QPoint(cr.left() + margin, cr.top() + margin)); dx = fr.width() + margin; dy = 0; max = (cr.width() - margin) / (fr.width() + margin) + 1; num = recalcValue(max); } else { fr.setWidth(cr.width() - 2 * margin); fr.setHeight((int)(0.67 * fr.width())); fr.moveBottomLeft(QPoint(cr.left() + margin, cr.bottom() - margin)); dx = 0; dy = - (fr.height() + margin); max = (cr.height() - margin) / (fr.height() + margin) + 1; num = recalcValue(max); } p->setClipRect(cr.x() + margin, cr.y() + margin, cr.width() - margin, cr.height() - margin); for (int i = 0; i < num; i++) { p->setBrushOrigin(fr.topLeft()); p->fillRect(fr, fb); fr.moveBy(dx, dy); } if (num != max) { if (orient == Horizontal) er.setLeft(fr.right() + 1); else er.setBottom(fr.bottom() + 1); if (!er.isNull()) { p->setBrushOrigin(cr.topLeft()); p->fillRect(er, eb); } } break; } if (text_enabled && bar_style != Blocked) drawText(p); }
Vector OdeErrControl( Method &method, const Scalar &ti , const Scalar &tf , const Vector &xi , const Scalar &smin , const Scalar &smax , Scalar &scur , const Vector &eabs , const Scalar &erel , Vector &ef , Vector &maxabs, size_t &nstep ) { // check simple vector class specifications CheckSimpleVector<Scalar, Vector>(); size_t n = xi.size(); CppADUsageError( smin <= smax, "Error in OdeErrControl: smin > smax" ); CppADUsageError( eabs.size() == n, "Error in OdeErrControl: size of eabs is not equal to n" ); CppADUsageError( maxabs.size() == n, "Error in OdeErrControl: size of maxabs is not equal to n" ); size_t m = method.order(); CppADUsageError( m > 1, "Error in OdeErrControl: m is less than or equal one" ); size_t i; Vector xa(n), xb(n), eb(n); // initialization Scalar zero(0); Scalar one(1); Scalar two(2); Scalar three(3); Scalar m1(m-1); Scalar ta = ti; for(i = 0; i < n; i++) { ef[i] = zero; xa[i] = xi[i]; if( zero <= xi[i] ) maxabs[i] = xi[i]; else maxabs[i] = - xi[i]; } nstep = 0; Scalar tb, step, lambda, axbi, a, r, root; while( ! (ta == tf) ) { // start with value suggested by error criteria step = scur; // check maximum if( smax <= step ) step = smax; // check minimum if( step <= smin ) step = smin; // check if near the end if( tf <= ta + step * three / two ) tb = tf; else tb = ta + step; // try using this step size nstep++; method.step(ta, tb, xa, xb, eb); step = tb - ta; // compute value of lambda for this step lambda = Scalar(10) * scur / step; for(i = 0; i < n; i++) { if( zero <= xb[i] ) axbi = xb[i]; else axbi = - xb[i]; a = eabs[i] + erel * axbi; if( ! (eb[i] == zero) ) { r = ( a / eb[i] ) * step / (tf - ti); root = exp( log(r) / m1 ); if( root <= lambda ) lambda = root; } } if( one <= lambda || step <= smin * three / two ) { // this step is within error limits or // close to the minimum size ta = tb; for(i = 0; i < n; i++) { xa[i] = xb[i]; ef[i] = ef[i] + eb[i]; if( zero <= xb[i] ) axbi = xb[i]; else axbi = - xb[i]; if( axbi > maxabs[i] ) maxabs[i] = axbi; } } // step suggested by error criteria // do not use last step becasue it may be very small if( ! (ta == tf) ) scur = lambda * step / two; } return xa; }
int Operand6502::parse(char *op) { char ch; char ch1; int reg; AsmBuf eb(100); AsmBuf ob(op+1,strlen(op+1)+1); theAssembler.errtype = true; type = 0; val.value = 0; r1 = 0; r2 = 0; if (isAReg(op)) return type = AM_ACC; // Immediate if(op[0] == '#') { val = ob.expeval(NULL); type = AM_IMM; return type; } // (d,s),y if (strmat(op, " ( %s, %c ) , %c ", eb.buf(), &ch1, &ch)) { if (tolower(ch1) == 's') { val = eb.expeval(NULL); if (tolower(ch)!='y') Err(E_INVOPERAND, op); return type = AM_SRIY; } } // (zp),y if (strmat(op, " ( %s) , %c ", eb.buf(), &ch)) { val = eb.expeval(NULL); if (tolower(ch)!='y') Err(E_INVOPERAND, op); r1 = 3; return type = AM_IY; } // [zp],y if (strmat(op, " [ %s] , %c ", eb.buf(), &ch)) { val = eb.expeval(NULL); if (tolower(ch)!='y') Err(E_INVOPERAND, op); return type = AM_IYL; } // (zp,x) if(strmat(op, " ( %s, %c) ", eb.buf(), &ch)) { val = eb.expeval(NULL); r1 = 2; if (tolower(ch)!='x') Err(E_INVOPERAND, op); return type = AM_IX; } // (abs) { jmp } if(strmat(op, " ( %s) ", eb.buf())) { val = eb.expeval(NULL); if (val.value < 256 && val.value >= 0) return type = AM_ZI; return type = AM_I; } // [abs] { jmp } if(strmat(op, " [ %s] ", eb.buf())) { val = eb.expeval(NULL); if (val.value < 256 && val.value >= 0) return type = AM_ZIL; return type = AM_IL; } // d,sp if (strmat(op, " %s, %c ", eb.buf(), &ch)) { if (tolower(ch)=='s') { val = eb.expeval(NULL); return type = AM_SR; } } // Could be indexed if (strmat(op, " %s, %c ", eb.buf(), &ch)) { val = eb.expeval(NULL); if (val.value < 256 && val.value >= 0) { if (tolower(ch)=='x') return type = AM_ZX; else if (tolower(ch)=='y') return type = AM_ZY; else Err(E_INVOPERAND, op); return AM_Z; } else { if (tolower(ch)=='x') return type = AM_AX; else if (tolower(ch)=='y') return type = AM_AY; else Err(E_INVOPERAND, op); return AM_A; } } // Assume // Absolute / Zero page // This must be the last mode tested for since anything will // match strmat(op, " %s ", eb.buf()); val = eb.expeval(NULL); if (val.value < 256 && val.value >= 0) { r2 = 0; return type = AM_Z; } return type = AM_A; }
Vector OdeErrControl( Method &method, const Scalar &ti , const Scalar &tf , const Vector &xi , const Scalar &smin , const Scalar &smax , Scalar &scur , const Vector &eabs , const Scalar &erel , Vector &ef , Vector &maxabs, size_t &nstep ) { // check simple vector class specifications CheckSimpleVector<Scalar, Vector>(); size_t n = size_t(xi.size()); CPPAD_ASSERT_KNOWN( smin <= smax, "Error in OdeErrControl: smin > smax" ); CPPAD_ASSERT_KNOWN( size_t(eabs.size()) == n, "Error in OdeErrControl: size of eabs is not equal to n" ); CPPAD_ASSERT_KNOWN( size_t(maxabs.size()) == n, "Error in OdeErrControl: size of maxabs is not equal to n" ); size_t m = method.order(); CPPAD_ASSERT_KNOWN( m > 1, "Error in OdeErrControl: m is less than or equal one" ); bool ok; bool minimum_step; size_t i; Vector xa(n), xb(n), eb(n), nan_vec(n); // initialization Scalar zero(0); Scalar one(1); Scalar two(2); Scalar three(3); Scalar m1(m-1); Scalar ta = ti; for(i = 0; i < n; i++) { nan_vec[i] = nan(zero); ef[i] = zero; xa[i] = xi[i]; if( zero <= xi[i] ) maxabs[i] = xi[i]; else maxabs[i] = - xi[i]; } nstep = 0; Scalar tb, step, lambda, axbi, a, r, root; while( ! (ta == tf) ) { // start with value suggested by error criteria step = scur; // check maximum if( smax <= step ) step = smax; // check minimum minimum_step = step <= smin; if( minimum_step ) step = smin; // check if near the end if( tf <= ta + step * three / two ) tb = tf; else tb = ta + step; // try using this step size nstep++; method.step(ta, tb, xa, xb, eb); step = tb - ta; // check if this steps error estimate is ok ok = ! (hasnan(xb) || hasnan(eb)); if( (! ok) && minimum_step ) { ef = nan_vec; return nan_vec; } // compute value of lambda for this step lambda = Scalar(10) * scur / step; for(i = 0; i < n; i++) { if( zero <= xb[i] ) axbi = xb[i]; else axbi = - xb[i]; a = eabs[i] + erel * axbi; if( ! (eb[i] == zero) ) { r = ( a / eb[i] ) * step / (tf - ti); root = exp( log(r) / m1 ); if( root <= lambda ) lambda = root; } } if( ok && ( one <= lambda || step <= smin * three / two) ) { // this step is within error limits or // close to the minimum size ta = tb; for(i = 0; i < n; i++) { xa[i] = xb[i]; ef[i] = ef[i] + eb[i]; if( zero <= xb[i] ) axbi = xb[i]; else axbi = - xb[i]; if( axbi > maxabs[i] ) maxabs[i] = axbi; } } if( ! ok ) { // decrease step an see if method will work this time scur = step / two; } else if( ! (ta == tf) ) { // step suggested by the error criteria is not used // on the last step because it may be very small. scur = lambda * step / two; } } return xa; }
int main(int argc, char *argv[]) { # include "setRootCase.H" # include "createTime.H" // Get times list instantList Times = runTime.times(); const label startTime = 1; const label endTime = Times.size(); const label nSnapshots = Times.size() - 1; Info << "Number of snapshots: " << nSnapshots << endl; // Create a list of snapshots PtrList<volScalarField> fields(nSnapshots); runTime.setTime(Times[startTime], startTime); # include "createMesh.H" IOdictionary PODsolverDict ( IOobject ( "PODsolverDict", runTime.system(), mesh, IOobject::MUST_READ, IOobject::NO_WRITE ) ); scalar accuracy = readScalar ( PODsolverDict.subDict("scalarTransportCoeffs").lookup("accuracy") ); Info << "Seeking accuracy: " << accuracy << endl; word fieldName ( PODsolverDict.subDict("scalarTransportCoeffs").lookup("field") ); label snapI = 0; labelList timeIndices(nSnapshots); for (label i = startTime; i < endTime; i++) { runTime.setTime(Times[i], i); Info<< "Time = " << runTime.timeName() << endl; mesh.readUpdate(); Info<< " Reading " << fieldName << endl; fields.set ( snapI, new volScalarField ( IOobject ( fieldName, runTime.timeName(), mesh, IOobject::MUST_READ ), mesh ) ); // Rename the field fields[snapI].rename(fieldName + name(i)); timeIndices[snapI] = i; snapI++; Info<< endl; } timeIndices.setSize(snapI); // Read accurary Info<< "Reading \n" << endl; scalarPODOrthoNormalBase eb(fields, accuracy); const scalarRectangularMatrix& coeffs = eb.interpolationCoeffs(); // Check all snapshots forAll (fields, fieldI) { runTime.setTime(Times[timeIndices[fieldI]], timeIndices[fieldI]); volScalarField pReconstruct ( IOobject ( fieldName + "PODreconstruct", runTime.timeName(), mesh, IOobject::NO_READ ), mesh, dimensionedScalar("zero", fields[fieldI].dimensions(), 0) ); for (label baseI = 0; baseI < eb.baseSize(); baseI++) { pReconstruct += coeffs[fieldI][baseI]*eb.orthoField(baseI); } scalar sumFieldError = Foam::sqrt ( sumSqr ( pReconstruct.internalField() - fields[fieldI].internalField() ) ); scalar measure = Foam::sqrt(sumSqr(fields[fieldI].internalField())) + SMALL; scalar sumFieldRelError = sumFieldError/measure; Info<< "Field error: absolute = " << sumFieldError << " relative = " << sumFieldRelError << " measure = " << measure << endl; pReconstruct.write(); }
int FMMGetEpsilon_Kottke(const S4_Simulation *S, const S4_Layer *L, const int n, std::complex<double> *Epsilon2, std::complex<double> *Epsilon_inv){ const int n2 = 2*n; const int *G = S->G; // Make grid // Determine size of the grid int ngrid[2] = {1,1}; for(int i = 0; i < 2; ++i){ // choose grid size for(int j = 0; j < n; ++j){ if(abs(G[2*j+i]) > ngrid[i]){ ngrid[i] = abs(G[2*j+i]); } } if(ngrid[i] < 1){ ngrid[i] = 1; } ngrid[i] *= S->options.resolution; ngrid[i] = fft_next_fast_size(ngrid[i]); } S4_TRACE("I Subpixel smoothing on %d x %d grid\n", ngrid[0], ngrid[1]); const int ng2 = ngrid[0]*ngrid[1]; const double ing2 = 1./(double)ng2; // The grid needs to hold 5 matrix elements: xx,xy,yx,yy,zz // We actually make 5 different grids to facilitate the fft routines //std::complex<double> *work = (std::complex<double>*)S4_malloc(sizeof(std::complex<double>)*(6*ng2)); std::complex<double> *work = fft_alloc_complex(6*ng2); std::complex<double>*fxx = work; std::complex<double>*fxy = fxx + ng2; std::complex<double>*fyx = fxy + ng2; std::complex<double>*fyy = fyx + ng2; std::complex<double>*fzz = fyy + ng2; std::complex<double>*Fto = fzz + ng2; //memset(work, 0, sizeof(std::complex<double>) * 6*ng2); double *discval = (double*)S4_malloc(sizeof(double)*(L->pattern.nshapes+1)); fft_plan plans[5]; for(int i = 0; i <= 4; ++i){ plans[i] = fft_plan_dft_2d(ngrid, fxx+i*ng2, Fto, 1); } int ii[2]; for(ii[0] = 0; ii[0] < ngrid[0]; ++ii[0]){ const int si0 = ii[0] >= ngrid[0]/2 ? ii[0]-ngrid[0]/2 : ii[0]+ngrid[0]/2; for(ii[1] = 0; ii[1] < ngrid[1]; ++ii[1]){ const int si1 = ii[1] >= ngrid[1]/2 ? ii[1]-ngrid[1]/2 : ii[1]+ngrid[1]/2; Pattern_DiscretizeCell(&L->pattern, S->Lr, ngrid[0], ngrid[1], ii[0], ii[1], discval); int nnz = 0; int imat[2] = {-1,-1}; for(int i = 0; i <= L->pattern.nshapes; ++i){ if(fabs(discval[i]) > 2*std::numeric_limits<double>::epsilon()){ if(0 == nnz){ imat[0] = i; } else if(1 == nnz){ imat[1] = i; } ++nnz; } } //S4_TRACE("I %d,%d nnz = %d\n", ii[0], ii[1], nnz); if(nnz < 2){ // just one material //fprintf(stderr, "%d\t%d\t0\t0\n", ii[0], ii[1]); const S4_Material *M; if(0 == imat[0]){ M = &S->material[L->material]; }else{ M = &S->material[L->pattern.shapes[imat[0]-1].tag]; } if(0 == M->type){ std::complex<double> eps_scalar(M->eps.s[0], M->eps.s[1]); fxx[si1+si0*ngrid[1]] = eps_scalar; fxy[si1+si0*ngrid[1]] = 0; fyx[si1+si0*ngrid[1]] = 0; fyy[si1+si0*ngrid[1]] = eps_scalar; fzz[si1+si0*ngrid[1]] = eps_scalar; }else{ fxx[si1+si0*ngrid[1]] = std::complex<double>(M->eps.abcde[0],M->eps.abcde[1]); fyy[si1+si0*ngrid[1]] = std::complex<double>(M->eps.abcde[6],M->eps.abcde[7]); fxy[si1+si0*ngrid[1]] = std::complex<double>(M->eps.abcde[2],M->eps.abcde[3]); fyx[si1+si0*ngrid[1]] = std::complex<double>(M->eps.abcde[4],M->eps.abcde[5]); fzz[si1+si0*ngrid[1]] = std::complex<double>(M->eps.abcde[8],M->eps.abcde[9]); } }else{ if(imat[1] > imat[0]){ std::swap(imat[0],imat[1]); } // imat[0] is the more-contained shape double nvec[2]; const double nxvec[2] = { ((double)ii[0]+0.5)/(double)ngrid[0]-0.5, ((double)ii[1]+0.5)/(double)ngrid[1]-0.5 }; const double xvec[2] = { // center of current parallelogramic pixel S->Lr[0]*nxvec[0] + S->Lr[2]*nxvec[1], S->Lr[1]*nxvec[0] + S->Lr[3]*nxvec[1] }; shape_get_normal(&(L->pattern.shapes[imat[0]-1]), xvec, nvec); if(2 == nnz && imat[1] != imat[0] && !(0 == nvec[0] && 0 == nvec[1])){ // use Kottke averaging //fprintf(stderr, "%d\t%d\t%f\t%f\n", ii[0], ii[1], nvec[0], nvec[1]); const double fill = discval[imat[0]]; // Get the two tensors std::complex<double> abcde[2][5]; for(int i = 0; i < 2; ++i){ const S4_Material *M; if(0 == imat[i]){ M = &S->material[L->material]; }else{ M = &S->material[L->pattern.shapes[imat[i]-1].tag]; } if(0 == M->type){ std::complex<double> eps_scalar(M->eps.s[0], M->eps.s[1]); abcde[i][0] = eps_scalar; abcde[i][1] = 0; abcde[i][2] = 0; abcde[i][3] = eps_scalar; abcde[i][4] = eps_scalar; }else{ for(int j = 0; j < 4; ++j){ abcde[i][j] = std::complex<double>(M->eps.abcde[2*j+0],M->eps.abcde[2*j+1]); } abcde[i][4] = std::complex<double>(M->eps.abcde[8],M->eps.abcde[9]); } } // The zz component is just directly obtained by averaging fzz[si1+si0*ngrid[1]] = discval[imat[0]] * abcde[0][4] + discval[imat[1]] * abcde[1][4]; // Compute rotated tensors // abcd1 = Rot^T abcd1 Rot // Rot = [ nvec[0] -nvec[1] ] // [ nvec[1] nvec[0] ] std::complex<double> abcd[2][4]; //fprintf(stderr, " nvec = {%f,%f}, fill = %f\n", nvec[0], nvec[1], fill); //fprintf(stderr, " abcde[0] = {%f,%f,%f,%f}\n", abcde[0][0].real(), abcde[0][1].real(), abcde[0][2].real(), abcde[0][3].real()); //fprintf(stderr, " abcde[1] = {%f,%f,%f,%f}\n", abcde[1][0].real(), abcde[1][1].real(), abcde[1][2].real(), abcde[1][3].real()); sym2x2rot(abcde[0], nvec, abcd[0]); sym2x2rot(abcde[1], nvec, abcd[1]); // Compute the average tau tensor into abcde[0][0-3] // tau(e__) = [ -1/e11 e12/e11 ] // [ e21/e11 e22 - e21 e12/e11 ] abcde[0][0] = fill * (-1./abcd[0][0]) + (1.-fill) * (-1./abcd[1][0]); abcde[0][1] = fill * (abcd[0][1]/abcd[0][0]) + (1.-fill) * (abcd[1][1]/abcd[1][0]); abcde[0][2] = fill * (abcd[0][2]/abcd[0][0]) + (1.-fill) * (abcd[1][2]/abcd[1][0]); abcde[0][3] = fill * (abcd[0][3]-abcd[0][1]*abcd[0][2]/abcd[0][0]) + (1.-fill) * (abcd[1][3]-abcd[1][1]*abcd[1][2]/abcd[1][0]); // Invert the tau transform into abcd[1] // invtau(t__) = [ -1/t11 -t12/t11 ] // [ -t21/t11 t22 - t21 t12/t11 ] abcd[1][0] = -1./abcde[0][0]; abcd[1][1] = -abcde[0][1]/abcde[0][0]; abcd[1][2] = -abcde[0][2]/abcde[0][0]; abcd[1][3] = abcde[0][3] - abcde[0][1]*abcde[0][2]/abcde[0][0]; //fprintf(stderr, " abcd[1] = {%f,%f,%f,%f}\n", abcd[1][0].real(), abcd[1][1].real(), abcd[1][2].real(), abcd[1][3].real()); // Unrotate abcd[1] into abcd[0] nvec[1] = -nvec[1]; sym2x2rot(abcd[1], nvec, abcd[0]); //fprintf(stderr, " abcd[0] = {%f,%f,%f,%f}\n\n", abcd[0][0].real(), abcd[0][1].real(), abcd[0][2].real(), abcd[0][3].real()); fxx[si1+si0*ngrid[1]] = abcd[0][0]; fxy[si1+si0*ngrid[1]] = abcd[0][1]; fyx[si1+si0*ngrid[1]] = abcd[0][2]; fyy[si1+si0*ngrid[1]] = abcd[0][3]; }else{ // too many, just use the area weighting //fprintf(stderr, "%d\t%d\t3\n", ii[0], ii[1]); fxx[si1+si0*ngrid[1]] = 0; fxy[si1+si0*ngrid[1]] = 0; fyx[si1+si0*ngrid[1]] = 0; fyy[si1+si0*ngrid[1]] = 0; fzz[si1+si0*ngrid[1]] = 0; for(int i = 0; i <= L->pattern.nshapes; ++i){ if(0 == discval[i]){ continue; } int j = i-1; const S4_Material *M; if(-1 == j){ M = &S->material[L->material]; }else{ M = &S->material[L->pattern.shapes[j].tag]; } if(0 == M->type){ std::complex<double> eps_scalar(M->eps.s[0], M->eps.s[1]); fxx[si1+si0*ngrid[0]] += discval[i]*eps_scalar; fyy[si1+si0*ngrid[0]] += discval[i]*eps_scalar; fzz[si1+si0*ngrid[0]] += discval[i]*eps_scalar; }else{ std::complex<double> ea(M->eps.abcde[0],M->eps.abcde[1]); std::complex<double> eb(M->eps.abcde[2],M->eps.abcde[3]); std::complex<double> ec(M->eps.abcde[4],M->eps.abcde[5]); std::complex<double> ed(M->eps.abcde[6],M->eps.abcde[7]); fxx[si1+si0*ngrid[1]] += discval[i]*ea; fxy[si1+si0*ngrid[1]] += discval[i]*eb; fyx[si1+si0*ngrid[1]] += discval[i]*ec; fyy[si1+si0*ngrid[1]] += discval[i]*ed; fzz[si1+si0*ngrid[1]] += discval[i]*std::complex<double>(M->eps.abcde[8],M->eps.abcde[9]); } } } } /* fprintf(stderr, "%d\t%d\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n", ii[0], ii[1], fxx[si1+si0*ngrid[1]].real(), fxx[si1+si0*ngrid[1]].imag(), fxy[si1+si0*ngrid[1]].real(), fxy[si1+si0*ngrid[1]].imag(), fyx[si1+si0*ngrid[1]].real(), fyx[si1+si0*ngrid[1]].imag(), fyy[si1+si0*ngrid[1]].real(), fyy[si1+si0*ngrid[1]].imag(), fzz[si1+si0*ngrid[1]].real(), fzz[si1+si0*ngrid[1]].imag() );//*/ } //fprintf(stderr, "\n"); } // Make Epsilon_inv first { //fprintf(stderr, "fzz1[0] = %f+I %f\n", fzz[0].real(), fzz[0].imag()); //memset(Fto, 0, sizeof(std::complex<double>)*ng2); fft_plan_exec(plans[4]); //fprintf(stderr, "fzz2[0] = %f+I %f\n", fzz[0].real(), fzz[0].imag()); //fprintf(stderr, "Fto[0] = %f+I %f\n", Fto[0].real(), Fto[0].imag()); for(int j = 0; j < n; ++j){ for(int i = 0; i < n; ++i){ int f[2] = {G[2*i+0]-G[2*j+0],G[2*i+1]-G[2*j+1]}; if(f[0] < 0){ f[0] += ngrid[0]; } if(f[1] < 0){ f[1] += ngrid[1]; } Epsilon2[i+j*n] = ing2 * Fto[f[1]+f[0]*ngrid[1]]; } } } //fprintf(stderr, "Epsilon2[0] = %f+I %f\n", Epsilon2[0].real(), Epsilon2[0].imag()); // Epsilon_inv needs inverting RNP::TBLAS::SetMatrix<'A'>(n,n, 0.,1., Epsilon_inv,n); int solve_info; RNP::LinearSolve<'N'>(n,n, Epsilon2,n, Epsilon_inv,n, &solve_info, NULL); //fprintf(stderr, "Epsilon_inv[0] = %f+I %f\n", Epsilon_inv[0].real(), Epsilon_inv[0].imag()); // We fill in the quarter blocks of F in Fortran order for(int w = 0; w < 4; ++w){ int Ecol = (w&1 ? n : 0); int Erow = (w&2 ? n : 0); //memset(Fto, 0, sizeof(std::complex<double>)*ng2); fft_plan_exec(plans[w]); //fprintf(stderr, "Fto(%d)[0] = %f+I %f\n", w, Fto[0].real(), Fto[0].imag()); for(int j = 0; j < n; ++j){ for(int i = 0; i < n; ++i){ int f[2] = {G[2*i+0]-G[2*j+0],G[2*i+1]-G[2*j+1]}; if(f[0] < 0){ f[0] += ngrid[0]; } if(f[1] < 0){ f[1] += ngrid[1]; } Epsilon2[Erow+i+(Ecol+j)*n2] = ing2 * Fto[f[1]+f[0]*ngrid[1]]; } } } //fprintf(stderr, "Epsilon2[0] = %f+I %f\n", Epsilon2[0].real(), Epsilon2[0].imag()); for(int i = 0; i <= 4; ++i){ fft_plan_destroy(plans[i]); } S4_free(discval); //S4_free(work); fft_free(work); return 0; }
void initCodegen() { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); g.stdlib_module = loadStdlib(); #if LLVMREV < 215967 llvm::EngineBuilder eb(new llvm::Module("empty_initial_module", g.context)); #else llvm::EngineBuilder eb(std::unique_ptr<llvm::Module>(new llvm::Module("empty_initial_module", g.context))); #endif #if LLVMREV < 216982 eb.setUseMCJIT(true); #endif eb.setEngineKind(llvm::EngineKind::JIT); // specify we only want the JIT, and not the interpreter fallback #if LLVMREV < 223183 eb.setMCJITMemoryManager(createMemoryManager().release()); #else eb.setMCJITMemoryManager(createMemoryManager()); #endif // eb.setOptLevel(llvm::CodeGenOpt::None); // -O0 // eb.setOptLevel(llvm::CodeGenOpt::Less); // -O1 // eb.setOptLevel(llvm::CodeGenOpt::Default); // -O2, -Os // eb.setOptLevel(llvm::CodeGenOpt::Aggressive); // -O3 llvm::TargetOptions target_options; target_options.NoFramePointerElim = true; // target_options.EnableFastISel = true; eb.setTargetOptions(target_options); // TODO enable this? should let us get better code: // eb.setMCPU(llvm::sys::getHostCPUName()); g.tm = eb.selectTarget(); assert(g.tm && "failed to get a target machine"); g.engine = eb.create(g.tm); assert(g.engine && "engine creation failed?"); if (ENABLE_JIT_OBJECT_CACHE) { g.object_cache = new PystonObjectCache; g.engine->setObjectCache(g.object_cache); } g.i1 = llvm::Type::getInt1Ty(g.context); g.i8 = llvm::Type::getInt8Ty(g.context); g.i8_ptr = g.i8->getPointerTo(); g.i32 = llvm::Type::getInt32Ty(g.context); g.i64 = llvm::Type::getInt64Ty(g.context); g.void_ = llvm::Type::getVoidTy(g.context); g.double_ = llvm::Type::getDoubleTy(g.context); std::vector<llvm::JITEventListener*> listeners = makeJITEventListeners(); for (int i = 0; i < listeners.size(); i++) { g.jit_listeners.push_back(listeners[i]); g.engine->RegisterJITEventListener(listeners[i]); } llvm::JITEventListener* stackmap_listener = makeStackMapListener(); g.jit_listeners.push_back(stackmap_listener); g.engine->RegisterJITEventListener(stackmap_listener); #if ENABLE_INTEL_JIT_EVENTS llvm::JITEventListener* intel_listener = llvm::JITEventListener::createIntelJITEventListener(); g.jit_listeners.push_back(intel_listener); g.engine->RegisterJITEventListener(intel_listener); #endif llvm::JITEventListener* registry_listener = makeRegistryListener(); g.jit_listeners.push_back(registry_listener); g.engine->RegisterJITEventListener(registry_listener); llvm::JITEventListener* tracebacks_listener = makeTracebacksListener(); g.jit_listeners.push_back(tracebacks_listener); g.engine->RegisterJITEventListener(tracebacks_listener); if (SHOW_DISASM) { #if LLVMREV < 216983 llvm::JITEventListener* listener = new DisassemblerJITEventListener(); g.jit_listeners.push_back(listener); g.engine->RegisterJITEventListener(listener); #else fprintf(stderr, "The LLVM disassembler has been removed\n"); abort(); #endif } initGlobalFuncs(g); setupRuntime(); // signal(SIGFPE, &handle_sigfpe); // signal(SIGUSR1, &handle_sigusr1); #if ENABLE_SAMPLING_PROFILER struct itimerval prof_timer; prof_timer.it_value.tv_sec = prof_timer.it_interval.tv_sec = 0; prof_timer.it_value.tv_usec = prof_timer.it_interval.tv_usec = 1000; signal(SIGPROF, handle_sigprof); setitimer(ITIMER_PROF, &prof_timer, NULL); #endif #ifdef INVESTIGATE_STAT_TIMER struct itimerval prof_timer; prof_timer.it_value.tv_sec = prof_timer.it_interval.tv_sec = 0; prof_timer.it_value.tv_usec = prof_timer.it_interval.tv_usec = 1000; signal(SIGPROF, handle_sigprof_investigate_stattimer); setitimer(ITIMER_PROF, &prof_timer, NULL); #endif // There are some parts of llvm that are only configurable through command line args, // so construct a fake argc/argv pair and pass it to the llvm command line machinery: std::vector<const char*> llvm_args = { "fake_name" }; llvm_args.push_back("--enable-patchpoint-liveness"); if (0) { // Enabling and debugging fast-isel: // llvm_args.push_back("--fast-isel"); // llvm_args.push_back("--fast-isel-verbose"); ////llvm_args.push_back("--fast-isel-abort"); } #ifndef NDEBUG // llvm_args.push_back("--debug-only=debug-ir"); // llvm_args.push_back("--debug-only=regalloc"); // llvm_args.push_back("--debug-only=stackmaps"); #endif // llvm_args.push_back("--time-passes"); // llvm_args.push_back("--print-after-all"); // llvm_args.push_back("--print-machineinstrs"); if (USE_REGALLOC_BASIC) llvm_args.push_back("--regalloc=basic"); llvm::cl::ParseCommandLineOptions(llvm_args.size(), &llvm_args[0], "<you should never see this>\n"); }
char * dump_snmpEngineID(const u_char * estring, size_t * estring_len) { #define eb(b) ( *(esp+b) & 0xff ) int rval = SNMPERR_SUCCESS, gotviolation = 0, slen = 0; u_int remaining_len; char buf[SNMP_MAXBUF], *s = NULL, *t; const u_char *esp = estring; struct in_addr iaddr; /* * Sanity check. */ if (!estring || (*estring_len <= 0)) { QUITFUN(SNMPERR_GENERR, dump_snmpEngineID_quit); } remaining_len = *estring_len; memset(buf, 0, SNMP_MAXBUF); /* * Test first bit. Return immediately with a hex string, or * begin by formatting the enterprise ID. */ if (!(*esp & 0x80)) { snprint_hexstring(buf, SNMP_MAXBUF, esp, remaining_len); s = strchr(buf, '\0'); s -= 1; goto dump_snmpEngineID_quit; } s = buf; s += sprintf(s, "enterprise %d, ", ((*(esp + 0) & 0x7f) << 24) | ((*(esp + 1) & 0xff) << 16) | ((*(esp + 2) & 0xff) << 8) | ((*(esp + 3) & 0xff))); /* * XXX Ick. */ if (remaining_len < 5) { /* XXX Violating string. */ goto dump_snmpEngineID_quit; } esp += 4; /* Incremented one more in the switch below. */ remaining_len -= 5; /* * Act on the fifth byte. */ switch ((int) *esp++) { case 1: /* IPv4 address. */ if (remaining_len < 4) goto dump_snmpEngineID_violation; memcpy(&iaddr.s_addr, esp, 4); if (!(t = inet_ntoa(iaddr))) goto dump_snmpEngineID_violation; s += sprintf(s, "%s", t); esp += 4; remaining_len -= 4; break; case 2: /* IPv6 address. */ if (remaining_len < 16) goto dump_snmpEngineID_violation; s += sprintf(s, "%02X%02X %02X%02X %02X%02X %02X%02X::" "%02X%02X %02X%02X %02X%02X %02X%02X", eb(0), eb(1), eb(2), eb(3), eb(4), eb(5), eb(6), eb(7), eb(8), eb(9), eb(10), eb(11), eb(12), eb(13), eb(14), eb(15)); esp += 16; remaining_len -= 16; break; case 3: /* MAC address. */ if (remaining_len < 6) goto dump_snmpEngineID_violation; s += sprintf(s, "%02X:%02X:%02X:%02X:%02X:%02X", eb(0), eb(1), eb(2), eb(3), eb(4), eb(5)); esp += 6; remaining_len -= 6; break; case 4: /* Text. */ /* * Doesn't exist on all (many) architectures */ /* * s += snprintf(s, remaining_len+3, "\"%s\"", esp); */ s += sprintf(s, "\"%.*s\"", sizeof(buf)-strlen(buf)-3, esp); goto dump_snmpEngineID_quit; break; /*NOTREACHED*/ case 5: /* Octets. */ snprint_hexstring(s, (SNMP_MAXBUF - (s-buf)), esp, remaining_len); s = strchr(buf, '\0'); s -= 1; goto dump_snmpEngineID_quit; break; /*NOTREACHED*/ dump_snmpEngineID_violation: case 0: /* Violation of RESERVED, * * -OR- of expected length. */ gotviolation = 1; s += sprintf(s, "!!! "); default: /* Unknown encoding. */ if (!gotviolation) { s += sprintf(s, "??? "); } snprint_hexstring(s, (SNMP_MAXBUF - (s-buf)), esp, remaining_len); s = strchr(buf, '\0'); s -= 1; goto dump_snmpEngineID_quit; } /* endswitch */ /* * Cases 1-3 (IP and MAC addresses) should not have trailing * octets, but perhaps they do. Throw them in too. XXX */ if (remaining_len > 0) { s += sprintf(s, " (??? "); snprint_hexstring(s, (SNMP_MAXBUF - (s-buf)), esp, remaining_len); s = strchr(buf, '\0'); s -= 1; s += sprintf(s, ")"); } dump_snmpEngineID_quit: if (s) { slen = s - buf + 1; s = calloc(1, slen); memcpy(s, buf, (slen) - 1); } memset(buf, 0, SNMP_MAXBUF); /* XXX -- Overkill? XXX: Yes! */ return s; #undef eb } /* end dump_snmpEngineID() */
void initCodegen() { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); g.stdlib_module = loadStdlib(); llvm::EngineBuilder eb(new llvm::Module("empty_initial_module", g.context)); eb.setEngineKind(llvm::EngineKind::JIT); // specify we only want the JIT, and not the interpreter fallback eb.setUseMCJIT(true); eb.setMCJITMemoryManager(createMemoryManager()); // eb.setOptLevel(llvm::CodeGenOpt::None); // -O0 // eb.setOptLevel(llvm::CodeGenOpt::Less); // -O1 // eb.setOptLevel(llvm::CodeGenOpt::Default); // -O2, -Os // eb.setOptLevel(llvm::CodeGenOpt::Aggressive); // -O3 llvm::TargetOptions target_options; target_options.NoFramePointerElim = true; // target_options.EnableFastISel = true; eb.setTargetOptions(target_options); g.tm = eb.selectTarget(); assert(g.tm && "failed to get a target machine"); g.engine = eb.create(g.tm); assert(g.engine && "engine creation failed?"); // g.engine->setObjectCache(new MyObjectCache()); g.i1 = llvm::Type::getInt1Ty(g.context); g.i8 = llvm::Type::getInt8Ty(g.context); g.i8_ptr = g.i8->getPointerTo(); g.i32 = llvm::Type::getInt32Ty(g.context); g.i64 = llvm::Type::getInt64Ty(g.context); g.void_ = llvm::Type::getVoidTy(g.context); g.double_ = llvm::Type::getDoubleTy(g.context); std::vector<llvm::JITEventListener*> listeners = makeJITEventListeners(); for (int i = 0; i < listeners.size(); i++) { g.jit_listeners.push_back(listeners[i]); g.engine->RegisterJITEventListener(listeners[i]); } llvm::JITEventListener* stackmap_listener = makeStackMapListener(); g.jit_listeners.push_back(stackmap_listener); g.engine->RegisterJITEventListener(stackmap_listener); llvm::JITEventListener* registry_listener = makeRegistryListener(); g.jit_listeners.push_back(registry_listener); g.engine->RegisterJITEventListener(registry_listener); llvm::JITEventListener* tracebacks_listener = makeTracebacksListener(); g.jit_listeners.push_back(tracebacks_listener); g.engine->RegisterJITEventListener(tracebacks_listener); if (SHOW_DISASM) { llvm::JITEventListener* listener = new PystonJITEventListener(); g.jit_listeners.push_back(listener); g.engine->RegisterJITEventListener(listener); } initGlobalFuncs(g); setupRuntime(); signal(SIGFPE, &handle_sigfpe); // There are some parts of llvm that are only configurable through command line args, // so construct a fake argc/argv pair and pass it to the llvm command line machinery: const char* llvm_args[] = { "fake_name", "--enable-stackmap-liveness", "--enable-patchpoint-liveness", // Enabling and debugging fast-isel: //"--fast-isel", //"--fast-isel-verbose", ////"--fast-isel-abort", #ifndef NDEBUG //"--debug-only=debug-ir", //"--debug-only=regalloc", //"--debug-only=stackmaps", #endif //"--print-after-all", //"--print-machineinstrs", }; int num_llvm_args = sizeof(llvm_args) / sizeof(llvm_args[0]); llvm::cl::ParseCommandLineOptions(num_llvm_args, llvm_args, "<you should never see this>\n"); }