Beispiel #1
0
void FW(Graph<int, int> & g){
    
    int V = (int)g.getVertices()->size();
    
    int ** dist = Helper::buildMatrix<int>(V, V);
    for (int i = 0; i < V; ++i) {
        for (int j = 0; j < V; ++j) {
            if (i == j) dist[i][j] = 0;
            else dist[i][j] = 1000;
        }
    }
    
    for (int i = 0; i < (int)g.getEdges()->size(); ++i) {
        Edge<int, int> * e = g.getEdgeAt(i);
        int origin = *(e->getOrigin()->getInfo());
        int destination = *(e->getDestination()->getInfo());
        dist[origin - 1][destination - 1] = *e->getInfo();
    }
    for (int k = 0; k < V; ++k) {
        PM(dist, V, V);
        for (int i = 0; i < V; ++i) {
            for (int j = 0; j < V; ++j) {                    if (dist[i][k] + dist[k][j] < dist[i][j]) {
                    dist[i][j] = dist[i][k] + dist[k][j];
                }
            }
        }
    }
    PM(dist, V, V);
}
Beispiel #2
0
std::pair<MayMustMap, std::set<llvm::GlobalVariable*> > getMayMustMap(llvm::Function *function)
{
    llvm::Module *module = function->getParent();

#if LLVM_VERSION < VERSION(3, 2)
    llvm::TargetData *TD = NULL;
#elif LLVM_VERSION < VERSION(3, 5)
    llvm::DataLayout *TD = NULL;
#elif LLVM_VERSION < VERSION(3, 7)
    llvm::DataLayoutPass *TD = NULL;
#endif
#if LLVM_VERSION < VERSION(3, 5)
    const std::string &ModuleDataLayout = module->getDataLayout();
#elif LLVM_VERSION == VERSION(3, 5)
    const std::string &ModuleDataLayout = module->getDataLayout()->getStringRepresentation();
#endif
#if LLVM_VERSION < VERSION(3, 2)
    if (!ModuleDataLayout.empty()) {
        TD = new llvm::TargetData(ModuleDataLayout);
    }
#elif LLVM_VERSION < VERSION(3, 5)
    if (!ModuleDataLayout.empty()) {
        TD = new llvm::DataLayout(ModuleDataLayout);
    }
#elif LLVM_VERSION == VERSION(3, 5)
    if (!ModuleDataLayout.empty()) {
        TD = new llvm::DataLayoutPass(llvm::DataLayout(ModuleDataLayout));
    }
#elif LLVM_VERSION < VERSION(3, 7)
    TD = new llvm::DataLayoutPass();
#endif

    // pass manager
#if LLVM_VERSION < VERSION(3, 7)
    llvm::FunctionPassManager PM(module);
#else
    llvm::legacy::FunctionPassManager PM(module);
#endif

#if LLVM_VERSION < VERSION(3, 7)
    if (TD != NULL) {
        PM.add(TD);
    }
#endif

#if LLVM_VERSION < VERSION(3, 8)
    PM.add(llvm::createBasicAliasAnalysisPass());
#else
    PM.add(llvm::createBasicAAWrapperPass());
#endif

    MemoryAnalyzer *maPass = createMemoryAnalyzerPass();
    PM.add(maPass);

    PM.run(*function);

    return std::make_pair(maPass->getMayMustMap(), maPass->getMayZap());
}
void
reboot ()
{
	int rstc;

	rstc = PM(RSTC);
	PM(WDOG) = PASSWORD | (10 & WDOG_TIME_SET);
	PM(RSTC) = PASSWORD | (rstc & RSTC_WRCFG_CLR) | RSTC_WRCFG_FULL_RESET;
}
void measurement_overhead() {
    printf("Measurement, 0, 0\n");

    PM("","RDTSC, "O_STR);

    #define FOR_MEAS for (int k = 0; k < 100; ++k) { ; }
    double m; uint64_t med, se, min, max;
    measure(FOR_MEAS,m,med,se,min,max,10000);
    printf("Loop, "O_STR, m/100, med/100, se/100, min/100, max/100);

    printf("Function Calls, 0, 0\n");

    PM_COUNT(p0(), "p0, "O_STR,1000000);

    PM_COUNT(p1(1), "p1, "O_STR,1000000);

    PM_COUNT(p2(1,2), "p2, "O_STR,1000000);

    PM_COUNT(p3(1,2,3), "p3, "O_STR,1000000);

    PM_COUNT(p4(1,2,3,4), "p4, "O_STR,1000000);

    PM_COUNT(p5(1,2,3,4,5), "p5, "O_STR,1000000);

    PM_COUNT(p6(1,2,3,4,5,6), "p6, "O_STR,1000000);

    PM_COUNT(p7(1,2,3,4,5,6,7), "p7, "O_STR,1000000);
}
Beispiel #5
0
TrueFalseMap getConditionPropagationMap(llvm::Function *function, std::set<llvm::BasicBlock*> lcbs)
{
    llvm::Module *module = function->getParent();

    // pass manager
#if LLVM_VERSION < VERSION(3, 7)
    llvm::FunctionPassManager PM(module);
#else
    llvm::legacy::FunctionPassManager PM(module);
#endif

    ConditionPropagator *cpPass = createConditionPropagatorPass(debug, onlyLoopConditions, lcbs);
    PM.add(cpPass);

    PM.run(*function);

    return cpPass->getTrueFalseMap();
}
Beispiel #6
0
ConditionMap getExplicitizedLoopConditionMap(llvm::Function *function)
{
    llvm::Module *module = function->getParent();

    // pass manager
#if LLVM_VERSION < VERSION(3, 7)
    llvm::FunctionPassManager PM(module);
#else
    llvm::legacy::FunctionPassManager PM(module);
#endif

    LoopConditionExplicitizer *lcePass = createLoopConditionExplicitizerPass(debug);
    PM.add(lcePass);

    PM.run(*function);

    return lcePass->getConditionMap();
}
Beispiel #7
0
std::set<llvm::BasicBlock*> getLoopConditionBlocks(llvm::Function *function)
{
    llvm::Module *module = function->getParent();

    // pass manager
#if LLVM_VERSION < VERSION(3, 7)
    llvm::FunctionPassManager PM(module);
#else
    llvm::legacy::FunctionPassManager PM(module);
#endif

    LoopConditionBlocksCollector *lcbPass = createLoopConditionBlocksCollectorPass();
    PM.add(lcbPass);

    PM.run(*function);

    return lcbPass->getLoopConditionBlocks();
}
Beispiel #8
0
static void NotebookTabElementGeometry(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    int *widthPtr, int *heightPtr, Ttk_Padding *paddingPtr)
{
    if (qApp == NULL) NULL_Q_APP;
    NULL_PROXY_WIDGET(TileQt_QTabBar_Widget);
    Tcl_MutexLock(&tileqtMutex);
#ifdef TILEQT_QT_VERSION_4
    QStyleOptionTab option;
    option.initFrom(wc->TileQt_QTabBar_Widget);
#endif /* TILEQT_QT_VERSION_4 */
    int PM_TabBarTabVSpace          = PM(PM_TabBarTabVSpace),
        PM_TabBarTabHSpace          = PM(PM_TabBarTabHSpace);
    Tcl_MutexUnlock(&tileqtMutex);
    *paddingPtr = Ttk_MakePadding(
           PM_TabBarTabHSpace/2,
#ifdef TILEQT_QT_VERSION_4
           PM_TabBarTabVSpace,
           PM_TabBarTabHSpace/2,
           0
#endif /* TILEQT_QT_VERSION_4 */
           );
}
Beispiel #9
0
void gpio_init(gpio_t *obj, PinName pin) {
    int group ;
    obj->pin = pin;
    if(pin == NC) return;
    
    obj->mask = gpio_set(pin);

    group = PINGROUP(pin);
    if (group > 11) return;

    obj->reg_set = (volatile uint32_t *)PORT(group);
    obj->reg_in  = (volatile uint32_t *) PPR(group);
    obj->reg_dir = (volatile uint32_t *)  PM(group);
    obj->reg_buf = (volatile uint32_t *)PIBC(group);
}
Beispiel #10
0
static void
init_uart0 ()
{
  initted = 1;

  PER0 = 0xff;
  SPS0 = 0x0011; /* 16 MHz */
  SMR00 = 0x0022; /* uart mode */
  SCR00 = 0x8097; /* 8-N-1 */
  SDR00 = 0x8a00; /* baud in MSB - 115200 */
  SOL0 = 0x0000; /* not inverted */
  SO0 = 0x000f; /* initial value */
  SOE0 = 0x0001; /* enable TxD0 */
  P(1)  |= 0b00000100;
  PM(1) &= 0b11111011;
  SS0 = 0x0001;
}
Beispiel #11
0
EXTRADECLS
#endif

/*****************************************************************************
*                                                                            *
*  This is a program which illustrates the use of nauty.                     *
*  Commands are read from stdin, and may be separated by white space,        *
*  commas or not separated.  Output is written to stdout.                    *
*  For a short description, see the nauty User's Guide.                      *
*                                                                            *
*****************************************************************************/

main()
{
        int m,n,newm,newn;
        boolean gvalid,ovalid,cvalid,pvalid,minus,prompt,doquot;
        int i,worksize,numcells,refcode,umask,qinvar;
        int oldorg;
        char *s1,*s2,*invarprocname;
        int c,d;
        register long li;
        set *gp;
        double timebefore,timeafter;
        char filename[100];
        graph *savedg;
        nvector *savedlab;
        int sgn,sgactn,sgorg;
        int cgactn,gactn;

        curfile = 0;
        fileptr[curfile] = stdin;
        prompt = DOPROMPT(INFILE);
        outfile = stdout;
        n = m = 1;

#ifdef  INITSEED
        INITSEED;
#endif

        umask = 0;
        pvalid = FALSE;
        gvalid = FALSE;
        ovalid = FALSE;
        cvalid = FALSE;
        minus = FALSE;
        worksize = 2*MAXM*WORKSIZE;
        labelorg = oldorg = 0;
        cgactn = sgactn = gactn = 0;

#ifdef  DYNALLOC
        workspace = (setword*) ALLOCS(WORKSIZE,2*MAXM*sizeof(setword));
        ptn = (nvector*) ALLOCS(MAXN,sizeof(nvector));
        orbits = (nvector*) ALLOCS(MAXN,sizeof(nvector));
        perm = (permutation*) ALLOCS(MAXN,sizeof(permutation));

        if (workspace == NILSET || ptn == (nvector*)NULL ||
                orbits == (nvector*)NULL || perm == (permutation*)NULL)
        {
            fprintf(ERRFILE,"ALLOCS failed; reduce MAXN.\n\n");
            EXIT;
        }
#endif

#ifdef  INITIALIZE
        INITIALIZE;
#endif

        allocg(&g,&lab,&gactn,n);
        if (gactn == 0)
        {
            fprintf(ERRFILE,"ALLOCS failed for g: this shouldn't happen.\n\n");
            EXIT;
        }

        invarprocname = "none";
        if (prompt)
        {
            fprintf(PROMPTFILE,"Dreadnaut version %s.\n",DREADVERSION);
            fprintf(PROMPTFILE,"> ");
        }

     /* Calling dummy routines in nautinv.c, nauty.c and nautil.c causes
        those segments to get loaded in various Macintosh variants.  This
        causes an apparent, but illusory, improvement in the time required
        for the first call to nauty().   */

        nautinv_null();
        nautil_null();
        nauty_null();

        while (curfile >= 0)
            if ((c = getc(INFILE)) == EOF || c == '\004')
            {
                fclose(INFILE);
                --curfile;
                if (curfile >= 0)
                    prompt = DOPROMPT(INFILE);
            }
            else switch (c)
            {
            case '\n':  /* possibly issue prompt */
                if (prompt)
                    fprintf(PROMPTFILE,"> ");
                minus = FALSE;
                break;

            case ' ':   /* do nothing */
            case '\t':
#ifndef  NLMAP
            case '\r':
#endif
            case '\f':
                break;

            case '-':   /* remember this for next time */
                minus = TRUE;
                break;

            case '+':   /* forget - */
            case ',':
            case ';':
                minus = FALSE;
                break;

            case '<':   /* new input file */
                minus = FALSE;
                if (curfile == MAXIFILES - 1)
                    fprintf(ERRFILE,"exceeded maximum input nesting of %d\n\n",
                            MAXIFILES);
                if (!readstring(INFILE,filename))
                {
                    fprintf(ERRFILE,
                            "missing file name on '>' command : ignored\n\n");
                    break;
                }
                if ((fileptr[curfile+1] = fopen(filename,"r")) == NULL)
                {
                    for (s1 = filename; *s1 != '\0'; ++s1) {}
                    for (s2 = def_ext; (*s1 = *s2) != '\0'; ++s1, ++s2) {}
                    fileptr[curfile+1] = fopen(filename,"r");
                }
                if (fileptr[curfile+1] != NULL)
                {
                    ++curfile;
                    prompt = DOPROMPT(INFILE);
                    if (prompt)
                        fprintf(PROMPTFILE,"> ");
                }
                else
                    fprintf(ERRFILE,"can't open input file\n\n");
                break;

            case '>':   /* new output file */
                if ((d = getc(INFILE)) != '>')
                    ungetc((char)d,INFILE);
                if (minus)
                {
                    minus = FALSE;
                    if (outfile != stdout)
                    {
                        fclose(outfile);
                        outfile = stdout;
                    }
                }
                else
                {
                    if (!readstring(INFILE,filename))
                    {
                        fprintf(ERRFILE,
                            "improper file name, reverting to stdout\n\n");
                        outfile = stdout;
                        break;
                    }
                    OPENOUT(outfile,filename,d=='>');
                    if (outfile == NULL)
                    {
                        fprintf(ERRFILE,
                            "can't open output file, reverting to stdout\n\n");
                        outfile = stdout;
                    }
                }
                break;

            case '!':   /* ignore rest of line */
                do
                    c = getc(INFILE);
                while (c != '\n' && c != EOF);
                if (c == '\n')
                    ungetc('\n',INFILE);
                break;

            case 'n':   /* read n value */
                minus = FALSE;
                i = getint(INFILE);
                if (i <= 0 || i > MAXN)
                    fprintf(ERRFILE,
                         " n can't be less than 1 or more than %d\n\n",MAXN);
                else
                {
                    gvalid = FALSE;
                    ovalid = FALSE;
                    cvalid = FALSE;
                    pvalid = FALSE;
                    n = i;
                    m = (n + WORDSIZE - 1) / WORDSIZE;
                    allocg(&g,&lab,&gactn,n);
                    if (gactn == 0)
                    {
                        fprintf(ERRFILE,"can't allocate space for graph\n");
                        n = m = 1;
                        break;
                    }
                }
                break;

            case 'g':   /* read graph */
                minus = FALSE;
                readgraph(INFILE,g,options.digraph,prompt,FALSE,
                          options.linelength,m,n);
                gvalid = TRUE;
                cvalid = FALSE;
                ovalid = FALSE;
                break;

            case 'e':   /* edit graph */
                minus = FALSE;
                readgraph(INFILE,g,options.digraph,prompt,gvalid,
                          options.linelength,m,n);
                gvalid = TRUE;
                cvalid = FALSE;
                ovalid = FALSE;
                break;

            case 'r':   /* relabel graph and current partition */
                minus = FALSE;
                if (gvalid)
                {
                    allocg(&canong,(nvector**)NULL,&cgactn,n);
                    if (cgactn == 0)
                    {
                        fprintf(ERRFILE,
                                "can't allocate work space for 'r'\n\n");
                        break;
                    }
                    readperm(INFILE,perm,prompt,n);
                    relabel(g,(pvalid ? lab : (nvector*)NULL),perm,canong,m,n);
                    cvalid = FALSE;
                    ovalid = FALSE;
                }
                else
                    fprintf(ERRFILE,"g is not defined\n\n");
                break;

            case '_':   /* complement graph */
                minus = FALSE;
                if (gvalid)
                {
                    complement(g,m,n);
                    cvalid = FALSE;
                    ovalid = FALSE;
                }
                else
                    fprintf(ERRFILE,"g is not defined\n\n");
                break;

            case '@':   /* copy canong into savedg */
                minus = FALSE;
                if (cvalid)
                {
                    allocg(&savedg,&savedlab,&sgactn,n);
                    if (sgactn == 0)
                    {
                        fprintf(ERRFILE,"can`t allocate space for h'\n\n");
                        break;
                    }
                    sgn = n;
                    for (li = (long)n * (long)m; --li >= 0;)
                        savedg[li] = canong[li];
                    for (i = n; --i >= 0;)
                        savedlab[i] = lab[i];
                    sgorg = labelorg;
                }
                else
                    fprintf(ERRFILE,"h is not defined\n\n");
                break;

            case '#':   /* compare canong to savedg */
                if ((d = getc(INFILE)) != '#')
                    ungetc((char)d,INFILE);

                if (cvalid)
                {
                    if (sgactn > 0)
                    {
                        if (sgn != n)
                            fprintf(OUTFILE,
                                  "h and h' have different sizes.\n");
                        else
                        {
                            for (li = (long)n * (long)m; --li >= 0;)
                                if (savedg[li] != canong[li])
                                    break;
                            if (li >= 0)
                                fprintf(OUTFILE,
                                   "h and h' are different.\n");
                            else
                            {
                                fprintf(OUTFILE,
                                   "h and h' are identical.\n");
                                if (d == '#')
                                    putmapping(OUTFILE,savedlab,sgorg,
                                           lab,labelorg,options.linelength,n);
                            }
                        }
                    }
                    else
                        fprintf(ERRFILE,"h' is not defined\n\n");
                }
                else
                    fprintf(ERRFILE,"h is not defined\n\n");
                break;

            case 'j':   /* relabel graph randomly */
                minus = FALSE;
                if (gvalid)
                {
                    allocg(&canong,(nvector**)NULL,&cgactn,n);
                    if (cgactn == 0)
                    {
                        fprintf(ERRFILE,
                                "can't allocate work space for 'j'\n\n");
                        break;
                    }
                    ranperm(perm,n);
                    relabel(g,(pvalid ? lab : (nvector*)NULL),perm,canong,m,n);
                    cvalid = FALSE;
                    ovalid = FALSE;
                }
                else
                    fprintf(ERRFILE,"g is not defined\n\n");
                break;

            case 'v':   /* write vertex degrees */
                minus = FALSE;
                if (gvalid)
                    putdegs(OUTFILE,g,options.linelength,m,n);
                else
                    fprintf(ERRFILE,"g is not defined\n\n");
                break;

            case '%':   /* do Mathon doubling operation */
                minus = FALSE;
                if (gvalid)
                {
                    if (2L * ((long)n + 1L) > MAXN)
                    {
                        fprintf(ERRFILE,"n can't be more than %d\n\n",MAXN);
                        break;
                    }
                    newn = 2 * (n + 1);
                    newm = (newn + WORDSIZE - 1) / WORDSIZE;
                    allocg(&canong,(nvector**)NULL,&cgactn,n);
                    if (cgactn == 0)
                    {
                        fprintf(ERRFILE,
                                "can't allocate work space for '%'\n\n");
                        break;
                    }

                    for (li = (long)n * (long)m; --li >= 0;)
                        canong[li] = g[li];

                    allocg(&g,&lab,&gactn,newn);
                    if (gactn == 0)
                    {
                        fprintf(ERRFILE,"can't allocate space for graph \n\n");
                        break;
                    }
                    mathon(canong,m,n,g,newm,newn);
                    m = newm;
                    n = newn;
                    cvalid = FALSE;
                    ovalid = FALSE;
                    pvalid = FALSE;
                }
                else
                    fprintf(ERRFILE,"g is not defined\n\n");
                break;

            case 's':   /* generate random graph */
                minus = FALSE;
                i = getint(INFILE);
                if (i <= 0)
                    i = 2;
                rangraph(g,options.digraph,i,m,n);
                gvalid = TRUE;
                cvalid = FALSE;
                ovalid = FALSE;
                break;

            case 'q':   /* quit */
                EXIT;
                break;

            case '"':   /* copy comment to output */
                minus = FALSE;
                copycomment(INFILE,OUTFILE,'"');
                break;

            case 'I':   /* do refinement and invariants procedure */
                if (!pvalid)
                    unitptn(lab,ptn,&numcells,n);
                cellstarts(ptn,0,active,m,n);
#ifdef  CPUTIME
                timebefore = CPUTIME;
#endif
                doref(g,lab,ptn,0,&numcells,&qinvar,perm,active,&refcode,
                      refine,options.invarproc,
                      0,0,options.invararg,options.digraph,m,n);
#ifdef  CPUTIME
                timeafter = CPUTIME;
#endif
                fprintf(OUTFILE," %d cell%s; code = %x",
                        SS(numcells,"","s"),refcode);
                if (options.invarproc != NILFUNCTION)
                    fprintf(OUTFILE," (%s %s)",invarprocname,
                        (qinvar == 2 ? "worked" : "failed"));
#ifdef  CPUTIME
                fprintf(OUTFILE,"; cpu time = %.2f seconds\n",
                        timeafter-timebefore);
#else
                fprintf(OUTFILE,"\n");
#endif
                if (numcells > 1)
                    pvalid = TRUE;
                break;

            case 'i':   /* do refinement */
                if (!pvalid)
                    unitptn(lab,ptn,&numcells,n);
                cellstarts(ptn,0,active,m,n);
                if (m == 1)
                    refine1(g,lab,ptn,0,&numcells,perm,active,&refcode,m,n);
                else
                    refine(g,lab,ptn,0,&numcells,perm,active,&refcode,m,n);
                fprintf(OUTFILE," %d cell%s; code = %x\n",
                        SS(numcells,"","s"),refcode);
                if (numcells > 1)
                    pvalid = TRUE;
                break;

            case 'x':   /* execute nauty */
                minus = FALSE;
                ovalid = FALSE;
                cvalid = FALSE;
                if (!gvalid)
                {
                    fprintf(ERRFILE,"g is not defined\n\n");
                    break;
                }
                if (pvalid)
                {
                    fprintf(OUTFILE,"[fixing partition]\n");
                    options.defaultptn = FALSE;
                }
                else
                    options.defaultptn = TRUE;
                options.outfile = outfile;

                if (options.getcanon)
                {
                    allocg(&canong,(nvector**)NULL,&cgactn,n);
                    if (cgactn == 0)
                    {
                        fprintf(ERRFILE,"can't allocate space for h\n\n");
                        break;
                    }
                }

                firstpath = TRUE;
#ifdef  CPUTIME
                timebefore = CPUTIME;
#endif
                nauty(g,lab,ptn,NILSET,orbits,&options,&stats,workspace,
                      worksize,m,n,canong);
#ifdef  CPUTIME
                timeafter = CPUTIME;
#endif
                if (stats.errstatus != 0)
                    fprintf(ERRFILE,
                      "nauty returned error status %d [this can't happen]\n\n",
                       stats.errstatus);
                else
                {
                    if (options.getcanon)
                        cvalid = TRUE;
                    ovalid = TRUE;
                    fprintf(OUTFILE,"%d orbit%s",SS(stats.numorbits,"","s"));
                    if (stats.grpsize2 == 0)
                        fprintf(OUTFILE,"; grpsize=%.0f",stats.grpsize1+0.1);
                    else
                    {
                        while (stats.grpsize1 >= 10.0)
                        {
                            stats.grpsize1 /= 10.0;
                            ++stats.grpsize2;
                        }
                        fprintf(OUTFILE,"; grpsize=%12.10fe%d",
                                   stats.grpsize1,stats.grpsize2);
                    }
                    fprintf(OUTFILE,"; %d gen%s",
                            SS(stats.numgenerators,"","s"));
                    fprintf(OUTFILE,"; %ld node%s",SS(stats.numnodes,"","s"));
                    if (stats.numbadleaves)
                        fprintf(OUTFILE," (%ld bad lea%s)",
                                SS(stats.numbadleaves,"f","ves"));
                    fprintf(OUTFILE,"; maxlev=%d\n", stats.maxlevel);
                    fprintf(OUTFILE,"tctotal=%ld",stats.tctotal);
                    if (options.getcanon)
                        fprintf(OUTFILE,"; canupdates=%ld",stats.canupdates);
#ifdef  CPUTIME
                    fprintf(OUTFILE,"; cpu time = %.2f seconds\n",
                            timeafter-timebefore);
#else
                    fprintf(OUTFILE,"\n");
#endif
                    if (options.invarproc != NILFUNCTION &&
                                           options.maxinvarlevel != 0)
                    {
                        fprintf(OUTFILE,"invarproc \"%s\" succeeded %ld/%ld",
                            invarprocname,stats.invsuccesses,stats.invapplics);
                        if (stats.invarsuclevel > 0)
                            fprintf(OUTFILE," beginning at level %d.\n",
                                    stats.invarsuclevel);
                        else
                            fprintf(OUTFILE,".\n");
                    }
                }
                break;

            case 'f':   /* read initial partition */
                if (minus)
                {
                    pvalid = FALSE;
                    minus = FALSE;
                }
                else
                {
                    readptn(INFILE,lab,ptn,&numcells,prompt,n);
                    pvalid = TRUE;
                }
                break;

            case 't':   /* type graph */
                minus = FALSE;
                if (!gvalid)
                    fprintf(ERRFILE,"g is not defined\n\n");
                else
                    putgraph(OUTFILE,g,options.linelength,m,n);
                break;

            case 'T':   /* type graph preceded by n, $ and g commands */
                minus = FALSE;
                if (!gvalid)
                    fprintf(ERRFILE,"g is not defined\n\n");
                else
                {
                    fprintf(OUTFILE,"n=%d $=%d g\n",n,labelorg);
                    putgraph(OUTFILE,g,options.linelength,m,n);
                    fprintf(OUTFILE,"$$\n");
                }
                break;

            case 'u':   /* call user procs */
                if (minus)
                {
                    umask = 0;
                    minus = FALSE;
                }
                else
                {
                    umask = getint(INFILE);
                    if (umask < 0)
                        umask = ~0;
                }
                if (umask & U_NODE)
                    options.usernodeproc = NODEPROC;
                else
                    options.usernodeproc = NILFUNCTION;
                if (umask & U_AUTOM)
                    options.userautomproc = AUTOMPROC;
                else
                    options.userautomproc = NILFUNCTION;
                if (umask & U_LEVEL)
                    options.userlevelproc = LEVELPROC;
                else
                    options.userlevelproc = NILFUNCTION;
                if (umask & U_TCELL)
                    options.usertcellproc = TCELLPROC;
                else
                    options.usertcellproc = NILFUNCTION;
                if (umask & U_REF)
                    options.userrefproc = REFPROC;
                else
                    options.userrefproc = NILFUNCTION;
                break;

            case 'o':   /* type orbits */
                minus = FALSE;
                if (ovalid)
                    putorbits(OUTFILE,orbits,options.linelength,n);
                else
                    fprintf(ERRFILE,"orbits are not defined\n\n");
                break;

            case 'b':   /* type canonlab and canong */
                minus = FALSE;
                if (cvalid)
                    putcanon(OUTFILE,lab,canong,options.linelength,m,n);
                else
                    fprintf(ERRFILE,"h is not defined\n\n");
                break;

            case 'z':   /* type hashcode for canong */
                minus = FALSE;
                if (cvalid)
                    fprintf(OUTFILE,"[%8lx %8lx]\n",
                                    hash(canong,(long)m * (long)n,13),
                                    hash(canong,(long)m * (long)n,7));
                else
                    fprintf(ERRFILE,"h is not defined\n\n");
                break;

            case 'c':   /* set getcanon option */
                options.getcanon = !minus;
                minus = FALSE;
                break;

            case 'w':   /* read size of workspace */
                minus = FALSE;
                worksize = getint(INFILE);
                if (worksize > 2*MAXM*WORKSIZE)
                {
                    fprintf(ERRFILE,
                       "too big - setting worksize = %d\n\n", 2*MAXM*WORKSIZE);
                    worksize = 2*MAXM*WORKSIZE;
                }
                break;

            case 'l':   /* read linelength for output */
                options.linelength = getint(INFILE);
                minus = FALSE;
                break;

            case 'y':   /* set tc_level field of options */
                options.tc_level = getint(INFILE);
                minus = FALSE;
                break;

            case 'k':   /* set invarlev fields of options */
                options.mininvarlevel = getint(INFILE);
                options.maxinvarlevel = getint(INFILE);
                minus = FALSE;
                break;

            case 'K':   /* set invararg field of options */
                options.invararg = getint(INFILE);
                minus = FALSE;
                break;

            case '*':   /* set invarproc field of options */
                minus = FALSE;
                d = getint(INFILE);
                if (d >= -1 && d <= NUMINVARS-2)
                {
                    options.invarproc = invarproc[d+1].entrypoint;
                    invarprocname = invarproc[d+1].name;
                }
                else
                    fprintf(ERRFILE,"no such vertex-invariant\n\n");
                break;

            case 'a':   /* set writeautoms option */
                options.writeautoms = !minus;
                minus = FALSE;
                break;

            case 'm':   /* set writemarkers option */
                options.writemarkers = !minus;
                minus = FALSE;
                break;

            case 'p':   /* set cartesian option */
                options.cartesian = !minus;
                minus = FALSE;
                break;

            case 'd':   /* set digraph option */
                if (options.digraph && minus)
                    gvalid = FALSE;
                options.digraph = !minus;
                minus = FALSE;
                break;

            case '$':   /* set label origin */
                if ((d = getc(INFILE)) == '$')
                    labelorg = oldorg;
                else
                {
                    ungetc((char)d,INFILE);
                    oldorg = labelorg;
                    i = getint(INFILE);
                    if (i < 0)
                        fprintf(ERRFILE,"labelorg must be >= 0\n\n");
                    else
                        labelorg = i;
                }
                break;

            case '?':   /* type options, etc. */
                minus = FALSE;
                fprintf(OUTFILE,"m=%d n=%d labelorg=%d",m,n,labelorg);
                if (!gvalid)
                    fprintf(OUTFILE," g=undef");
                else
                {
                    li = 0;
                    for (i = 0, gp = g; i < n; ++i, gp += m)
                        li += setsize(gp,m);
                    if (options.digraph)
                        fprintf(OUTFILE," arcs=%ld",li);
                    else
                        fprintf(OUTFILE," edges=%ld",li/2);
                }
                fprintf(OUTFILE," options=(%cc%ca%cm%cp%cd",
                            PM(options.getcanon),PM(options.writeautoms),
                            PM(options.writemarkers),PM(options.cartesian),
                            PM(options.digraph));
                if (umask & 31)
                    fprintf(OUTFILE," u=%d",umask&31);
                if (options.tc_level > 0)
                    fprintf(OUTFILE," y=%d",options.tc_level);
                if (options.mininvarlevel != 0 || options.maxinvarlevel != 0)
                    fprintf(OUTFILE," k=(%d,%d)",
                                  options.mininvarlevel,options.maxinvarlevel);
                if (options.invararg > 0)
                    fprintf(OUTFILE," K=%d",options.invararg);
                fprintf(OUTFILE,")\n");
                fprintf(OUTFILE,"linelen=%d worksize=%d input_depth=%d",
                                options.linelength,worksize,curfile);
                if (options.invarproc != NILFUNCTION)
                    fprintf(OUTFILE," invarproc=%s",invarprocname);
                if (pvalid)
                    fprintf(OUTFILE,"; %d cell%s",SS(numcells,"","s"));
                else
                    fprintf(OUTFILE,"; 1 cell");
                fprintf(OUTFILE,"\n");
                if (OUTFILE != PROMPTFILE)
                    fprintf(PROMPTFILE,"m=%d n=%d depth=%d labelorg=%d\n",
                            m,n,curfile,labelorg);
                break;

            case '&':   /* list the partition and possibly the quotient */
                if ((d = getc(INFILE)) == '&')
                    doquot = TRUE;
                else
                {
                    ungetc((char)d,INFILE);
                    doquot = FALSE;
                }
                minus = FALSE;
                if (pvalid)
                    putptn(OUTFILE,lab,ptn,0,options.linelength,n);
                else
                    fprintf(OUTFILE,"unit partition\n");
                if (doquot)
                {
                    if (!pvalid)
                        unitptn(lab,ptn,&numcells,n);
                    putquotient(OUTFILE,g,lab,ptn,0,options.linelength,m,n);
                }
                break;

            case 'h':   /* type help information */
                minus = FALSE;
                help(PROMPTFILE);
                break;

            default:    /* illegal command */
                fprintf(ERRFILE,"'%c' is illegal - type 'h' for help\n\n",c);
                flushline(INFILE);
                if (prompt)
                    fprintf(PROMPTFILE,"> ");
                break;

            }  /* end of switch */
}
int initOgreAR(aruco::CameraParameters camParams, unsigned char* buffer, std::string resourcePath)
{
    
    /// INIT OGRE FUNCTIONS
    root = new Ogre::Root(resourcePath + "plugins.cfg", resourcePath + "ogre.cfg");
    if (!root->showConfigDialog()) return -1;
    Ogre::SceneManager* smgr = root->createSceneManager(Ogre::ST_GENERIC);
    
    
    /// CREATE WINDOW, CAMERA AND VIEWPORT
    Ogre::RenderWindow* window = root->initialise(true);
    Ogre::Camera *camera;
    Ogre::SceneNode* cameraNode;
    camera = smgr->createCamera("camera");
    camera->setNearClipDistance(0.01f);
    camera->setFarClipDistance(10.0f);
    camera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
    camera->setPosition(0, 0, 0);
    camera->lookAt(0, 0, 1);
    double pMatrix[16];
    camParams.OgreGetProjectionMatrix(camParams.CamSize,camParams.CamSize, pMatrix, 0.05,10, false);
    Ogre::Matrix4 PM(pMatrix[0], pMatrix[1], pMatrix[2] , pMatrix[3],
    pMatrix[4], pMatrix[5], pMatrix[6] , pMatrix[7],
    pMatrix[8], pMatrix[9], pMatrix[10], pMatrix[11],
    pMatrix[12], pMatrix[13], pMatrix[14], pMatrix[15]);
    camera->setCustomProjectionMatrix(true, PM);
    camera->setCustomViewMatrix(true, Ogre::Matrix4::IDENTITY);
    window->addViewport(camera);
    cameraNode = smgr->getRootSceneNode()->createChildSceneNode("cameraNode");
    cameraNode->attachObject(camera);
    
    
    /// CREATE BACKGROUND FROM CAMERA IMAGE
    int width = camParams.CamSize.width;
    int height = camParams.CamSize.height;
    // create background camera image
    mPixelBox = Ogre::PixelBox(width, height, 1, Ogre::PF_R8G8B8, buffer);
    // Create Texture
    mTexture = Ogre::TextureManager::getSingleton().createManual("CameraTexture",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
    Ogre::TEX_TYPE_2D,width,height,0,Ogre::PF_R8G8B8,Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);
    
    //Create Camera Material
    Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("CameraMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    Ogre::Technique *technique = material->createTechnique();
    technique->createPass();
    material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
    material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
    material->getTechnique(0)->getPass(0)->createTextureUnitState("CameraTexture");
    
    Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true);
    rect->setCorners(-1.0, 1.0, 1.0, -1.0);
    rect->setMaterial("CameraMaterial");
    
    // Render the background before everything else
    rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND);
    
    // Hacky, but we need to set the bounding box to something big, use infinite AAB to always stay visible
    Ogre::AxisAlignedBox aabInf;
    aabInf.setInfinite();
    rect->setBoundingBox(aabInf);
    
    // Attach background to the scene
    Ogre::SceneNode* node = smgr->getRootSceneNode()->createChildSceneNode("Background");
    node->attachObject(rect);
    
    
    /// CREATE SIMPLE OGRE SCENE
    // add sinbad.mesh
    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("Sinbad.zip", "Zip", "Popular");
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
    Ogre::Entity* ogreEntity = smgr->createEntity("Board", "Sinbad.mesh");
    ogreNode = smgr->getRootSceneNode()->createChildSceneNode();
    // add entity to a child node to correct position (this way, entity axis is on feet of sinbad)
    Ogre::SceneNode *ogreNodeChild = ogreNode->createChildSceneNode();
    ogreNodeChild->attachObject(ogreEntity);
    Ogre::Real offset = ogreEntity->getBoundingBox().getHalfSize().y;
    // Sinbad is placed along Y axis, we need to rotate to put it along Z axis so it stands up over the board
    // first rotate along X axis, then add offset in Z dir so it is over the board and not in the middle of it
    ogreNodeChild->rotate(Ogre::Vector3(1,0,0), Ogre::Radian(Ogre::Degree(-90)));
    ogreNodeChild->translate(0,0,-offset,Ogre::Node::TS_PARENT); // board Z axis is pointing down, so we need to negate offset
    // mesh is too big, rescale!
    const float scale = 0.01675f;
    ogreNode->setScale(scale, scale, scale);
    
    // Init animation
    ogreEntity->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);
    baseAnim = ogreEntity->getAnimationState("RunBase");
    topAnim = ogreEntity->getAnimationState("RunTop");
    baseAnim->setLoop(true);
    topAnim->setLoop(true);
    baseAnim->setEnabled(true);
    topAnim->setEnabled(true);
    
    
    /// KEYBOARD INPUT READING
    size_t windowHnd = 0;
    window->getCustomAttribute("WINDOW", &windowHnd);
    im = OIS::InputManager::createInputSystem(windowHnd);
    keyboard = static_cast<OIS::Keyboard*>(im->createInputObject(OIS::OISKeyboard, true));
    
    return 1;
}
Beispiel #13
0
static void NotebookTabElementDraw(
    void *clientData, void *elementRecord, Tk_Window tkwin,
    Drawable d, Ttk_Box b, unsigned state)
{
    if (qApp == NULL) NULL_Q_APP;
    NULL_PROXY_WIDGET(TileQt_QTabBar_Widget);
    int width = b.width, height = b.height;
    Tcl_MutexLock(&tileqtMutex);
    int PM_DefaultFrameWidth = 0, PM_TabBarBaseOverlap = 0;

    // TileQt_StateInfo(state, tkwin);
#ifdef TILEQT_QT_VERSION_4
    QStyleOptionTab::TabPosition position;
    int position_int;
    QStyleOptionTabV2 option;
    option.initFrom(wc->TileQt_QTabBar_Widget); option.state |= 
      (QStyle::StateFlag) TileQt_StateTableLookup(notebook_statemap, state);
#endif /* TILEQT_QT_VERSION_4 */

    PM_DefaultFrameWidth = PM(PM_DefaultFrameWidth);

    if (TileQt_ThemeIs(wc, "bluecurve")) {
      PM_DefaultFrameWidth = 2;
    }

    PM_TabBarBaseOverlap = PM(PM_TabBarBaseOverlap);
    height += PM_TabBarBaseOverlap;

    if ((state & TTK_STATE_USER1) && (state & TTK_STATE_USER2)) {
      /* Only tab */
#ifdef TILEQT_QT_VERSION_4
      wc->TileQt_QTabBar_Widget->addTab("");
      position = QStyleOptionTab::OnlyOneTab;
      position_int = 0;
#endif /* TILEQT_QT_VERSION_4 */
    } else if (state & TTK_STATE_USER1) {
      /* Left-most tab */
#ifdef TILEQT_QT_VERSION_4
      wc->TileQt_QTabBar_Widget->addTab("");
      wc->TileQt_QTabBar_Widget->addTab("");
      position = QStyleOptionTab::Beginning;
      position_int = 0;
#endif /* TILEQT_QT_VERSION_4 */
    } else if (state & TTK_STATE_USER2) {
      /* Right-most tab */
#ifdef TILEQT_QT_VERSION_4
      wc->TileQt_QTabBar_Widget->addTab("");
      wc->TileQt_QTabBar_Widget->addTab("");
      position = QStyleOptionTab::End;
      position_int = 1;
#endif /* TILEQT_QT_VERSION_4 */
    } else {
      /* A regular tab, in the middle of tab bar */
#ifdef TILEQT_QT_VERSION_4
      wc->TileQt_QTabBar_Widget->addTab("");
      wc->TileQt_QTabBar_Widget->addTab("");
      wc->TileQt_QTabBar_Widget->addTab("");
      position = QStyleOptionTab::Middle;
      position_int = 1;
#endif /* TILEQT_QT_VERSION_4 */
    }
#ifdef TILEQT_QT_VERSION_4
    if (state & TTK_STATE_DISABLED) {
      wc->TileQt_QTabBar_Widget->setTabEnabled(position_int, false);
    } else wc->TileQt_QTabBar_Widget->setTabEnabled(position_int, true);
#endif /* TILEQT_QT_VERSION_4 */

    QPixmap      pixmap(width, height);
    QPainter     painter(&pixmap);
    TILEQT_PAINT_BACKGROUND(width, height);
    TILEQT_SET_FOCUS(state);
#ifdef TILEQT_QT_VERSION_4
    option.rect = QRect(0, 0, width, height);
    option.position = position;
    option.selectedPosition = QStyleOptionTab::NotAdjacent;
    wc->TileQt_Style->drawControl(QStyle::CE_TabBarTabShape, &option,
                                  &painter, wc->TileQt_QTabBar_Widget);
#endif /* TILEQT_QT_VERSION_4 */
    TILEQT_CLEAR_FOCUS(state);
    TileQt_CopyQtPixmapOnToDrawable(pixmap, d, tkwin,
           0, 0, width, height, b.x, b.y + PM_DefaultFrameWidth);
#ifdef TILEQT_QT_VERSION_4
    for (int i = 0; i < wc->TileQt_QTabBar_Widget->count(); ++i) {
      wc->TileQt_QTabBar_Widget->removeTab(i);
    }
#endif /* TILEQT_QT_VERSION_4 */
    Tcl_MutexUnlock(&tileqtMutex);
}
Beispiel #14
0
void CheckLoad(uint32 type, int16 id, uint16 *p, uint32 size)
{
	uint16 *p16;
	uint32 base;
	D(bug("vCheckLoad %c%c%c%c (%08x) ID %d, data %p, size %d\n", type >> 24, (type >> 16) & 0xff, (type >> 8) & 0xff, type & 0xff, type, id, p, size));

	// Don't modify resources in ROM
	if ((uintptr)p >= (uintptr)ROMBaseHost && (uintptr)p <= (uintptr)(ROMBaseHost + ROM_SIZE))
		return;

	if (type == FOURCC('b','o','o','t') && id == 3) {
		D(bug("boot 3 found\n"));
		size >>= 1;
		while (size--) {
			if (PM(0,0x51c9) && PM(2,0x2e49)) {
				// Set boot stack pointer (7.5.2, 7.5.3, 7.5.5, 7.6, 7.6.1, 8.0, 8.1, 8.5, 8.6, 9.0)
				p[2] = htons(M68K_EMUL_OP_FIX_BOOTSTACK);
				D(bug(" patch 1 applied\n"));
			} else if (PM(0,0x4267) && PM(1,0x3f01) && PM(2,0x3f2a) && PM(3,0x0006) && PM(4,0x6100)) {
				// Check when ntrb 17 is installed (for native Resource Manager patch) (7.5.3, 7.5.5)
				p[7] = htons(M68K_EMUL_OP_NTRB_17_PATCH3);
				D(bug(" patch 2 applied\n"));
			} else if (PM(0,0x3f2a) && PM(1,0x0006) && PM(2,0x3f2a) && PM(3,0x0002) && PM(4,0x6100)) {
				// Check when ntrb 17 is installed (for native Resource Manager patch) (7.6, 7.6.1, 8.0, 8.1)
				p[7] = htons(M68K_EMUL_OP_NTRB_17_PATCH);
				D(bug(" patch 3 applied\n"));
			} else if (PM(0,0x3f2a) && PM(1,0x0006) && PM(2,0x3f2a) && PM(3,0x0002) && PM(4,0x61ff) && PM(8,0x245f)) {
				// Check when ntrb 17 is installed (for native Resource Manager patch) (8.5, 8.6)
				p[8] = htons(M68K_EMUL_OP_NTRB_17_PATCH);
				D(bug(" patch 4 applied\n"));
			} else if (PM(0,0x3f2a) && PM(1,0x0006) && PM(2,0x3f2a) && PM(3,0x0002) && PM(4,0x61ff) && PM(7,0x301f)) {
				// Check when ntrb 17 is installed (for native Resource Manager patch) (9.0)
				p[7] = htons(M68K_EMUL_OP_NTRB_17_PATCH4);
				p[8] = htons(ntohs(p[8]) & 0xf0ff); // bra
				D(bug(" patch 5 applied\n"));
			} else if (PM(0,0x0c39) && PM(1,0x0001) && PM(2,0xf800) && PM(3,0x0008) && PM(4,0x6f00)) {
				// Don't read from 0xf8000008 (8.5 with Zanzibar ROM, 8.6, 9.0)
				p[0] = htons(M68K_NOP);
				p[1] = htons(M68K_NOP);
				p[2] = htons(M68K_NOP);
				p[3] = htons(M68K_NOP);
				p[4] = htons(0x6000);	// bra
				D(bug(" patch 6 applied\n"));
			} else if (PM(0,0x2f3c) && PM(1,0x6b72) && PM(2,0x6e6c) && PM(3,0x4267) && PM(4,0xa9a0) && PM(5,0x265f) && PM(6,0x200b) && PM(7,0x6700)) {
				// Don't replace nanokernel ("krnl" resource) (8.6, 9.0)
				p[0] = htons(M68K_NOP);
				p[1] = htons(M68K_NOP);
				p[2] = htons(M68K_NOP);
				p[3] = htons(M68K_NOP);
				p[4] = htons(M68K_NOP);
				p[7] = htons(0x6000);	// bra
				D(bug(" patch 7 applied\n"));
			} else if (PM(0,0xa8fe) && PM(1,0x3038) && PM(2,0x017a) && PM(3,0x0c40) && PM(4,0x8805) && PM(5,0x6710)) {
				// No SCSI (calls via 0x205c jump vector which is not initialized in NewWorld ROM 1.6) (8.6)
				if (ROMType == ROMTYPE_NEWWORLD) {
					p[5] = htons(0x6010);	// bra
					D(bug(" patch 8 applied\n"));
				}
			} else if (PM(0,0x2f3c) && PM(1,0x7665) && PM(2,0x7273) && PM(3,0x3f3c) && PM(4,0x0001) && PM(10,0x2041) && PM(11,0x2248) && PM(12,0x2050) && PM(20,0x7066) && PM(21,0xa9c9)) {
				// Check when vers 1 is installed (for safe abort if MacOS < 8.1 is used with a NewWorld ROM)
				p[10] = htons(M68K_EMUL_OP_CHECK_SYSV);
				p[11] = htons(0x4a81);	// tst.l	d1
				p[12] = htons(0x670e);	// beq.s	<SysError #dsOldSystem>
				D(bug(" patch 9 applied\n"));
			}
			p++;
		}

	} else if (type == FOURCC('g','n','l','d') && id == 0) {
Beispiel #15
0
bool PowerSeriesWP::isTrivial(const Word& w)
{
  // Construct two possible types of monomials:
  // PM: (1 + x) and NM: ( 1 - x + x^2 - x^3 + ... x^c ) 

  int wLen = w.length();
  int numOfGens = F.numberOfGenerators();

  VectorOf<int> PM(c), NM(c);
  
  for( int i = 0; i < c; ++i ) {
    PM[i] = 0;
    if( odd(i+1) )
      NM[i] = -1;
    else
      NM[i] = 1;
  }
  PM[0] = 1;
  
  // Construct all monomials
  
  VectorOf<int>* M[wLen];
  for( int i = 0; i < wLen; ++i )
    if( ord(Generator(w[i])) > 0 )
      M[i] = &PM;
    else
      M[i] = &NM;

  // Enumerate all possible monomials and compute their coefficients.
  // They all are equal to 0 iff the word is trivial.

  VectorOf<int> v(c);
  for( int i = 0; i < c; ++i )
    v[i] = 0;

  // The main cycle

  while( true ) {
    
    // Construct the current monomial v

    int i = c-1;
    while( true ) {

      if( ++v[i] <= numOfGens )	break;
      v[i--] = 1;
      if( i < 0 ) return true;
    }

    for( i = 0; i < c; ++i )
      if( v[i] > 0 ) break;

    // Compute the sum of it's coefficients in M
    
    int sum = 0;
    Stack stack(c);
    State state(1, -1, i);
    bool checkPower = false;

    while( true ) {

      if( checkPower && v[state.vPos] == v[state.vPos + state.power] &&  
	  (*M[state.wPos])[state.power] != 0 ) {
	
	//state.vPos += state.power;
	++state.power;
      }
      else {

	++state.wPos;
	state.power = 1;

	for( ; state.wPos < wLen; ++state.wPos )
	  if( abs(ord(Generator(w[state.wPos]))) == v[state.vPos] )
	    break;
      }
      
      if( state.wPos == wLen) {

	if( stack.length() == 0 ) break;

	stack.get(state);
	checkPower = true;
      }
      else {

	stack.put(state);
	if( checkPower ) {
	  state.coef *= (*M[state.wPos])[state.power-1];
	  state.vPos += state.power;
	  state.power = 1;
	}
	else {
	  state.coef *= (*M[state.wPos])[0];
	  ++state.vPos;
	}
	checkPower = false;
	
	if( state.vPos >= c ) {
	  
	  sum += state.coef;
	  stack.get(state);
	}
      }
    }

  #ifdef debug_fnwp
    cout << "Monomial: " << v << "  Sum = " << sum << endl;
  #endif

    if( sum != 0 ) return false;
  }
}
Beispiel #16
0
void printCPUInfo(int processor, const CPUInfo& info) {
    printf("Processor %d:\n", processor);
    if (!info.supportsCPUID) {
        printf("  No CPUID Support\n");
        printf("\n");
        return;
    }

    printf("  Vendor:         %s\n", info.getVendorName());
    printf("  Name:           %s\n", info.getProcessorName().c_str());
    printf("  Type:           %s\n", info.getProcessorTypeName());
    printf("  Brand:          %s\n", info.getProcessorBrandName().c_str());
    printf("  Classical Name: %s\n", info.getClassicalProcessorName());
    printf("\n");
    printf("  Family:         %d\n", info.identity.family);
    printf("  Model:          %d\n", info.identity.model);
    printf("  Stepping:       %d\n", info.identity.stepping);
    printf("\n");
    printf("  Frequency:      %d MHz\n", info.frequency);
    printf("\n");
    printf("  Features:\n");
    
    bool featureflag = false;
#define F(flag, desc)                           \
    if (info.features.flag) {                   \
        featureflag = true;                     \
        printf("  %8s: %s\n", #flag, desc);     \
    }

    F(fpu,     "Floating Point Unit");
    F(vme,     "Virtual-8086 Mode Enhancement");
    F(de,      "Debugging Extensions");
    F(pse,     "Page Size Extensions");
    F(tsc,     "Time Stamp Counter");
    F(msr,     "RDMSR and WRMSR Support");
    F(pae,     "Physical Address Extensions");
    F(mce,     "Machine Check Exception");
    F(cx8,     "CMPXCHG8B Instruction");
    F(apic,    "APIC on Chip");
    F(sep,     "SYSENTER and SYSEXIT");
    F(mtrr,    "Memory Type Range Registers");
    F(pge,     "PTE Global Bit");
    F(mca,     "Machine Check Architecture");
    F(cmov,    "Conditional Move/Compare Instructions");
    F(pat,     "Page Attribute Table");
    F(pse36,   "Page Size Extension");
    F(serial,  "Serial Number Available");
    F(clfsh,   "CLFLUSH Instruction");
    F(ds,      "Debug Store");
    F(acpi,    "Thermal Monitor and Clock Control");
    F(mmx,     "MMX Technology");
    F(fxsr,    "FXSAVE/FXRSTOR Instructions");
    F(sse,     "SSE Extensions");
    F(ssefp,   "SSE Floating Point");
    F(sse2,    "SSE2 Extensions");
    F(ss,      "Self Snoop");
    F(htt,     "Hyper-Threading Technology");
    F(thermal, "Thermal Monitor");
    F(ia64,    "IA64 Instructions");
    F(pbe,     "Pending Break Enable");

    F(sse3,    "SSE3 Extensions");
    F(monitor, "MONITOR/MWAIT");
    F(ds_cpl,  "CPL Qualified Debug Store");
    F(est,     "Enhanced Intel SpeedStep Technology");
    F(tm2,     "Thermal Monitor 2");
    F(cnxt_id, "L1 Context ID");

    F(_3dnow,  "3DNow! Instructions");
    F(_3dnowPlus, "3DNow! Instructions Extensions");
    F(ssemmx,  "SSE MMX");
    F(mmxPlus, "MMX+");
    F(supportsMP, "Supports Multiprocessing");
    
#undef F

    if (!featureflag) {
        printf("    None\n");
    }

    printf("\n");

    if (info.features.serial) {
        printf("            Serial Number: %s\n", info.features.serialNumber);
    }
    if (info.features.htt) {
        printf("            Logical Processors per Physical: %d\n",
               info.features.logicalProcessorsPerPhysical);
    }
    if (info.features.clfsh) {
        printf("            CLFLUSH Cache Line Size: %d bytes\n",
               info.features.CLFLUSHCacheLineSize);
    }
    if (info.features.apic) {
        printf("            APIC ID: %d\n", info.features.APIC_ID);
    }

    printf("\n");

    printf("  Cache:\n");
    if (info.cache.L1CacheSize != -1) {
        printf("    L1 Size: %d kB\n", info.cache.L1CacheSize);
    }
    if (info.cache.L2CacheSize != -1) {
        printf("    L2 Size: %d kB\n", info.cache.L2CacheSize);
    }
    if (info.cache.L3CacheSize != -1) {
        printf("    L3 Size: %d kB\n", info.cache.L3CacheSize);
    }

    printf("\n");
    printf("  Enhanced Power Management:\n");

    bool pmflag = false;
#define PM(flag, desc)                          \
    if (info.powerManagement.flag) {            \
        pmflag = true;                          \
        printf("  %8s: %s\n", #flag, desc);     \
    }

    PM(ts,  "Temperature Sensor");
    PM(fid, "Frequency ID");
    PM(vid, "Voltage ID");
    PM(ttp, "Thermal Trip");
    PM(tm,  "Thermal Monitoring");
    PM(stc, "Software Thermal Control");

#undef PM

    if (!pmflag) {
        printf("    None\n");
    }

    printf("\n\n");
}
Beispiel #17
0
int main ( void )
{
#  if defined(VGO_darwin)
   // Mac OS X has neither memalign() nor posix_memalign();  do nothing.
   // Still true for 10.6 / 10.7 ?

#  else
   // Nb: assuming VG_MIN_MALLOC_SZB is 8 or more...
   int* p;
   int* piece;
   int  res;
   assert(sizeof(long int) == sizeof(void*));

   // Check behaviour of memalign/free for big alignment.
   // In particular, the below aims at checking that a
   // superblock with a big size is not marked as reclaimable
   // if the superblock is used to provide a big aligned block
   // (see bug 250101, comment #14).
   // Valgrind m_mallocfree.c will allocate a big superblock for the memalign
   // call and will split it in two. This split superblock was
   // wrongly marked as reclaimable, which was then causing
   // assert failures (as reclaimable blocks cannot be split).
   p = memalign(1024 * 1024, 4 * 1024 * 1024 + 1);   assert(0 == (long)p % (1024 * 1024));
   // We allocate (and then free) a piece of memory smaller than
   // the hole created in the big superblock.
   // If the superblock is marked as reclaimable, the below free(s) will cause
   // an assert. Note that the test has to be run with a --free-list-vol
   // parameter smaller than the released blocks size to ensure the free is directly
   // executed (otherwise memcheck does not really release the memory and so
   // the bug is not properly tested).
   piece = malloc(1024 * 1000); assert (piece);
   free (piece);
   free (p);
   
   // Same as above but do the free in the reverse order.
   p = memalign(1024 * 1024, 4 * 1024 * 1024 + 1);   assert(0 == (long)p % (1024 * 1024));
   piece = malloc(1024 * 100); assert (piece);
   free (p);
   free (piece);
   
   p = memalign(0, 100);      assert(0 == (long)p % 8);
   p = memalign(1, 100);      assert(0 == (long)p % 8);
   p = memalign(2, 100);      assert(0 == (long)p % 8);
   p = memalign(3, 100);      assert(0 == (long)p % 8);
   p = memalign(4, 100);      assert(0 == (long)p % 8);
   p = memalign(5, 100);      assert(0 == (long)p % 8);

   p = memalign(7, 100);      assert(0 == (long)p % 8);
   p = memalign(8, 100);      assert(0 == (long)p % 8);
   p = memalign(9, 100);      assert(0 == (long)p % 16);

   p = memalign(31, 100);     assert(0 == (long)p % 32);
   p = memalign(32, 100);     assert(0 == (long)p % 32);
   p = memalign(33, 100);     assert(0 == (long)p % 64);

   p = memalign(4095, 100);   assert(0 == (long)p % 4096);
   p = memalign(4096, 100);   assert(0 == (long)p % 4096);
   p = memalign(4097, 100);   assert(0 == (long)p % 8192);

   p = memalign(4 * 1024 * 1024, 100);   assert(0 == (long)p % (4 * 1024 * 1024));
   p = memalign(16 * 1024 * 1024, 100);   assert(0 == (long)p % (16 * 1024 * 1024));

#  define PM(a,b,c) posix_memalign((void**)a, b, c)

   res = PM(&p, -1,100);      assert(EINVAL == res);
   res = PM(&p, 0, 100);      assert(0 == res && 0 == (long)p % 8);
   res = PM(&p, 1, 100);      assert(EINVAL == res);
   res = PM(&p, 2, 100);      assert(EINVAL == res);
   res = PM(&p, 3, 100);      assert(EINVAL == res);
   res = PM(&p, sizeof(void*), 100);
                              assert(0 == res && 0 == (long)p % sizeof(void*));

   res = PM(&p, 31, 100);     assert(EINVAL == res);
   res = PM(&p, 32, 100);     assert(0 == res && 0 == (long)p % 32);
   res = PM(&p, 33, 100);     assert(EINVAL == res);

   res = PM(&p, 4095, 100);   assert(EINVAL == res);
   res = PM(&p, 4096, 100);   assert(0 == res && 0 == (long)p % 4096); 
   res = PM(&p, 4097, 100);   assert(EINVAL == res);

   res = PM(&p, 4 * 1024 * 1024, 100);   assert(0 == res 
                                                && 0 == (long)p % (4 * 1024 * 1024));
   res = PM(&p, 16 * 1024 * 1024, 100);   assert(0 == res 
                                                && 0 == (long)p % (16 * 1024 * 1024));
#  endif
   
   return 0;
}
Beispiel #18
0
int
main (int argc, char *argv[])
{
  char * bptr, * eptr;
  int i;
  int html_mode = 0;
  char * enc_name = 0;
  char * tenc_name = 0;

  for (;;)
    {
      i = getopt (argc, argv, "hf:e:t:");
      if (i == -1)
	break;

      switch (i)
	{
	case 'h':
	  html_mode = 1;
#ifdef UNIT_DEBUG
	  printf ("HTML mode!\n");
#endif
	  break;
	case 'e':
	  enc_name = optarg;
	  break;
	case 't':
	  tenc_name = optarg;
	  break;
	case 'f':
	  f = fopen (optarg, "r");
	  if (f)
	    break;

	  perror ("can't open file\n");
	  exit (2);
	default:
	  exit (-1);
	}
    }

  if (argc <= optind)
    {
      printf ("USAGE: %s 'STRING'\n", argv[0]);
      exit (-1);
    }

  /*
    dk_memory_initialize ();
    dk_alloc (1);
  */

  bptr = argv[1];
  eptr = bptr + strlen (bptr);

  bsize = argc - optind - 1;
  buf = malloc (bsize);
  for (i = optind + 1; i < bsize; i++)
    buf[i] = strtol (argv[i + 2], 0, 0);

  for (i = 0; i < 1; i++)
    {
      parser = XML_ParserCreate (tenc_name);

      printf ("sizeof (*parser) = %d\n", sizeof (*parser));

      XML_SetEntityEncoding (parser, enc_name);

      XML_ParserInput (parser, ff, 0);

      XML_SetElementHandler (parser, start_element_handler, end_element_handler);
      XML_SetCharacterDataHandler (parser, cdh);
      XML_SetEntityRefHandler (parser, erh);

      if (XML_Parse (parser, argv[optind], strlen (argv[optind]), 1))
	printf ("Successfully parsed!\n");
      else if (PM(err))
	printf ("ERROR %d: %s\n", PM(err), XML_ErrorString (PM(err)));

      XML_ParserFree (parser);
    }
  exit (0);
}
Beispiel #19
0
// Methods for class Direct3D ////////////////////////////////////////////
// In place of constructor, mainly so that there can be a return value
HRESULT Direct3D::Init(HWND Window,			// Window to initialize in
					   INT ScreenWidth,		// ScreenWidth
					   INT ScreenHeight,	// ScreenHeight
					   BOOL FreeForm)		// Whether to initialize in freeform mode
{
	// Set the freeform member to the value passed
	IsFreeForm = FreeForm;

	static DDSURFACEDESC2 SD;

	static HRESULT Return;

	// First, if this is a freeform initialization, we need to copy the screen to a
	// DC owned by this	module
	HDC Screen;
	HBITMAP	ScreenData;
	if(IsFreeForm)
	{
		// Force GDI to repaint the screen
		InvalidateRect(0, 0, FALSE);

		// wait for repaint to finish
		Sleep(500);

		HDC Desktop = GetDC(0);

		Screen = CreateCompatibleDC(Desktop);
		ScreenData = CreateCompatibleBitmap(Desktop,
											ScreenWidth,
											ScreenHeight);
		SelectObject(Screen, ScreenData);

		StretchBlt(Screen,
				   0,
				   0,
				   ScreenWidth,
				   ScreenHeight,
				   Desktop,
				   0,
				   0,
				   ScreenWidth,
				   ScreenHeight,
				   SRCCOPY);   

		ReleaseDC(0, Desktop);
	} // end if
	else 
		ShowCursor(0);

	// Create the master DirectDraw interface
	Return = DirectDrawCreateEx(0,
								(LPVOID*)&DirectDraw,
								IID_IDirectDraw7,
								0);
	if(FAILED(Return))
		return Return;

	// Set the cooperative level with other apps, allow ctrl-alt-delete and that's about it
	Return = DirectDraw->SetCooperativeLevel(Window,
											 DDSCL_ALLOWREBOOT |
											 DDSCL_FULLSCREEN  |
											 DDSCL_EXCLUSIVE);
	if(FAILED(Return))
		return Return;

	// Set the display mode
	Return = DirectDraw->SetDisplayMode(ScreenWidth,
									    ScreenHeight,
									    16, // Force 16 bit color
									    0,
									    0);
	if(FAILED(Return))
		return Return;

	// Create the backbuffer's clipper
	Return = DirectDraw->CreateClipper(0,
									   &Clipper,
									   0);
	if(FAILED(Return))
		return Return;

	// Set the clipper's clip list -- do it the easy way
	Return = Clipper->SetHWnd(0,
							  Window);
	if(FAILED(Return))
		return Return;

	// Create the primary surface
	ZeroMemory(&SD, sizeof(SD));
	SD.dwSize = sizeof(SD);
	SD.dwFlags = DDSD_CAPS |
				 DDSD_BACKBUFFERCOUNT;
	SD.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
						DDSCAPS_FLIP           |
						DDSCAPS_3DDEVICE       |
						DDSCAPS_COMPLEX;
	SD.dwBackBufferCount = 1;
	Return = DirectDraw->CreateSurface(&SD,
									   &PrimarySurface,
									   0);
	if(FAILED(Return))
		return Return;

	// Get the attached surface (backbuffer)
	static DDSCAPS2 C;
	ZeroMemory(&C, sizeof(C));
	C.dwCaps = DDSCAPS_BACKBUFFER;
	Return = PrimarySurface->GetAttachedSurface(&C,
												&BackBuffer);
	if(FAILED(Return))
		return Return;

	// Attach the clipper to the backbuffer
	Return = BackBuffer->SetClipper(Clipper);
	if(FAILED(Return))
		return Return;

	// Get master 3D interface
	Return = DirectDraw->QueryInterface(IID_IDirect3D7, (LPVOID*)&D3D);
	if(FAILED(Return))
		return Return;
	
	// Create the zbuffer, not a fun thing to do
	// Stores the 
	INT ZBufFormat = 0;
	// Enumerate the Z-buffer formats, making sure they fit the device.
	// First try hardware with accelerated transform and lighting.
	// If you cannot get that, just keep trying with worse and worse devices :)
	static DDPIXELFORMAT ZBufferPF;
	ZeroMemory(&ZBufferPF, sizeof(ZBufferPF));
	ZBufferPF.dwSize = sizeof(ZBufferPF);
	ZBufferPF.dwFlags = DDPF_ZBUFFER ;
	D3D->EnumZBufferFormats(	IID_IDirect3DTnLHalDevice, 
								EnumZBufferFormatsCallback,
								(VOID*)&ZBufferPF	);
	if(ZBufFound)
		ZBufFormat = 1;
	else
	{
		D3D->EnumZBufferFormats(	IID_IDirect3DHALDevice,
									EnumZBufferFormatsCallback,
									(VOID*)&ZBufferPF	);
		if(ZBufFound)
			ZBufFormat=2;
		else
		{
			D3D->EnumZBufferFormats(	IID_IDirect3DMMXDevice,
										EnumZBufferFormatsCallback,
										(VOID*)&ZBufferPF	);
			if(ZBufFound)
				ZBufFormat=3;
			else
			{
				D3D->EnumZBufferFormats(	IID_IDirect3DRGBDevice,
											EnumZBufferFormatsCallback,
											(VOID*)&ZBufferPF	);
				if(ZBufFound) 
					ZBufFormat=4;
			} // end else
		} // end else
	} // end else

	// Create the zbuffer
	ZeroMemory(&SD, sizeof(SD));
    SD.dwSize = sizeof(SD);
    SD.dwFlags = DDSD_CAPS   |
				 DDSD_WIDTH  |
				 DDSD_HEIGHT |
				 DDSD_PIXELFORMAT;
	
	// Use counter to check if we should create z-buffer in video or system memory
	// Note flag that specifies that this is a z-buffer surface.
	if(ZBufFormat<3)
		SD.ddsCaps.dwCaps = DDSCAPS_ZBUFFER|DDSCAPS_VIDEOMEMORY;
	else
		SD.ddsCaps.dwCaps = DDSCAPS_ZBUFFER|DDSCAPS_SYSTEMMEMORY;
	
	// Set it the to size of screen
	SD.dwWidth = ScreenWidth;
	SD.dwHeight = ScreenHeight;
	SD.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
	SD.ddpfPixelFormat.dwFlags = DDPF_ZBUFFER;
	memcpy(&SD.ddpfPixelFormat, &ZBufferPF, sizeof(DDPIXELFORMAT));
    Return = DirectDraw->CreateSurface(&SD, &ZBuffer, 0);
	if(FAILED(Return))
		return Return;

	// Attach z-buffer to the backbuffer...
	Return = BackBuffer->AddAttachedSurface(ZBuffer);
	if(FAILED(Return))
		return Return;

	// Set up the best hardware interface, really dumb, brute-forcish way to do it
	if(FAILED(D3D->CreateDevice(IID_IDirect3DTnLHalDevice, BackBuffer, &D3DDevice)))
		if(FAILED(D3D->CreateDevice(IID_IDirect3DHALDevice, BackBuffer, &D3DDevice)))
			if(FAILED(D3D->CreateDevice(IID_IDirect3DMMXDevice, BackBuffer, &D3DDevice)))
				if(FAILED(Return = D3D->CreateDevice(IID_IDirect3DRGBDevice, BackBuffer, &D3DDevice)))
					return Return; // Report the error

	// Set up the viewport for the new screen size
	D3DVIEWPORT7 Viewport;
	Viewport.dwX = 0;
	Viewport.dwY = 0;
	Viewport.dwWidth = ScreenWidth;
	Viewport.dwHeight = ScreenHeight;
	Viewport.dvMinZ = 0.0f;
	Viewport.dvMaxZ = 1.0f;
	Return = D3DDevice->SetViewport(&Viewport);
	if(FAILED(Return))
		return Return;

	// Set up a nice projection matrix
	D3DMATRIX PM(3,	0,  0, 0,
				 0,	4,  0, 0,
				 0,	0,  1, 1,
				 0, 0, -5, 0);

	// Apply the projection matrix
	Return = D3DDevice->SetTransform(D3DTRANSFORMSTATE_PROJECTION, &PM);
	if(FAILED(Return))
		return Return;

	// Turn on some nice texture filtering
	Return = D3DDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
	if(FAILED(Return))
		return Return;
	Return = D3DDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
	if(FAILED(Return))
		return Return;
	Return = D3DDevice->SetTextureStageState(0, D3DTSS_COLOROP,   D3DTOP_MODULATE);
	if(FAILED(Return))
		return Return;
	Return = D3DDevice->SetTextureStageState(0, D3DTSS_MINFILTER, D3DTFN_LINEAR);
	if(FAILED(Return))
		return Return;
	Return = D3DDevice->SetTextureStageState(0, D3DTSS_MAGFILTER, D3DTFG_LINEAR);
	if(FAILED(Return))
		return Return;

	// Enable z-buffering.
    Return = D3DDevice->SetRenderState(D3DRENDERSTATE_ZENABLE, D3DZB_USEW);
	if(FAILED(Return))
		return Return;
	Return = D3DDevice->SetRenderState(D3DRENDERSTATE_ZFUNC, D3DCMP_LESSEQUAL);
	if(FAILED(Return))
		return Return;

	// Enable Direct3D lighting
	Return = D3DDevice->SetRenderState(D3DRENDERSTATE_LIGHTING, TRUE);
	if(FAILED(Return))
		return Return;
	Return = D3DDevice->SetRenderState(D3DRENDERSTATE_SPECULARENABLE, FALSE);
	if(FAILED(Return))
		return Return;

	// Just to be safe, disable backface culling
	Return = D3DDevice->SetRenderState(D3DRENDERSTATE_CULLMODE, D3DCULL_NONE);
	if(FAILED(Return))
		return Return;

	// Turn on dithering
	Return = D3DDevice->SetRenderState(D3DRENDERSTATE_DITHERENABLE, TRUE);
	if(FAILED(Return))
		return Return;

	// Do any freeform initialization
	if(IsFreeForm)
	{
		// Get a copy of the GDI surface
		ZeroMemory(&SD, sizeof(SD));
		SD.dwSize = sizeof(SD);
		SD.dwFlags = DDSD_WIDTH		|
					 DDSD_HEIGHT	|
					 DDSD_CAPS;
		SD.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
		SD.dwWidth = ScreenWidth;
		SD.dwHeight = ScreenHeight;
		Return = DirectDraw->CreateSurface(&SD, &GDIScreenShot, 0);
		if(FAILED(Return))
			return(Return);

		HDC xdc;
		GDIScreenShot->GetDC(&xdc);
		StretchBlt(xdc,
				   0,
				   0,
				   ScreenWidth,
				   ScreenHeight,
				   Screen,
				   0,
				   0,
				   ScreenWidth,
				   ScreenHeight,
				   SRCCOPY);
		GDIScreenShot->ReleaseDC(xdc);

		// Clean up the GDI memory
		DeleteDC(Screen);
		DeleteObject(ScreenData);
	} // end if

	// Return success
	return(D3D_OK);
} // end Direct3D::Init
Function * futamurize( const Function * orig_func, DenseMap<const Value*, Value*> &argmap, std::set<const unsigned char *> &constant_addresses_set )
{
	LLVMContext &context = getGlobalContext();
	
	
	// Make a copy of the function, removing constant arguments
	Function * specialized_func = CloneFunction( orig_func, argmap );
	specialized_func->setName( orig_func->getNameStr() + "_1" );
	
	// add it to our module
	LLVM_Module->getFunctionList().push_back( specialized_func );
	
	printf("\nspecialized_func = %p <%s>\n", specialized_func, specialized_func->getName().data());
	//~ specialized_func->dump();

	// Optimize it
	FunctionPassManager PM( LLVM_Module );
	createStandardFunctionPasses( &PM, 3 );
	
	PM.add(createScalarReplAggregatesPass());  // Break up aggregate allocas
	PM.add(createInstructionCombiningPass());  // Cleanup for scalarrepl.
	PM.add(createJumpThreadingPass());         // Thread jumps.
	PM.add(createCFGSimplificationPass());     // Merge & remove BBs
	PM.add(createInstructionCombiningPass());  // Combine silly seq's
	PM.add(createTailCallEliminationPass());   // Eliminate tail calls
	PM.add(createCFGSimplificationPass());     // Merge & remove BBs
	PM.add(createReassociatePass());           // Reassociate expressions
	PM.add(createLoopRotatePass());            // Rotate Loop
	PM.add(createLICMPass());                  // Hoist loop invariants
	PM.add(createLoopUnswitchPass( false ));
	PM.add(createInstructionCombiningPass());
	PM.add(createIndVarSimplifyPass());        // Canonicalize indvars
	PM.add(createLoopDeletionPass());          // Delete dead loops
	PM.add(createLoopUnroll2Pass());            // Unroll small loops
	PM.add(createInstructionCombiningPass());  // Clean up after the unroller
	PM.add(createGVNPass());                   // Remove redundancies
	PM.add(createMemCpyOptPass());             // Remove memcpy / form memset
	PM.add(createSCCPPass());                  // Constant prop with SCCP
	PM.add(createPromoteMemoryToRegisterPass()); 
	PM.add(createConstantPropagationPass());            
	PM.add(createDeadStoreEliminationPass());            
	PM.add(createAggressiveDCEPass());            
	PM.add(new MemoryDependenceAnalysis());            
	//~ PM.add(createAAEvalPass());              
	
	const PassInfo * pinfo = Pass::lookupPassInfo( "print-alias-sets" );
	if( !pinfo ) { printf( "print-alias-sets not found\n" ); exit(-1); }
	PM.add( pinfo->createPass() );
	
	FunctionPassManager PM_Inline( LLVM_Module );
	PM_Inline.add(createSingleFunctionInliningPass());            
	
	bool Changed = false;
	int iterations = 2;
	int inline_iterations = 6;
	
	do
	{
		Changed = false;
		
		// first do some optimizations
		PM.doInitialization();
		PM.run( *specialized_func );
		PM.doFinalization();
		
		// Load from Constant Memory detection
		const TargetData *TD = LLVM_EE->getTargetData();
		
		for (inst_iterator I = inst_begin(specialized_func), E = inst_end(specialized_func); I != E; ++I) 
		{
			Instruction * inst = (Instruction *) &*I;

			// get all Load instructions
			LoadInst * load = dyn_cast<LoadInst>( inst );
			if( !load ) continue;
			if( load->isVolatile() ) continue;

			if (load->use_empty()) continue;        // Don't muck with dead instructions...

			// get the address loaded by load instruction
			Value *ptr_value = load->getPointerOperand();
			
			// we're only interested in constant addresses
			ConstantExpr * ptr_constant_expr =  dyn_cast<ConstantExpr>( ptr_value );
			if( !ptr_constant_expr ) continue;			
			ptr_constant_expr->dump();
			
			// compute real address of constant pointer expression
			Constant * ptr_constant = ConstantFoldConstantExpression( ptr_constant_expr, TD );
			if( !ptr_constant ) continue;
			ptr_constant->dump();
			
			// convert to int constant
			ConstantInt *int_constant =  dyn_cast<ConstantInt>( ConstantExpr::getPtrToInt( ptr_constant, Type::getInt64Ty( context )));
			if( !int_constant ) continue;
			int_constant->dump();
			
			// get data size
			int data_length = TD->getTypeAllocSize( load->getType() );
			ptr_value->getType()->dump();
			
			// get real address (at last !)
			const unsigned char * c_ptr = (const unsigned char *) int_constant->getLimitedValue();
			
			printf( "%ld %d %d\n", c_ptr, constant_addresses_set.count( c_ptr ), data_length );
			
			// check what's in this address	
			int isconst = 1;
			for( int offset=0; offset<data_length; offset++ )
				isconst &= constant_addresses_set.count( c_ptr + offset );
			
			if( !isconst ) continue;
			printf( "It is constant.\n" );
			
			// make a LLVM const with the data
			Constant *new_constant = NULL;
			switch( data_length )
			{
				case 1:	new_constant = ConstantInt::get( Type::getInt8Ty( context ),  *(uint8_t*)c_ptr, false /* signed */ );	break;
				case 2:	new_constant = ConstantInt::get( Type::getInt16Ty( context ), *(uint16_t*)c_ptr, false /* signed */ );	break;
				case 4:	new_constant = ConstantInt::get( Type::getInt32Ty( context ), *(uint32_t*)c_ptr, false /* signed */ );	break;
				case 8:	new_constant = ConstantInt::get( Type::getInt64Ty( context ), *(uint64_t*)c_ptr, false /* signed */ );	break;
				default:
				{
					StringRef const_data ( (const char *) c_ptr, data_length );
					new_constant = ConstantArray::get( context, const_data, false /* dont add terminating null */ );
				}
			}
			
			if( !new_constant ) continue;
			
			new_constant->dump();
							
			//~ // get the type that is loaded
			const Type *Ty = load->getType();
			
			// do we need a cast ?
			if( load->getType() != new_constant->getType() )
			{
				new_constant = ConstantExpr::getBitCast( new_constant, Ty );
				new_constant->dump();
			}
			
			// zap the load and replace with constant address
			load->replaceAllUsesWith( new_constant );
			printf( "\nREPLACED :...\n" );
			load->dump();
			new_constant->dump();
			
			Changed = true;
		}	
		
		if( Changed )
			continue;	// re-optimize and do another pass of constant load elimination
		
		// if we can't do anything else, do an inlining pass
		if( inline_iterations > 0 )
		{
			inline_iterations --;
			
			PM_Inline.doInitialization();
			Changed |= PM_Inline.run( *specialized_func );
			PM_Inline.doFinalization();

			//~ for( int i=0; i<3; i++ )
			{
				PM.doInitialization();
				Changed |= PM.run( *specialized_func );
				PM.doFinalization();
			}
		}
		
		if( iterations>0 && !Changed ) 
			iterations--;
	} while( Changed || iterations>0 );
	
	return specialized_func;
}