FDVM_DD (1158349)

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

Текст из файла

28


Fortran DVM Compiler

Detailed design

Март 30, 1999

Keldysh Institute of Applied Mathematics

Russia Academy of Sciences

Contents

1 Introduction 3

2 The General Scheme of Compiler 4

2.1 Parsing 4

2.2 Transforming internal form 4

2.3 Generating source code 5

3 Basic Data Structures 5

3.1 Parse Tree 5

3.2 Symbol and Type Table 5

4 Detailed Description of Basic Modules 7

4.1 Distributed Array Creation and Remapping 12

4.2 Distributed array referencing 16

4.3 Parallel loop 18

4.4 Input/Output (io.cpp module) 21

4.5 Inserting new statements in parse tree (stmt.cpp module) 24

1 Introduction

This report presents the detailed description of the Fortran-DVM (FDVM) compiler implementation. The basic data structures, the control scheme, and the functions of compiler modules are considered.

Fortran-DVM is the Fortran 77 language which is extended by special annotations for specifying parallel execution of the program. These annotations are called DVM directives. The FDVM compiler translates the parallel FDVM code into Fortran 77 code including Lib-DVM library calls.

The following command line start the compiler up:

fdvm [ options ] source-file

Source FDVM program is placed into input file source-file.

On the command-line options are the compiler options.

Overall options.

-o file

Place output in file file.

-s

Produce sequential code (DVM directives are ignored.)

-p

Produce parallel code.

By default, FDVM compiler produces parallel code.

-v

Print (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler.

-Idir

Append directory dir to the list of directories searched for include files.

Debugging options.

-dlevel

Generate extra code for debugging FDVM program. Use level to specify how much information.

Level 0 – The information about loops and iterations is accumulated.

Level 1 - In addition to the previous level the information about

Modifications of distributed arrays is accumulated.

Level 2 - In addition to the previous level the information about

all the usage of distributed arrays is accumulated.

Level 3 - In addition to the level 1 the information about modification

of all the variables is accumulated.

Level 4 - In addition to the previous level the information about

The usage of all the variables is accumulated.

-elevel

Generate extra code for performance analyzing FDVM program. Use level to specify how much information.

Level 1 – The execution time characteristics of all the parallel

Loops and surrounding sequential loops are accumulated.

Level 2 – The execution characteristics of all the user specified

Intervals of program are accumulated.

Level 3 – Combination of the level 1 and 2.

Level 4 – The execution characteristics of all the the loops and the user specified intervals are accumulated.

2 The General Scheme of Compiler

Sage ++ system is used as a tool for designing FDVM compiler.

Sage++ is an object oriented toolkit for building program transformation systems for Fortran 77, Fortran 90, C and C++ languages. It is designed as an open C++ class library that provides the user with a set of parsers, a structured parse tree, a symbol and type table. The heart of the system is a set of functions that allow to restructure the parse tree and a mechanism (called unparsing) for generating new source code from the restructured internal form.

The FDVM compiler consists of three components:

  • Parsing

  • Transforming internal form

  • Generating source code

2.1 Parsing

The Fortran parser of Sage++ which is based on the GNU Bison version of YACC is extended to add language extensions (DVM directives) to Fortran system. It consists of the following modules:

ftn.gram

- grammar rules for Fortran

fdvm.gram

- grammar rules for Fortran DVM

lexfdvm.c

- lexical analyzer

tag

- variant tag list

tokens

- lexeme list

gram1.tab.c

- parser generated by Bison

cftn.c

- main routine (calls parser, opens and closes the files that are

needed)

init.c

- initialization routines

stat.c

- routines for creating internal form of statements (bif node of

parse tree)

errors.c

- printing error messages

sym.c

-Symbol table routines

types.c

- routines to handle the variable declarations

lists.c

- routines to build the lists

misc.c

- miscellaneous help routines

hash.c

- hash table routine

The parser reads the source, checks the concrete syntax, constructs a parse tree, and writes its internal representation in a .dep file.

2.2 Transforming internal form

Second phase of compiling involves analyzing and restructuring internal representation of FDVM program. A DVM directive is substituted for a sequence of Lib-DVM function calls. Afterwards new source code is generated from restructured internal form.

Back-end of the compiler is written in C++ language using Sage++ class library.

The Sage++ library is organized as a class hierarchy that provides access to the parse tree, symbol table and type table for each file in an application project. There are five basic families of classes in the library: Project and Files, Statements, Expressions, Symbols, and Types.

Project and Files correspond to source files. Statements correspond to the basic source statements in Fortran 77 and DVM directives. Expressions are contained within statements. Symbols are the basic user defined identifiers. Types are associated with each identifier and expression.

In addition, the SgAttribute class allows the users to add their own information to Sage++ objects.

The file libSage++.h contains all the class definitions.

There are six modules in the translator:

dvm.cpp

- analyzing and restructuring parse tree

funcall.cpp

- generating LibDVM library calls

stmt.cpp

- generating new statement and inserting it into the procedure

io.cpp

- translating I/O statements

debug.cpp

- support of debugging mode

help.cpp

- miscellaneous help routines

2.3 Generating source code

Generating new source code from the restructured internal form is implemented by the File class member function (unparse( )) of Sage++ class library.

3 Basic Data Structures

The definitions of data structures of internal representation are contained in the files:

  • bif.h (parse tree node for statement)

  • ll.h (parse tree node for expression)

  • symb.h (Symbol and Type Table elements)

3.1 Parse Tree

The structures of parse tree nodes for a statement and an expression are given in Fig. 3.1 and Fig.3.2 accordingly. The Fig. 3.4 illustrates the fragment of parse tree.

3.2 Symbol and Type Table

The Fig.3.3 presents the Symbol and Type Table entries.

variant tag

identification tag

index

global line number

local line number

declaration specifier

pointer to the label

pointer to the next statement node

pointer to the source filename

pointer to the control parent node

property list

list of nodes(list of procedures)

pointer to the comment

symbol table entry

L-value expr tree

R-value expr tree

spare expr tree

do-label (used by do)

null

null

null

null

Fig. 3.1. Parse tree node representing a statement (bif node).

variant tag

identification tag

pointer to the next node (by allocation order)

pointer to the Type table element

constant value

pointer to the Symbol table element

L-value expr tree

R-value expr tree

Fig. 3.2. Parse tree node representing an expression (low level node).

Identifier

variant tag

next entry

identification tag

Symbol table entry

identifier

Hash table entry

special list

special list

special list

next Symbol table entry

Type table entry

scope

use-definition chain

attributes (mask)

do-variable flag

parser used

pointer to value ( for constants)

Fig.3.3. Hash and Symbol table entries

special fields

Parse Tree


next

control parent

ASSIGN_STAT

. . .

. . .


VAR_REF

...

+

...



VAR_REF

...

VAR_REF

...

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

Тип файла документ

Документы такого типа открываются такими программами, как Microsoft Office Word на компьютерах Windows, Apple Pages на компьютерах Mac, Open Office - бесплатная альтернатива на различных платформах, в том числе Linux. Наиболее простым и современным решением будут Google документы, так как открываются онлайн без скачивания прямо в браузере на любой платформе. Существуют российские качественные аналоги, например от Яндекса.

Будьте внимательны на мобильных устройствах, так как там используются упрощённый функционал даже в официальном приложении от Microsoft, поэтому для просмотра скачивайте PDF-версию. А если нужно редактировать файл, то используйте оригинальный файл.

Файлы такого типа обычно разбиты на страницы, а текст может быть форматированным (жирный, курсив, выбор шрифта, таблицы и т.п.), а также в него можно добавлять изображения. Формат идеально подходит для рефератов, докладов и РПЗ курсовых проектов, которые необходимо распечатать. Кстати перед печатью также сохраняйте файл в PDF, так как принтер может начудить со шрифтами.

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

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