diff options
| author | Tim Foley <tfoleyNV@users.noreply.github.com> | 2019-02-15 09:08:19 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-02-15 09:08:19 -0800 |
| commit | a3fd4e2bc40cfc77db953b14744c30e7a18e7c1d (patch) | |
| tree | 5c226a6a4304086412c051f642a5f45fb043083c /source/slang/lower-to-ir.cpp | |
| parent | 4cd317bcae0a13dc2bbb78448c8d60cd1dcc76bd (diff) | |
Split front- and back-ends (#846)
* Split front- and back-ends
This change is a major refactor of several of the types that provide the behind-the-scenes implementation of the public C API.
The goal of this refactor is primarily to allow for future API services that let the user operate both the front- and back-ends of the compiler in a more complex fashion.
For example, as user should be able to compile a bunch of source code into modules, look up types, functions, etc. in those modules, specialize generic types/functions to the types they've looked up, and then finally request target code to be gernerated for specialized entry points.
The back-end code generation they trigger should re-use the front-end compilation work (parsing, semantic checking, IR generation) that was already performed.
The most visible change is that `CompileRequest` has been split up into several smaller types that take responsibility for parts of what it did:
* The `Linkage` type owns the storage for `import`ed modules, and well as the `TargetRequest`s that represent code-generation targets. The intention is that an application could use a single `Linkage` for the duration of its runtime (so long as it was okay with the memory usage), so that each `import`ed module only gets loaded once. For now, this type needs to manage the search paths, file system, and source manager, because of its responsibility for loading files.
* A `FrontEndCompileRequest` owns the stuff related to parsing, semantic checking, and initial IR generation. This most notably includes the `TranslationUnitRequest`s and the `FrontEndEntryPointRequest`s (which used to be just `EntryPointRequest`s). It's main job is to produce AST and IR modules for each translation unit, and to find and validate the entry points. The front-end request does *not* interact with generic arguments for global or entry-point generic parameters.
* The main output of both `import` operations and front-end translation units is the `Module` type, which is just a simple container for both the AST module (to service the reflection/layout APIs, and also for semantic checking of code that `import`s the module) and the IR module (for linking and code generation). This type captures the commonalities between the old `LoadedModule` (which is now just an alias for `Module`) and `TranslationUnitRequest` (which now owns a `Module`).
* The secondary output of front-end compilation is a `Program`, which comprises a list of referenced `Module`s and validated `EntryPoint`s that will be used together. Layout and code generation both need a `Program` to tell them what modules and entry points will be used together (we don't want to just code-gen everythin that has ever been loaded into the linakge). The `Program`s created by the front-end do not include generic arguments, so they may provide incomplete layout information and/or be unsuitable for code generation.
* A `BackEndCompileRequest` owns stuff related to turning a `Program` into output kernels for the targets of a `Linkage`. Most of the data it owns beyond the `Program` to be compiled is minor, so this is a good candidate for demotion from a heap-allocated object to just a `struct` of options that gets passed around.
* The `CompileRequestBase` type is an attempt to wrap up the common functionality of both front-end and back-end compile requests. Most of it is just exposing the availability of a linkage and `DiagnosticSink`, so this type is a good candidate for subsequent removal. The main interesting thing it has is the flags related to dumping and validation of IR, so there is probably a good refactoring still to be made around deciding how options should be handled going forward.
* Behind the scenes, the `Program` type is set up to handle some level of on-line compilation and layout work. The `Program` knows the `Linkage` it belongs to, and allows for a `TargetProgram` to be looked up based on a specific `TargetRequest`. A `TargetProgram` then allows layout information and compiled kernel code to be asked for on-demand, in order to support eventual "live" compilation scenarios.
* The `EndToEndCompileRequest` type is a composition/coordination type that replaces the old `CompileRequest` in a way that uses the services of the various other types. It owns a few pieces of state that only make sense in the context of an end-to-end compile (e.g., there is really no way to "pass through" code when the front- and back-ends are run separately) or a command-line compile (everything to do with specifying output paths for files is really just for the benefit of `slangc`, and might even be moved there over time).
* One important detail is that the `EndToEndCompilRequest` owns all of the string-based generic arguments for both global and entry-point generic parameters. The logic in `check.cpp` for dealing with those arguments has been heavily refactored to separate out the parsings steps that are specific to end-to-end compilation with string-based type arguments, and the semantic checking steps that result in a specialized `Program` (which can be exposed through new APIs that aren't tied to end-to-end compilation).
It is perhaps not surprising that this change had a lot of consequences, so I'll briefly run over some of the main categories of changes required:
* I changed the way that global generic arguments are passed via API (use `spSetGlobalGenericArgs` instead of the generic arguments for `spAddEntryPointEx`, which are not just for entry-point generics), which has been a change that we've needed for a long time. This is technically a breaking API change, although we should have very few client applications that care about it.
* A bunch of places that used to take "big" objects like `CompileRequest` now just take the sub-pieces they care about (e.g., a function might have only needed a `Linkage` and a `DiagnosticSink`). This makes many subroutines or "context" struct types more generally useful, at the cost of taking more parameters.
* In a few cases the conceptually clean separation of the layers breaks down (often for edge-case or compatibility features), and so we may pass along additional objects that are allowed to be null, but are used when present. A big example of this is how the back-end code generation routines accept an `EndToEndCompileRequest` that is optional, and only used to check whether "pass through" compilation is needed. We should probably look into cleaning this kind of logic up over time so that we don't need to violate the apparent separation of phases of compilation.
* In cases where separation of layers was being broken for the sake of GLSL features, I went ahead and ripped them out, since all of that should be dead code anyway.
* In many cases I increased the encapsulation of data in the core types to help track down use sites and make sure they are following invariants better.
* In cases where code was doing, e.g., `context->shared->compileRequest->session->getThing()` I have tried to introduce convenience routines so that the usage site is just `context->getThing()` to improve encapsulation and allow changes to be made more easily going forward.
* The `noteInternalErrorLoc` functionality was moved off of the compile request and into `DiagnosticSink`, since that is the one type you can rely on having around when you want to note an internal error. We may consider going forward if (and how) it should reset the counter used for noting locations on internal errors.
* A few APIs now take `DiagnosticSink*` arguments where they didn't before, and as a result some public APIs need to create `DiagnosticSink`s to pass in, before going ahead and ignoring the messages. In the future there should be variations of these APIs that accept an `ISlangBlob**` parameter for the output.
* fixup: missing include for compilers with accurate template checking (non-VS)
* fixup: review feedback
Diffstat (limited to 'source/slang/lower-to-ir.cpp')
| -rw-r--r-- | source/slang/lower-to-ir.cpp | 225 |
1 files changed, 154 insertions, 71 deletions
diff --git a/source/slang/lower-to-ir.cpp b/source/slang/lower-to-ir.cpp index 0d9427b08..b53bb8ebb 100644 --- a/source/slang/lower-to-ir.cpp +++ b/source/slang/lower-to-ir.cpp @@ -300,8 +300,18 @@ struct IRGenEnv struct SharedIRGenContext { - CompileRequest* compileRequest; - ModuleDecl* mainModuleDecl; + SharedIRGenContext( + Session* session, + DiagnosticSink* sink, + ModuleDecl* mainModuleDecl = nullptr) + : m_session(session) + , m_sink(sink) + , m_mainModuleDecl(mainModuleDecl) + {} + + Session* m_session = nullptr; + DiagnosticSink* m_sink = nullptr; + ModuleDecl* m_mainModuleDecl = nullptr; // The "global" environment for mapping declarations to their IR values. IRGenEnv globalEnv; @@ -356,17 +366,17 @@ struct IRGenContext Session* getSession() { - return shared->compileRequest->mSession; + return shared->m_session; } - CompileRequest* getCompileRequest() + DiagnosticSink* getSink() { - return shared->compileRequest; + return shared->m_sink; } - DiagnosticSink* getSink() + ModuleDecl* getMainModuleDecl() { - return &getCompileRequest()->mSink; + return shared->m_mainModuleDecl; } }; @@ -422,7 +432,7 @@ bool isImportedDecl(IRGenContext* context, Decl* decl) if (isFromStdLib(decl)) return false; - if (moduleDecl != context->shared->mainModuleDecl) + if (moduleDecl != context->getMainModuleDecl()) return true; return false; @@ -1735,16 +1745,31 @@ static String getNameForNameHint( if(auto genericParentDecl = as<GenericDecl>(parentDecl)) parentDecl = genericParentDecl->ParentDecl; + // A `ModuleDecl` can have a name too, but in the common case + // we don't want to generate name hints that include the module + // name, simply because they would lead to every global symbol + // getting a much longer name. + // + // TODO: We should probably include the module name for symbols + // being `import`ed, and not for symbols being compiled directly + // (those coming from a module that had no name given to it). + // + // For now we skip past a `ModuleDecl` parent. + // + if(auto moduleParentDecl = as<ModuleDecl>(parentDecl)) + parentDecl = moduleParentDecl->ParentDecl; + + if(!parentDecl) + { + return leafName->text; + } + auto parentName = getNameForNameHint(context, parentDecl); if(parentName.Length() == 0) { return leafName->text; } - // TODO: at some point we will start giving `ModuleDecl`s names, - // and in that case we need to think carefully about whether to - // include their names here or not. - // We will now construct a new `Name` to use as the hint, // combining the name of the parent and the leaf declaration. @@ -3603,7 +3628,7 @@ void lowerStmt( catch(AbortCompilationException&) { throw; } catch(...) { - context->getCompileRequest()->noteInternalErrorLoc(stmt->loc); + context->getSink()->noteInternalErrorLoc(stmt->loc); throw; } } @@ -5877,7 +5902,7 @@ LoweredValInfo lowerDecl( catch(AbortCompilationException&) { throw; } catch(...) { - context->getCompileRequest()->noteInternalErrorLoc(decl->loc); + context->getSink()->noteInternalErrorLoc(decl->loc); throw; } } @@ -6108,56 +6133,59 @@ LoweredValInfo emitDeclRef( type); } -static void lowerEntryPointToIR( - IRGenContext* context, - EntryPointRequest* entryPointRequest) +static void lowerFrontEndEntryPointToIR( + IRGenContext* context, + EntryPoint* entryPoint) { - // First, lower the entry point like an ordinary function + // TODO: We should emit an entry point as a dedicated IR function + // (distinct from the IR function used if it were called normally), + // with a mangled name based on the original function name plus + // the stage for which it is being compiled as an entry point (so + // that entry points for distinct stages always have distinct names). + // + // For now we just have an (implicit) constraint that a given + // function should only be used as an entry point for one stage, + // and any such function should *not* be used as an ordinary function. - auto session = context->getSession(); - auto entryPointFuncDeclRef = entryPointRequest->getFuncDeclRef(); - auto entryPointFuncType = lowerType(context, getFuncType(session, entryPointFuncDeclRef)); + auto entryPointFuncDecl = entryPoint->getFuncDecl(); auto builder = context->irBuilder; builder->setInsertInto(builder->getModule()->getModuleInst()); auto loweredEntryPointFunc = getSimpleVal(context, - emitDeclRef(context, entryPointFuncDeclRef, entryPointFuncType)); + ensureDecl(context, entryPointFuncDecl)); // Attach a marker decoration so that we recognize // this as an entry point. // - builder->addEntryPointDecoration(loweredEntryPointFunc); - - // - if(!loweredEntryPointFunc->findDecoration<IRLinkageDecoration>()) + IRInst* instToDecorate = loweredEntryPointFunc; + if(auto irGeneric = as<IRGeneric>(instToDecorate)) { - builder->addExportDecoration(loweredEntryPointFunc, getMangledName(entryPointFuncDeclRef).getUnownedSlice()); + instToDecorate = findGenericReturnVal(irGeneric); } + builder->addEntryPointDecoration(instToDecorate); +} - // Now lower all the arguments supplied for global generic - // type parameters. - // - for (RefPtr<Substitutions> subst = entryPointRequest->globalGenericSubst; subst; subst = subst->outer) - { - auto gSubst = subst.as<GlobalGenericParamSubstitution>(); - if(!gSubst) - continue; +static void lowerProgramEntryPointToIR( + IRGenContext* context, + EntryPoint* entryPoint) +{ + // First, lower the entry point like an ordinary function - IRInst* typeParam = getSimpleVal(context, ensureDecl(context, gSubst->paramDecl)); - IRType* typeVal = lowerType(context, gSubst->actualType); + auto session = context->getSession(); + auto entryPointFuncDeclRef = entryPoint->getFuncDeclRef(); + auto entryPointFuncType = lowerType(context, getFuncType(session, entryPointFuncDeclRef)); - // bind `typeParam` to `typeVal` - builder->emitBindGlobalGenericParam(typeParam, typeVal); + auto builder = context->irBuilder; + builder->setInsertInto(builder->getModule()->getModuleInst()); - for (auto& constraintArg : gSubst->constraintArgs) - { - IRInst* constraintParam = getSimpleVal(context, ensureDecl(context, constraintArg.decl)); - IRInst* constraintVal = lowerSimpleVal(context, constraintArg.val); + auto loweredEntryPointFunc = getSimpleVal(context, + emitDeclRef(context, entryPointFuncDeclRef, entryPointFuncType)); - // bind `constraintParam` to `constraintVal` - builder->emitBindGlobalGenericParam(constraintParam, constraintVal); - } + // + if(!loweredEntryPointFunc->findDecoration<IRLinkageDecoration>()) + { + builder->addExportDecoration(loweredEntryPointFunc, getMangledName(entryPointFuncDeclRef).getUnownedSlice()); } } @@ -6191,19 +6219,19 @@ IRModule* generateIRForTranslationUnit( { auto compileRequest = translationUnit->compileRequest; - SharedIRGenContext sharedContextStorage; + SharedIRGenContext sharedContextStorage( + translationUnit->getSession(), + translationUnit->compileRequest->getSink(), + translationUnit->getModuleDecl()); SharedIRGenContext* sharedContext = &sharedContextStorage; - sharedContext->compileRequest = compileRequest; - sharedContext->mainModuleDecl = translationUnit->SyntaxNode; - IRGenContext contextStorage(sharedContext); IRGenContext* context = &contextStorage; SharedIRBuilder sharedBuilderStorage; SharedIRBuilder* sharedBuilder = &sharedBuilderStorage; sharedBuilder->module = nullptr; - sharedBuilder->session = compileRequest->mSession; + sharedBuilder->session = compileRequest->getSession(); IRBuilder builderStorage; IRBuilder* builder = &builderStorage; @@ -6224,12 +6252,13 @@ IRModule* generateIRForTranslationUnit( // in case they require special handling. for (auto entryPoint : translationUnit->entryPoints) { - lowerEntryPointToIR(context, entryPoint); + lowerFrontEndEntryPointToIR(context, entryPoint); } + // // Next, ensure that all other global declarations have // been emitted. - for (auto decl : translationUnit->SyntaxNode->Members) + for (auto decl : translationUnit->getModuleDecl()->Members) { ensureAllDeclsRec(context, decl); } @@ -6271,12 +6300,12 @@ IRModule* generateIRForTranslationUnit( // Propagate `constexpr`-ness through the dataflow graph (and the // call graph) based on constraints imposed by different instructions. - propagateConstExpr(module, &compileRequest->mSink); + propagateConstExpr(module, compileRequest->getSink()); // TODO: give error messages if any `undefined` or // `unreachable` instructions remain. - checkForMissingReturns(module, &compileRequest->mSink); + checkForMissingReturns(module, compileRequest->getSink()); // TODO: consider doing some more aggressive optimizations // (in particular specialization of generics) here, so @@ -6293,28 +6322,82 @@ IRModule* generateIRForTranslationUnit( // then we can dump the initial IR for the module here. if(compileRequest->shouldDumpIR) { - ISlangWriter* writer = translationUnit->compileRequest->getWriter(WriterChannel::StdError); - - dumpIR(module, writer); + DiagnosticSinkWriter writer(compileRequest->getSink()); + dumpIR(module, &writer); } return module; } -#if 0 -String emitSlangIRAssemblyForEntryPoint( - EntryPointRequest* entryPoint) +RefPtr<IRModule> generateIRForProgram( + Session* session, + Program* program, + DiagnosticSink* sink) { - auto compileRequest = entryPoint->compileRequest; - auto irModule = lowerEntryPointToIR( - entryPoint, - compileRequest->layout.Ptr(), - // TODO: we need to pick the target more carefully here - CodeGenTarget::HLSL); - - return getSlangIRAssembly(irModule); -} -#endif +// auto compileRequest = translationUnit->compileRequest; + + SharedIRGenContext sharedContextStorage( + session, + sink); + SharedIRGenContext* sharedContext = &sharedContextStorage; + + IRGenContext contextStorage(sharedContext); + IRGenContext* context = &contextStorage; + + SharedIRBuilder sharedBuilderStorage; + SharedIRBuilder* sharedBuilder = &sharedBuilderStorage; + sharedBuilder->module = nullptr; + sharedBuilder->session = session; + + IRBuilder builderStorage; + IRBuilder* builder = &builderStorage; + builder->sharedBuilder = sharedBuilder; + + RefPtr<IRModule> module = builder->createModule(); + sharedBuilder->module = module; + + context->irBuilder = builder; + + // We need to emit symbols for all of the entry + // points in the program; this is especially + // important in the case where a generic entry + // point is being specialized. + // + for(auto entryPoint : program->getEntryPoints()) + { + lowerProgramEntryPointToIR(context, entryPoint); + } + + // Now lower all the arguments supplied for global generic + // type parameters. + // + for (RefPtr<Substitutions> subst = program->getGlobalGenericSubstitution(); subst; subst = subst->outer) + { + auto gSubst = subst.as<GlobalGenericParamSubstitution>(); + if(!gSubst) + continue; + + IRInst* typeParam = getSimpleVal(context, ensureDecl(context, gSubst->paramDecl)); + IRType* typeVal = lowerType(context, gSubst->actualType); + + // bind `typeParam` to `typeVal` + builder->emitBindGlobalGenericParam(typeParam, typeVal); + + for (auto& constraintArg : gSubst->constraintArgs) + { + IRInst* constraintParam = getSimpleVal(context, ensureDecl(context, constraintArg.decl)); + IRInst* constraintVal = lowerSimpleVal(context, constraintArg.val); + + // bind `constraintParam` to `constraintVal` + builder->emitBindGlobalGenericParam(constraintParam, constraintVal); + } + } + + // TODO: Should we apply any of the validation or + // mandatory optimization passes here? + + return module; +} } // namespace Slang |
