sagexx_ug (1158317), страница 10

Файл №1158317 sagexx_ug (Раздаточные материалы) 10 страницаsagexx_ug (1158317) страница 102019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 10)

In a pCxx Program to** refer to any particular element an array like syntax is used. To refer** to a field within an element that resides on someother processor is** expensive at present. The reason being when a reference to a nonlocal** element occurs the whole element is brought in and then the particular** field that is required is extracted from it.**** This application analyzes pCxx Program for "Collection Array** References" and transforms them so that the communication for getting** fields of non local elements is not more than the "length" of the** field.**** As an example consider the following pCxx Program and in** Processor_Main are some potential non local references.**** class Simple{**public:**int foo;**float bar[10];**void hello() {printf("hello world\n");};** };**** #include "distarray.h"**** Collection DistBlkVector: SuperKernel** {**public:**DistBlkVector(Distribution *T, Align *A);**MethodOfElement:**virtual void hello();** };****** DistBlkVector::DistBlkVector(Template *T, Align *A):SuperKernel(T, A)** {}****** void Processor_Main()** {**int i,j;**Processors P;**Distribution T(GRIDSIZE,&P,BLOCK);**Align A(GRIDSIZE,"[ALIGN(V[i],T[i])]");Chapter 9: Example Programs160**Distribution T1(GRIDSIZE,GRIDSIZE&P,BLOCK, BLOCK);**Align A1(GRIDSIZE,"[ALIGN(V[i][j],T[i][j])]");**DistBlkVector<Simple>x(&T,&A);**DistBlkVector<Simple>y(&T,&A);****x(i)->foo; // xformed to x.Get_ElementPart_Int(i, <foo-offset>, <sizeof (int)>)**x(i)->hello();****y(i,j)->bar // xformed to y.GetElementPart(i, <bar-offset>, 10 * <sizeof (float)>**y(i,j)->hello();**** }*******************************************************************/#include <stdio.h>#include <malloc.h>#include <sage++user.h>// Make the dummy var table into a class and clean it up.#define MAXDUMMYVAR 20SgSymbol*DummyVar[MAXDUMMYVAR];SgType*DummyVarType[MAXDUMMYVAR];SgExpression *DummyVarExpr[MAXDUMMYVAR];int TotalDummyVars = 0;SgFunctionSymb *GetElementPart, *GetElemInt, *GetElemFloat, *GetElemDouble;SgVariableSymb *addr1, *addr2;void SearchInExpForCollectionArrayRef(SgStatement *br, SgExpression *e,int & level);void ReplaceWithGetElemPart(SgStatement *br, SgExpression *e,SgDerivedCollectionType *a, SgSymbol *b, int level);int MatchingDummyVar(SgType *x);Expand Syntax - isReferenceToElementFieldSgSymbol *isReferenceToElementField(SgExpression *expr){SgVarRefExp *varef;SgArrayRefExp *aref;SgSymbol *symb;SgFieldSymb *symbf;Chapter 9: Example Programsif (!expr)return NULL;if (varef = isSgVarRefExp(expr)){symb = varef->symbol();if (symbf = isSgFieldSymb(symb))return symbf;}else if (aref = isSgArrayRefExp(expr)){symb = aref->symbol();if (symbf = isSgFieldSymb(symb))return symbf;}return NULL;}Expand Syntax - isArrayRefOfCollection// Looks into the expression for collection Array References// Returns the type of the collection if it finds one.SgDerivedCollectionType *isArrayRefOfCollection(SgExpression *expr){SgType *type = NULL;SgExpression *lhs;SgVarRefExp *varef;SgDerivedCollectionType *dstype;if (!expr)return NULL;switch (expr->variant()){case FUNCTION_OP:lhs = expr->lhs();break;default :return NULL;}if (!lhs)return NULL;161Chapter 9: Example Programsif (varef = isSgVarRefExp(lhs)){if (varef->symbol())type = varef->symbol()->type();}if (!type)return NULL;if (dstype = isSgDerivedCollectionType(type))return dstype;}return NULL;Expand Syntax - ExpandSyntaxvoidExpandSyntax(SgFile *f){SgStatement *br;SgExprListExp *l;SgExpression *e;SgStatement *s;int lvl = 0;s = f->firstStatement();for (br = s; br; br = br->lexNext())if (isSgCExpStmt(br)) {for (l = isSgExprListExp(br->expr(0)); l ; l = l->next()) {e = l->value();SearchInExpForCollectionArrayRef(br,e, lvl);lvl = 0;}}}Expand Syntax - SearchInExpForCollectionArrayRef// Need the level stuff to handle multiple references collection field// references in one statement.162Chapter 9: Example Programsvoid SearchInExpForCollectionArrayRef(SgStatement *br, SgExpression *e,int & level){if (e == NULL)return;if (e->variant() == POINTST_OP) {SgDerivedCollectionType *a;SgSymbol *b;a = isArrayRefOfCollection(e->lhs());b = isReferenceToElementField(e->rhs());if (a && b) {ReplaceWithGetElemPart(br, e, a, b, level);level = level + 1;}}}else {SearchInExpForCollectionArrayRef(br, e->lhs(), level);SearchInExpForCollectionArrayRef(br, e->rhs(), level);}Expand Syntax - ReplaceWithGetElemPartvoid ReplaceWithGetElemPart(SgStatement *br, SgExpression *e,SgDerivedCollectionType *a, SgSymbol *b, int level){SgBasicBlockStmt bgn;SgControlEndStmt nd;SgStatement *ext, *brnext;int matchingdummy;SgType *btype;matchingdummy = MatchingDummyVar(a->elementClass());if (!matchingdummy)Message("Dummy variable has not been created!\n", 0);br->insertStmtBefore(bgn, *(br->controlParent()));brnext = br->lexNext();ext = br->extractStmt();163Chapter 9: Example Programs164SgExpression dummy(RECORD_REF);dummy.setLhs(*DummyVarExpr[matchingdummy]);dummy.setRhs(*(e->rhs()));char addr1str[16], addr2str[16];if (level == 0) {strcpy(addr1str, "addr1");strcpy(addr2str, "addr2");}else {sprintf(addr1str, "addr1_%d", level);sprintf(addr2str, "addr2_%d", level);}SgPointerType p(*SgTypeInt());SgVariableSymb addr1(addr1str,p);SgVariableSymb addr2(addr2str,p);SgVarRefExp addr1ref(addr1), addr2ref(addr2);SgTypeArray *arrtype;if ((arrtype = isSgTypeArray(b->type())) && isSgArrayRefExp(e->rhs()))btype = arrtype->baseType();elsebtype = b->type();SgFunctionSymb *fsymb;if (btype->equivalentToType(*SgTypeInt()))fsymb = GetElemInt;else if (btype->equivalentToType(*SgTypeFloat()))fsymb = GetElemFloat;else if (btype->equivalentToType(*SgTypeDouble()))fsymb = GetElemDouble;elsefsymb = GetElementPart;SgFunctionCallExp func(*fsymb);func.addArg(*(e->lhs()->rhs()));func.addArg(addr2ref - addr1ref);// sizeof will be wrong for array's like x(i)->foo where foo// is an array so do more work.

Handle only one, two and three dimension// cases.// Need to work harder here. What about stuff like x(i)->foo[10] where the// field foo is a 2d array.Chapter 9: Example Programsif ((arrtype = isSgTypeArray(b->type())) && isSgVarRefExp(e->rhs())) {if (arrtype->dimension() == 1)func.addArg(SgSizeOfOp(dummy) * arrtype->sizeInDim(0)->copy());else if (arrtype->dimension() == 2)func.addArg(SgSizeOfOp(dummy) * arrtype->sizeInDim(0)->copy()* arrtype->sizeInDim(1)->copy());else if (arrtype->dimension() == 3)func.addArg(SgSizeOfOp(dummy) * arrtype->sizeInDim(0)->copy()* arrtype->sizeInDim(1)->copy()* arrtype->sizeInDim(2)->copy());}elsefunc.addArg(SgSizeOfOp(dummy));SgVarRefExp *collref;collref = isSgVarRefExp(e->lhs()->lhs());e->setVariant(RECORD_REF);e->setLhs(*collref);e->setRhs(func);SgExpression x1(ASSGN_OP);x1.setLhs(addr1ref);x1.setRhs(SgAddrOp(*DummyVarExpr[matchingdummy]));SgExprListExp exp1(x1);SgCExpStmt addr1assgn(exp1);SgExpression x2(ASSGN_OP);x2.setLhs(addr2ref);x2.setRhs(SgAddrOp(dummy));SgExprListExp exp2(x2);SgCExpStmt addr2assgn(exp2);bgn.insertStmtAfter(addr1assgn);addr1assgn.insertStmtAfter(addr2assgn);addr2assgn.insertStmtAfter(*ext);ext->insertStmtAfter(nd);}addr1.declareTheSymbol(bgn);addr2.declareTheSymbol(bgn);Expand Syntax - MatchingDummyVarint MatchingDummyVar(SgType *x)165Chapter 9: Example Programs{}166for (int i=0; i < TotalDummyVars; i++)if (DummyVarType[i]->equivalentToType(*x))return i;return 0;Expand Syntax - InDummyVarTableint InDummyVarTable(SgType *x){for (int i=0; i < MAXDUMMYVAR; i++)if (DummyVarType[i] != NULL)if (DummyVarType[i]->equivalentToType(*x))return TRUE;}return FALSE;Expand Syntax - Initvoid Init( SgFile *f) {char strin[256];SgStatement *fr;SgPointerType *p;SgSymbol *symb;fr = f->firstStatement();p = new SgPointerType(*SgTypeInt());GetElementPart = new SgFunctionSymb(FUNCTION_NAME, "Get_ElementPart", *p, *fr);GetElemInt = new SgFunctionSymb(FUNCTION_NAME, "Get_ElementPart_Int", *p, *fr);GetElemFloat = new SgFunctionSymb(FUNCTION_NAME, "Get_ElementPart_Float", *p, *fr);GetElemDouble = new SgFunctionSymb(FUNCTION_NAME, "Get_ElementPart_Double", *p, *fr);for (int i=0; i < MAXDUMMYVAR; i++){DummyVar[i] = NULL;DummyVarType[i] = NULL;DummyVarExpr[i] = NULL;}SgType *type;Chapter 9: Example ProgramsSgDerivedCollectionType *ct;{for (i=0,type = f->firstType(); type; type = type->next()){if (ct = isSgDerivedCollectionType(type))SgType *elementype;elementype = ct->elementClass();if (!InDummyVarTable(elementype)){SgClassStmt *fordef;sprintf(strin, "Dummy_%d", i);DummyVar[i] = new SgVariableSymb(strin, *elementype, *fr);DummyVar[i]->declareTheSymbol(*fr);DummyVarType[i] = elementype;DummyVarExpr[i] = new SgVarRefExp(*DummyVar[i]);fordef = new SgClassStmt(*elementype->symbol());fr->insertStmtAfter(*fordef);}}}i++;}TotalDummyVars = i;Expand Syntax - CAnalyzevoidCAnalyze(SgProject * project){for (int i = 0; i < project->numberOfFiles(); i++) {SgFile *f;}}f = &(project->file(i));Init(f);ExpandSyntax(f);167Chapter 9: Example ProgramsExpand Syntax - ProjectUnparsevoidProjectUnparse(SgProject *project){for (int i = 0; i < project->numberOfFiles(); i++) {SgFile *f;}}f = &(project->file(i));f->unparsestdout();Expand Syntax - mainmain(int argc, char **argv){SgProject project("simple.proj");SgFile file("simple.pc");int c;switch (file.languageType()) {case CSrc:#if 1CAnalyze(&project);ProjectUnparse(&project);#endifbreak;}case ForSrc:printf("Wrong language!\n");exit(-1);}9.4 Dump Info/*********************************************************************//*pC++/Sage++ Copyright (C) 1993*//* Indiana University University of Oregon University of Rennes*//*********************************************************************/168Chapter 9: Example Programs#include <stdio.h>#include <malloc.h>#include "sage++user.h"//////////This program demonstrates the functions that access thecontents of the parsed program stored in the .dep files.It is very simple.

Характеристики

Список файлов учебной работы

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6529
Авторов
на СтудИзбе
301
Средний доход
с одного платного файла
Обучение Подробнее