1 //===- unittests/CodeGen/BufferSourceTest.cpp - MemoryBuffer source tests -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/AST/ASTConsumer.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/AST/RecursiveASTVisitor.h"
12 #include "clang/Basic/TargetInfo.h"
13 #include "clang/CodeGen/ModuleBuilder.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Parse/ParseAST.h"
17 #include "clang/Sema/Sema.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/Support/Host.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "gtest/gtest.h"
23 
24 using namespace llvm;
25 using namespace clang;
26 
27 namespace {
28 
29 // Emitting constructors for global objects involves looking
30 // at the source file name. This makes sure that we don't crash
31 // if the source file is a memory buffer.
32 const char TestProgram[] =
33     "class EmitCXXGlobalInitFunc    "
34     "{                              "
35     "public:                        "
36     "   EmitCXXGlobalInitFunc() {}  "
37     "};                             "
38     "EmitCXXGlobalInitFunc test;    ";
39 
40 TEST(BufferSourceTest, EmitCXXGlobalInitFunc) {
41     LLVMContext Context;
42     CompilerInstance compiler;
43 
44     compiler.createDiagnostics();
45     compiler.getLangOpts().CPlusPlus = 1;
46     compiler.getLangOpts().CPlusPlus11 = 1;
47 
48     compiler.getTargetOpts().Triple = llvm::Triple::normalize(
49         llvm::sys::getProcessTriple());
50     compiler.setTarget(clang::TargetInfo::CreateTargetInfo(
51       compiler.getDiagnostics(),
52       std::make_shared<clang::TargetOptions>(
53         compiler.getTargetOpts())));
54 
55     compiler.createFileManager();
56     compiler.createSourceManager(compiler.getFileManager());
57     compiler.createPreprocessor(clang::TU_Prefix);
58 
59     compiler.createASTContext();
60 
61     compiler.setASTConsumer(std::unique_ptr<ASTConsumer>(
62         CreateLLVMCodeGen(
63             compiler.getDiagnostics(),
64             "EmitCXXGlobalInitFuncTest",
65             compiler.getHeaderSearchOpts(),
66             compiler.getPreprocessorOpts(),
67             compiler.getCodeGenOpts(),
68             Context)));
69 
70     compiler.createSema(clang::TU_Prefix, nullptr);
71 
72     clang::SourceManager &sm = compiler.getSourceManager();
73     sm.setMainFileID(sm.createFileID(
74         llvm::MemoryBuffer::getMemBuffer(TestProgram), clang::SrcMgr::C_User));
75 
76     clang::ParseAST(compiler.getSema(), false, false);
77 }
78 
79 } // end anonymous namespace
80