llvm.org GIT mirror llvm / 1ef8bda
For PR351: * Place a try/catch block around the entire tool to Make sure std::string exceptions are caught and printed before exiting the tool. * Make sure we catch unhandled exceptions at the top level so that we don't abort with a useless message but indicate than an unhandled exception was generated. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@19192 91177308-0d34-0410-b5e6-96231b3b80d8 Reid Spencer 14 years ago
17 changed file(s) with 994 addition(s) and 886 deletion(s). Raw diff Collapse all Expand all
115115 }
116116
117117 int main(int argc, char **argv) {
118 cl::ParseCommandLineOptions(argc, argv, " llvm analysis printer tool\n");
119 sys::PrintStackTraceOnErrorSignal();
118 try {
119 cl::ParseCommandLineOptions(argc, argv, " llvm analysis printer tool\n");
120 sys::PrintStackTraceOnErrorSignal();
120121
121 Module *CurMod = 0;
122 try {
122 Module *CurMod = 0;
123 try {
123124 #if 0
124 TimeRegion RegionTimer(BytecodeLoadTimer);
125 TimeRegion RegionTimer(BytecodeLoadTimer);
125126 #endif
126 CurMod = ParseBytecodeFile(InputFilename);
127 if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename))){
128 std::cerr << argv[0] << ": input file didn't read correctly.\n";
127 CurMod = ParseBytecodeFile(InputFilename);
128 if (!CurMod && !(CurMod = ParseAssemblyFile(InputFilename))){
129 std::cerr << argv[0] << ": input file didn't read correctly.\n";
130 return 1;
131 }
132 } catch (const ParseException &E) {
133 std::cerr << argv[0] << ": " << E.getMessage() << "\n";
129134 return 1;
130135 }
131 } catch (const ParseException &E) {
132 std::cerr << argv[0] << ": " << E.getMessage() << "\n";
133 return 1;
136
137 // Create a PassManager to hold and optimize the collection of passes we are
138 // about to build...
139 //
140 PassManager Passes;
141
142 // Add an appropriate TargetData instance for this module...
143 Passes.add(new TargetData("analyze", CurMod));
144
145 // Make sure the input LLVM is well formed.
146 if (!NoVerify)
147 Passes.add(createVerifierPass());
148
149 // Create a new optimization pass for each one specified on the command line
150 for (unsigned i = 0; i < AnalysesList.size(); ++i) {
151 const PassInfo *Analysis = AnalysesList[i];
152
153 if (Analysis->getNormalCtor()) {
154 Pass *P = Analysis->getNormalCtor()();
155 Passes.add(P);
156
157 if (BasicBlockPass *BBP = dynamic_cast(P))
158 Passes.add(new BasicBlockPassPrinter(Analysis));
159 else if (FunctionPass *FP = dynamic_cast(P))
160 Passes.add(new FunctionPassPrinter(Analysis));
161 else
162 Passes.add(new ModulePassPrinter(Analysis));
163
164 } else
165 std::cerr << argv[0] << ": cannot create pass: "
166 << Analysis->getPassName() << "\n";
167 }
168
169 Passes.run(*CurMod);
170
171 delete CurMod;
172 return 0;
173
174 } catch (const std::string& msg) {
175 std::cerr << argv[0] << ": " << msg << "\n";
176 } catch (...) {
177 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
134178 }
135
136 // Create a PassManager to hold and optimize the collection of passes we are
137 // about to build...
138 //
139 PassManager Passes;
140
141 // Add an appropriate TargetData instance for this module...
142 Passes.add(new TargetData("analyze", CurMod));
143
144 // Make sure the input LLVM is well formed.
145 if (!NoVerify)
146 Passes.add(createVerifierPass());
147
148 // Create a new optimization pass for each one specified on the command line
149 for (unsigned i = 0; i < AnalysesList.size(); ++i) {
150 const PassInfo *Analysis = AnalysesList[i];
151
152 if (Analysis->getNormalCtor()) {
153 Pass *P = Analysis->getNormalCtor()();
154 Passes.add(P);
155
156 if (BasicBlockPass *BBP = dynamic_cast(P))
157 Passes.add(new BasicBlockPassPrinter(Analysis));
158 else if (FunctionPass *FP = dynamic_cast(P))
159 Passes.add(new FunctionPassPrinter(Analysis));
160 else
161 Passes.add(new ModulePassPrinter(Analysis));
162
163 } else
164 std::cerr << argv[0] << ": cannot create pass: "
165 << Analysis->getPassName() << "\n";
166 }
167
168 Passes.run(*CurMod);
169
170 delete CurMod;
171 return 0;
179 return 1;
172180 }
5050 return D.run();
5151 } catch (ToolExecutionError &TEE) {
5252 std::cerr << "Tool execution error: " << TEE.what() << '\n';
53 return 1;
53 } catch (const std::string& msg) {
54 std::cerr << argv[0] << ": " << msg << "\n";
5455 } catch (...) {
5556 std::cerr << "Whoops, an exception leaked out of bugpoint. "
5657 << "This is a bug in bugpoint!\n";
57 return 1;
5858 }
59 return 1;
5960 }
4444 cl::value_desc("function"));
4545
4646 int main(int argc, char **argv) {
47 cl::ParseCommandLineOptions(argc, argv, " llvm extractor\n");
48 sys::PrintStackTraceOnErrorSignal();
47 try {
48 cl::ParseCommandLineOptions(argc, argv, " llvm extractor\n");
49 sys::PrintStackTraceOnErrorSignal();
4950
50 std::auto_ptr M(ParseBytecodeFile(InputFilename));
51 if (M.get() == 0) {
52 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
53 return 1;
54 }
55
56 // Figure out which function we should extract
57 Function *F = M.get()->getNamedFunction(ExtractFunc);
58 if (F == 0) {
59 std::cerr << argv[0] << ": program doesn't contain function named '"
60 << ExtractFunc << "'!\n";
61 return 1;
62 }
63
64 // In addition to deleting all other functions, we also want to spiff it up a
65 // little bit. Do this now.
66 //
67 PassManager Passes;
68 Passes.add(new TargetData("extract", M.get())); // Use correct TargetData
69 // Either isolate the function or delete it from the Module
70 Passes.add(createFunctionExtractionPass(F, DeleteFn));
71 Passes.add(createGlobalDCEPass()); // Delete unreachable globals
72 Passes.add(createFunctionResolvingPass()); // Delete prototypes
73 Passes.add(createDeadTypeEliminationPass()); // Remove dead types...
74
75 std::ostream *Out = 0;
76
77 if (OutputFilename != "-") { // Not stdout?
78 if (!Force && std::ifstream(OutputFilename.c_str())) {
79 // If force is not specified, make sure not to overwrite a file!
80 std::cerr << argv[0] << ": error opening '" << OutputFilename
81 << "': file exists!\n"
82 << "Use -f command line argument to force output\n";
51 std::auto_ptr M(ParseBytecodeFile(InputFilename));
52 if (M.get() == 0) {
53 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
8354 return 1;
8455 }
85 Out = new std::ofstream(OutputFilename.c_str());
86 } else { // Specified stdout
87 Out = &std::cout;
56
57 // Figure out which function we should extract
58 Function *F = M.get()->getNamedFunction(ExtractFunc);
59 if (F == 0) {
60 std::cerr << argv[0] << ": program doesn't contain function named '"
61 << ExtractFunc << "'!\n";
62 return 1;
63 }
64
65 // In addition to deleting all other functions, we also want to spiff it up a
66 // little bit. Do this now.
67 //
68 PassManager Passes;
69 Passes.add(new TargetData("extract", M.get())); // Use correct TargetData
70 // Either isolate the function or delete it from the Module
71 Passes.add(createFunctionExtractionPass(F, DeleteFn));
72 Passes.add(createGlobalDCEPass()); // Delete unreachable globals
73 Passes.add(createFunctionResolvingPass()); // Delete prototypes
74 Passes.add(createDeadTypeEliminationPass()); // Remove dead types...
75
76 std::ostream *Out = 0;
77
78 if (OutputFilename != "-") { // Not stdout?
79 if (!Force && std::ifstream(OutputFilename.c_str())) {
80 // If force is not specified, make sure not to overwrite a file!
81 std::cerr << argv[0] << ": error opening '" << OutputFilename
82 << "': file exists!\n"
83 << "Use -f command line argument to force output\n";
84 return 1;
85 }
86 Out = new std::ofstream(OutputFilename.c_str());
87 } else { // Specified stdout
88 Out = &std::cout;
89 }
90
91 Passes.add(new WriteBytecodePass(Out)); // Write bytecode to file...
92 Passes.run(*M.get());
93
94 if (Out != &std::cout)
95 delete Out;
96 return 0;
97 } catch (const std::string& msg) {
98 std::cerr << argv[0] << ": " << msg << "\n";
99 } catch (...) {
100 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
88101 }
89
90 Passes.add(new WriteBytecodePass(Out)); // Write bytecode to file...
91 Passes.run(*M.get());
92
93 if (Out != &std::cout)
94 delete Out;
95 return 0;
102 return 1;
96103 }
127127
128128
129129 int main(int argc, char **argv) {
130 cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");
131 sys::PrintStackTraceOnErrorSignal();
132
133 std::auto_ptr M;
134130 try {
135 // Parse the file now...
136 M.reset(ParseAssemblyFile(InputFilename));
137 } catch (const ParseException &E) {
138 std::cerr << argv[0] << ": " << E.getMessage() << "\n";
139 return 1;
131 cl::ParseCommandLineOptions(argc, argv,
132 " llvm .s -> .o assembler for GCC\n");
133 sys::PrintStackTraceOnErrorSignal();
134
135 std::auto_ptr M;
136 try {
137 // Parse the file now...
138 M.reset(ParseAssemblyFile(InputFilename));
139 } catch (const ParseException &E) {
140 std::cerr << argv[0] << ": " << E.getMessage() << "\n";
141 return 1;
142 }
143
144 if (M.get() == 0) {
145 std::cerr << argv[0] << ": assembly didn't read correctly.\n";
146 return 1;
147 }
148
149 std::ostream *Out = 0;
150 if (OutputFilename == "") { // Didn't specify an output filename?
151 if (InputFilename == "-") {
152 OutputFilename = "-";
153 } else {
154 std::string IFN = InputFilename;
155 int Len = IFN.length();
156 if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s?
157 OutputFilename = std::string(IFN.begin(), IFN.end()-2);
158 } else {
159 OutputFilename = IFN; // Append a .o to it
160 }
161 OutputFilename += ".o";
162 }
163 }
164
165 if (OutputFilename == "-")
166 Out = &std::cout;
167 else {
168 Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);
169
170 // Make sure that the Out file gets unlinked from the disk if we get a
171 // signal
172 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
173 }
174
175
176 if (!Out->good()) {
177 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
178 return 1;
179 }
180
181 // In addition to just parsing the input from GCC, we also want to spiff it up
182 // a little bit. Do this now.
183 //
184 PassManager Passes;
185
186 // Add an appropriate TargetData instance for this module...
187 Passes.add(new TargetData("gccas", M.get()));
188
189 // Add all of the transformation passes to the pass manager to do the cleanup
190 // and optimization of the GCC output.
191 //
192 AddConfiguredTransformationPasses(Passes);
193
194 // Make sure everything is still good.
195 Passes.add(createVerifierPass());
196
197 // Write bytecode to file...
198 Passes.add(new WriteBytecodePass(Out,false,!NoCompress));
199
200 // Run our queue of passes all at once now, efficiently.
201 Passes.run(*M.get());
202
203 if (Out != &std::cout) delete Out;
204 return 0;
205 } catch (const std::string& msg) {
206 std::cerr << argv[0] << ": " << msg << "\n";
207 } catch (...) {
208 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
140209 }
141
142 if (M.get() == 0) {
143 std::cerr << argv[0] << ": assembly didn't read correctly.\n";
144 return 1;
145 }
146
147 std::ostream *Out = 0;
148 if (OutputFilename == "") { // Didn't specify an output filename?
149 if (InputFilename == "-") {
150 OutputFilename = "-";
151 } else {
152 std::string IFN = InputFilename;
153 int Len = IFN.length();
154 if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s?
155 OutputFilename = std::string(IFN.begin(), IFN.end()-2);
156 } else {
157 OutputFilename = IFN; // Append a .o to it
158 }
159 OutputFilename += ".o";
160 }
161 }
162
163 if (OutputFilename == "-")
164 Out = &std::cout;
165 else {
166 Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);
167
168 // Make sure that the Out file gets unlinked from the disk if we get a
169 // signal
170 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
171 }
172
173
174 if (!Out->good()) {
175 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
176 return 1;
177 }
178
179 // In addition to just parsing the input from GCC, we also want to spiff it up
180 // a little bit. Do this now.
181 //
182 PassManager Passes;
183
184 // Add an appropriate TargetData instance for this module...
185 Passes.add(new TargetData("gccas", M.get()));
186
187 // Add all of the transformation passes to the pass manager to do the cleanup
188 // and optimization of the GCC output.
189 //
190 AddConfiguredTransformationPasses(Passes);
191
192 // Make sure everything is still good.
193 Passes.add(createVerifierPass());
194
195 // Write bytecode to file...
196 Passes.add(new WriteBytecodePass(Out,false,!NoCompress));
197
198 // Run our queue of passes all at once now, efficiently.
199 Passes.run(*M.get());
200
201 if (Out != &std::cout) delete Out;
202 return 0;
203 }
210 return 1;
211 }
6262 // main - Entry point for the llc compiler.
6363 //
6464 int main(int argc, char **argv) {
65 cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
66 sys::PrintStackTraceOnErrorSignal();
65 try {
66 cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
67 sys::PrintStackTraceOnErrorSignal();
6768
68 // Load the module to be compiled...
69 std::auto_ptr M(ParseBytecodeFile(InputFilename));
70 if (M.get() == 0) {
71 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
72 return 1;
73 }
74 Module &mod = *M.get();
75
76 // Allocate target machine. First, check whether the user has
77 // explicitly specified an architecture to compile for.
78 TargetMachine* (*TargetMachineAllocator)(const Module&,
79 IntrinsicLowering *) = 0;
80 if (MArch == 0) {
81 std::string Err;
82 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
83 if (MArch == 0) {
84 std::cerr << argv[0] << ": error auto-selecting target for module '"
85 << Err << "'. Please use the -march option to explicitly "
86 << "pick a target.\n";
69 // Load the module to be compiled...
70 std::auto_ptr M(ParseBytecodeFile(InputFilename));
71 if (M.get() == 0) {
72 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
8773 return 1;
8874 }
89 }
75 Module &mod = *M.get();
9076
91 std::auto_ptr target(MArch->CtorFn(mod, 0));
92 assert(target.get() && "Could not allocate target machine!");
93 TargetMachine &Target = *target.get();
94 const TargetData &TD = Target.getTargetData();
95
96 // Build up all of the passes that we want to do to the module...
97 PassManager Passes;
98 Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
99 TD.getPointerAlignment(), TD.getDoubleAlignment()));
100
101 // Figure out where we are going to send the output...
102 std::ostream *Out = 0;
103 if (OutputFilename != "") {
104 if (OutputFilename != "-") {
105 // Specified an output filename?
106 if (!Force && std::ifstream(OutputFilename.c_str())) {
107 // If force is not specified, make sure not to overwrite a file!
108 std::cerr << argv[0] << ": error opening '" << OutputFilename
109 << "': file exists!\n"
110 << "Use -f command line argument to force output\n";
77 // Allocate target machine. First, check whether the user has
78 // explicitly specified an architecture to compile for.
79 TargetMachine* (*TargetMachineAllocator)(const Module&,
80 IntrinsicLowering *) = 0;
81 if (MArch == 0) {
82 std::string Err;
83 MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);
84 if (MArch == 0) {
85 std::cerr << argv[0] << ": error auto-selecting target for module '"
86 << Err << "'. Please use the -march option to explicitly "
87 << "pick a target.\n";
11188 return 1;
11289 }
113 Out = new std::ofstream(OutputFilename.c_str());
90 }
11491
115 // Make sure that the Out file gets unlinked from the disk if we get a
116 // SIGINT
117 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
92 std::auto_ptr target(MArch->CtorFn(mod, 0));
93 assert(target.get() && "Could not allocate target machine!");
94 TargetMachine &Target = *target.get();
95 const TargetData &TD = Target.getTargetData();
96
97 // Build up all of the passes that we want to do to the module...
98 PassManager Passes;
99 Passes.add(new TargetData("llc", TD.isLittleEndian(), TD.getPointerSize(),
100 TD.getPointerAlignment(), TD.getDoubleAlignment()));
101
102 // Figure out where we are going to send the output...
103 std::ostream *Out = 0;
104 if (OutputFilename != "") {
105 if (OutputFilename != "-") {
106 // Specified an output filename?
107 if (!Force && std::ifstream(OutputFilename.c_str())) {
108 // If force is not specified, make sure not to overwrite a file!
109 std::cerr << argv[0] << ": error opening '" << OutputFilename
110 << "': file exists!\n"
111 << "Use -f command line argument to force output\n";
112 return 1;
113 }
114 Out = new std::ofstream(OutputFilename.c_str());
115
116 // Make sure that the Out file gets unlinked from the disk if we get a
117 // SIGINT
118 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
119 } else {
120 Out = &std::cout;
121 }
118122 } else {
119 Out = &std::cout;
123 if (InputFilename == "-") {
124 OutputFilename = "-";
125 Out = &std::cout;
126 } else {
127 OutputFilename = GetFileNameRoot(InputFilename);
128
129 if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
130 OutputFilename += ".s";
131 else
132 OutputFilename += ".cbe.c";
133
134 if (!Force && std::ifstream(OutputFilename.c_str())) {
135 // If force is not specified, make sure not to overwrite a file!
136 std::cerr << argv[0] << ": error opening '" << OutputFilename
137 << "': file exists!\n"
138 << "Use -f command line argument to force output\n";
139 return 1;
140 }
141
142 Out = new std::ofstream(OutputFilename.c_str());
143 if (!Out->good()) {
144 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
145 delete Out;
146 return 1;
147 }
148
149 // Make sure that the Out file gets unlinked from the disk if we get a
150 // SIGINT
151 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
152 }
120153 }
121 } else {
122 if (InputFilename == "-") {
123 OutputFilename = "-";
124 Out = &std::cout;
154
155 // Ask the target to add backend passes as necessary
156 if (Target.addPassesToEmitAssembly(Passes, *Out)) {
157 std::cerr << argv[0] << ": target '" << Target.getName()
158 << "' does not support static compilation!\n";
159 if (Out != &std::cout) delete Out;
160 // And the Out file is empty and useless, so remove it now.
161 std::remove(OutputFilename.c_str());
162 return 1;
125163 } else {
126 OutputFilename = GetFileNameRoot(InputFilename);
164 // Run our queue of passes all at once now, efficiently.
165 Passes.run(*M.get());
166 }
127167
128 if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE
129 OutputFilename += ".s";
130 else
131 OutputFilename += ".cbe.c";
132
133 if (!Force && std::ifstream(OutputFilename.c_str())) {
134 // If force is not specified, make sure not to overwrite a file!
135 std::cerr << argv[0] << ": error opening '" << OutputFilename
136 << "': file exists!\n"
137 << "Use -f command line argument to force output\n";
138 return 1;
139 }
140
141 Out = new std::ofstream(OutputFilename.c_str());
142 if (!Out->good()) {
143 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
144 delete Out;
145 return 1;
146 }
147
148 // Make sure that the Out file gets unlinked from the disk if we get a
149 // SIGINT
150 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
151 }
168 // Delete the ostream if it's not a stdout stream
169 if (Out != &std::cout) delete Out;
170
171 return 0;
172 } catch (const std::string& msg) {
173 std::cerr << argv[0] << ": " << msg << "\n";
174 } catch (...) {
175 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
152176 }
153
154 // Ask the target to add backend passes as necessary
155 if (Target.addPassesToEmitAssembly(Passes, *Out)) {
156 std::cerr << argv[0] << ": target '" << Target.getName()
157 << "' does not support static compilation!\n";
158 if (Out != &std::cout) delete Out;
159 // And the Out file is empty and useless, so remove it now.
160 std::remove(OutputFilename.c_str());
161 return 1;
162 } else {
163 // Run our queue of passes all at once now, efficiently.
164 Passes.run(*M.get());
165 }
166
167 // Delete the ostream if it's not a stdout stream
168 if (Out != &std::cout) delete Out;
169
170 return 0;
177 return 1;
171178 }
4646 // main Driver function
4747 //
4848 int main(int argc, char **argv, char * const *envp) {
49 cl::ParseCommandLineOptions(argc, argv,
50 " llvm interpreter & dynamic compiler\n");
51 sys::PrintStackTraceOnErrorSignal();
49 try {
50 cl::ParseCommandLineOptions(argc, argv,
51 " llvm interpreter & dynamic compiler\n");
52 sys::PrintStackTraceOnErrorSignal();
5253
53 // Load the bytecode...
54 std::string ErrorMsg;
55 ModuleProvider *MP = 0;
56 try {
57 MP = getBytecodeModuleProvider(InputFile);
58 } catch (std::string &err) {
59 std::cerr << "Error loading program '" << InputFile << "': " << err << "\n";
60 exit(1);
54 // Load the bytecode...
55 std::string ErrorMsg;
56 ModuleProvider *MP = 0;
57 try {
58 MP = getBytecodeModuleProvider(InputFile);
59 } catch (std::string &err) {
60 std::cerr << "Error loading program '" << InputFile << "': " << err << "\n";
61 exit(1);
62 }
63
64 ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter);
65 assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
66
67 // If the user specifically requested an argv[0] to pass into the program, do
68 // it now.
69 if (!FakeArgv0.empty()) {
70 InputFile = FakeArgv0;
71 } else {
72 // Otherwise, if there is a .bc suffix on the executable strip it off, it
73 // might confuse the program.
74 if (InputFile.rfind(".bc") == InputFile.length() - 3)
75 InputFile.erase(InputFile.length() - 3);
76 }
77
78 // Add the module's name to the start of the vector of arguments to main().
79 InputArgv.insert(InputArgv.begin(), InputFile);
80
81 // Call the main function from M as if its signature were:
82 // int main (int argc, char **argv, const char **envp)
83 // using the contents of Args to determine argc & argv, and the contents of
84 // EnvVars to determine envp.
85 //
86 Function *Fn = MP->getModule()->getMainFunction();
87 if (!Fn) {
88 std::cerr << "'main' function not found in module.\n";
89 return -1;
90 }
91
92 // Run main...
93 int Result = EE->runFunctionAsMain(Fn, InputArgv, envp);
94
95 // If the program didn't explicitly call exit, call exit now, for the program.
96 // This ensures that any atexit handlers get called correctly.
97 Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy,
98 Type::IntTy, 0);
99
100 std::vector Args;
101 GenericValue ResultGV;
102 ResultGV.IntVal = Result;
103 Args.push_back(ResultGV);
104 EE->runFunction(Exit, Args);
105
106 std::cerr << "ERROR: exit(" << Result << ") returned!\n";
107 abort();
108 } catch (const std::string& msg) {
109 std::cerr << argv[0] << ": " << msg << "\n";
110 } catch (...) {
111 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
61112 }
62
63 ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter);
64 assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?");
65
66 // If the user specifically requested an argv[0] to pass into the program, do
67 // it now.
68 if (!FakeArgv0.empty()) {
69 InputFile = FakeArgv0;
70 } else {
71 // Otherwise, if there is a .bc suffix on the executable strip it off, it
72 // might confuse the program.
73 if (InputFile.rfind(".bc") == InputFile.length() - 3)
74 InputFile.erase(InputFile.length() - 3);
75 }
76
77 // Add the module's name to the start of the vector of arguments to main().
78 InputArgv.insert(InputArgv.begin(), InputFile);
79
80 // Call the main function from M as if its signature were:
81 // int main (int argc, char **argv, const char **envp)
82 // using the contents of Args to determine argc & argv, and the contents of
83 // EnvVars to determine envp.
84 //
85 Function *Fn = MP->getModule()->getMainFunction();
86 if (!Fn) {
87 std::cerr << "'main' function not found in module.\n";
88 return -1;
89 }
90
91 // Run main...
92 int Result = EE->runFunctionAsMain(Fn, InputArgv, envp);
93
94 // If the program didn't explicitly call exit, call exit now, for the program.
95 // This ensures that any atexit handlers get called correctly.
96 Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy,
97 Type::IntTy, 0);
98
99 std::vector Args;
100 GenericValue ResultGV;
101 ResultGV.IntVal = Result;
102 Args.push_back(ResultGV);
103 EE->runFunction(Exit, Args);
104
105 std::cerr << "ERROR: exit(" << Result << ") returned!\n";
106113 abort();
107114 }
5151 cl::ParseCommandLineOptions(argc, argv, " llvm .ll -> .bc assembler\n");
5252 sys::PrintStackTraceOnErrorSignal();
5353
54 int exitCode = 0;
5455 std::ostream *Out = 0;
5556 try {
5657 // Parse the file now...
125126 WriteBytecodeToFile(M.get(), *Out, !NoCompress);
126127 } catch (const ParseException &E) {
127128 std::cerr << argv[0] << ": " << E.getMessage() << "\n";
128 return 1;
129 exitCode = 1;
130 } catch (const std::string& msg) {
131 std::cerr << argv[0] << ": " << msg << "\n";
132 exitCode = 1;
133 } catch (...) {
134 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
135 exitCode = 1;
129136 }
130137
131138 if (Out != &std::cout) delete Out;
132 return 0;
139 return exitCode;
133140 }
134141
4848 static cl::opt Verify ("verify", cl::desc("Progressively verify module"));
4949
5050 int
51 main(int argc, char **argv)
52 {
53 cl::ParseCommandLineOptions(argc, argv,
54 " llvm-bcanalyzer Analysis of ByteCode Dumper\n");
51 main(int argc, char **argv) {
52 try {
53 cl::ParseCommandLineOptions(argc, argv,
54 " llvm-bcanalyzer Analysis of ByteCode Dumper\n");
5555
56 sys::PrintStackTraceOnErrorSignal();
56 sys::PrintStackTraceOnErrorSignal();
5757
58 std::ostream* Out = &std::cout; // Default to printing to stdout...
59 std::istream* In = &std::cin; // Default to reading stdin
60 std::string ErrorMessage;
61 BytecodeAnalysis bca;
58 std::ostream* Out = &std::cout; // Default to printing to stdout...
59 std::istream* In = &std::cin; // Default to reading stdin
60 std::string ErrorMessage;
61 BytecodeAnalysis bca;
6262
63 /// Determine what to generate
64 bca.detailedResults = !NoDetails;
65 bca.progressiveVerify = Verify;
63 /// Determine what to generate
64 bca.detailedResults = !NoDetails;
65 bca.progressiveVerify = Verify;
6666
67 /// Analyze the bytecode file
68 Module* M = AnalyzeBytecodeFile(InputFilename, bca, &ErrorMessage, (Dump?Out:0));
67 /// Analyze the bytecode file
68 Module* M = AnalyzeBytecodeFile(InputFilename, bca, &ErrorMessage, (Dump?Out:0));
6969
70 // All that bcanalyzer does is write the gathered statistics to the output
71 PrintBytecodeAnalysis(bca,*Out);
70 // All that bcanalyzer does is write the gathered statistics to the output
71 PrintBytecodeAnalysis(bca,*Out);
7272
73 if ( M && Verify ) {
74 std::string verificationMsg;
75 try {
76 verifyModule( *M, ThrowExceptionAction );
77 } catch (std::string& errmsg ) {
78 verificationMsg = errmsg;
73 if ( M && Verify ) {
74 std::string verificationMsg;
75 try {
76 verifyModule( *M, ThrowExceptionAction );
77 } catch (std::string& errmsg ) {
78 verificationMsg = errmsg;
79 }
80 if ( verificationMsg.length() > 0 )
81 std::cerr << "Final Verification Message: " << verificationMsg << "\n";
7982 }
80 if ( verificationMsg.length() > 0 )
81 std::cerr << "Final Verification Message: " << verificationMsg << "\n";
82 }
8383
8484
85 // If there was an error, print it and stop.
86 if ( ErrorMessage.size() ) {
87 std::cerr << argv[0] << ": " << ErrorMessage << "\n";
88 return 1;
85 // If there was an error, print it and stop.
86 if ( ErrorMessage.size() ) {
87 std::cerr << argv[0] << ": " << ErrorMessage << "\n";
88 return 1;
89 }
90
91
92 if (Out != &std::cout) {
93 ((std::ofstream*)Out)->close();
94 delete Out;
95 }
96 return 0;
97 } catch (const std::string& msg) {
98 std::cerr << argv[0] << ": " << msg << "\n";
99 } catch (...) {
100 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
89101 }
90
91
92 if (Out != &std::cout) {
93 ((std::ofstream*)Out)->close();
94 delete Out;
95 }
96 return 0;
102 return 1;
97103 }
98104
99105 // vim: sw=2
4949 // main Driver function
5050 //
5151 int main(int argc, char **argv, char * const *envp) {
52 cl::ParseCommandLineOptions(argc, argv,
53 " llvm source-level debugger\n");
54 sys::PrintStackTraceOnErrorSignal();
52 try {
53 cl::ParseCommandLineOptions(argc, argv,
54 " llvm source-level debugger\n");
55 sys::PrintStackTraceOnErrorSignal();
5556
56 if (!Quiet)
57 std::cout << "llvm-db: The LLVM source-level debugger\n";
57 if (!Quiet)
58 std::cout << "llvm-db: The LLVM source-level debugger\n";
5859
59 // Merge Inputfile and InputArgs into the InputArgs list...
60 if (!InputFile.empty() && InputArgs.empty())
61 InputArgs.push_back(InputFile);
60 // Merge Inputfile and InputArgs into the InputArgs list...
61 if (!InputFile.empty() && InputArgs.empty())
62 InputArgs.push_back(InputFile);
6263
63 // Create the CLI debugger...
64 CLIDebugger D;
64 // Create the CLI debugger...
65 CLIDebugger D;
6566
66 // Initialize the debugger with the command line options we read...
67 Debugger &Dbg = D.getDebugger();
67 // Initialize the debugger with the command line options we read...
68 Debugger &Dbg = D.getDebugger();
6869
69 // Initialize the debugger environment.
70 Dbg.initializeEnvironment(envp);
71 Dbg.setWorkingDirectory(WorkingDirectory);
72 for (unsigned i = 0, e = SourceDirectories.size(); i != e; ++i)
73 D.addSourceDirectory(SourceDirectories[i]);
74
75 if (!InputArgs.empty()) {
76 try {
77 D.fileCommand(InputArgs[0]);
78 } catch (const std::string &Error) {
79 std::cout << "Error: " << Error << "\n";
70 // Initialize the debugger environment.
71 Dbg.initializeEnvironment(envp);
72 Dbg.setWorkingDirectory(WorkingDirectory);
73 for (unsigned i = 0, e = SourceDirectories.size(); i != e; ++i)
74 D.addSourceDirectory(SourceDirectories[i]);
75
76 if (!InputArgs.empty()) {
77 try {
78 D.fileCommand(InputArgs[0]);
79 } catch (const std::string &Error) {
80 std::cout << "Error: " << Error << "\n";
81 }
82
83 Dbg.setProgramArguments(InputArgs.begin()+1, InputArgs.end());
8084 }
8185
82 Dbg.setProgramArguments(InputArgs.begin()+1, InputArgs.end());
86 // Now that we have initialized the debugger, run it.
87 return D.run();
88 } catch (const std::string& msg) {
89 std::cerr << argv[0] << ": " << msg << "\n";
90 } catch (...) {
91 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
8392 }
84
85 // Now that we have initialized the debugger, run it.
86 return D.run();
93 return 1;
8794 }
4040 CWriteMode("c", cl::desc("Obsolete option, do not use"), cl::ReallyHidden);
4141
4242 int main(int argc, char **argv) {
43 cl::ParseCommandLineOptions(argc, argv, " llvm .bc -> .ll disassembler\n");
44 sys::PrintStackTraceOnErrorSignal();
43 try {
44 cl::ParseCommandLineOptions(argc, argv, " llvm .bc -> .ll disassembler\n");
45 sys::PrintStackTraceOnErrorSignal();
4546
46 std::ostream *Out = &std::cout; // Default to printing to stdout...
47 std::string ErrorMessage;
47 std::ostream *Out = &std::cout; // Default to printing to stdout...
48 std::string ErrorMessage;
4849
49 if (CWriteMode) {
50 std::cerr << "ERROR: llvm-dis no longer contains the C backend. "
51 << "Use 'llc -march=c' instead!\n";
52 exit(1);
53 }
50 if (CWriteMode) {
51 std::cerr << "ERROR: llvm-dis no longer contains the C backend. "
52 << "Use 'llc -march=c' instead!\n";
53 exit(1);
54 }
5455
55 std::auto_ptr M(ParseBytecodeFile(InputFilename, &ErrorMessage));
56 if (M.get() == 0) {
57 std::cerr << argv[0] << ": ";
58 if (ErrorMessage.size())
59 std::cerr << ErrorMessage << "\n";
60 else
61 std::cerr << "bytecode didn't read correctly.\n";
62 return 1;
63 }
64
65 if (OutputFilename != "") { // Specified an output filename?
66 if (OutputFilename != "-") { // Not stdout?
67 if (!Force && std::ifstream(OutputFilename.c_str())) {
68 // If force is not specified, make sure not to overwrite a file!
69 std::cerr << argv[0] << ": error opening '" << OutputFilename
70 << "': file exists! Sending to standard output.\n";
56 std::auto_ptr M(ParseBytecodeFile(InputFilename, &ErrorMessage));
57 if (M.get() == 0) {
58 std::cerr << argv[0] << ": ";
59 if (ErrorMessage.size())
60 std::cerr << ErrorMessage << "\n";
61 else
62 std::cerr << "bytecode didn't read correctly.\n";
63 return 1;
64 }
65
66 if (OutputFilename != "") { // Specified an output filename?
67 if (OutputFilename != "-") { // Not stdout?
68 if (!Force && std::ifstream(OutputFilename.c_str())) {
69 // If force is not specified, make sure not to overwrite a file!
70 std::cerr << argv[0] << ": error opening '" << OutputFilename
71 << "': file exists! Sending to standard output.\n";
72 } else {
73 Out = new std::ofstream(OutputFilename.c_str());
74 }
75 }
76 } else {
77 if (InputFilename == "-") {
78 OutputFilename = "-";
7179 } else {
72 Out = new std::ofstream(OutputFilename.c_str());
80 std::string IFN = InputFilename;
81 int Len = IFN.length();
82 if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
83 // Source ends in .bc
84 OutputFilename = std::string(IFN.begin(), IFN.end()-3)+".ll";
85 } else {
86 OutputFilename = IFN+".ll";
87 }
88
89 if (!Force && std::ifstream(OutputFilename.c_str())) {
90 // If force is not specified, make sure not to overwrite a file!
91 std::cerr << argv[0] << ": error opening '" << OutputFilename
92 << "': file exists! Sending to standard output.\n";
93 } else {
94 Out = new std::ofstream(OutputFilename.c_str());
95
96 // Make sure that the Out file gets unlinked from the disk if we get a
97 // SIGINT
98 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
99 }
73100 }
74101 }
75 } else {
76 if (InputFilename == "-") {
77 OutputFilename = "-";
78 } else {
79 std::string IFN = InputFilename;
80 int Len = IFN.length();
81 if (IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {
82 // Source ends in .bc
83 OutputFilename = std::string(IFN.begin(), IFN.end()-3)+".ll";
84 } else {
85 OutputFilename = IFN+".ll";
86 }
87102
88 if (!Force && std::ifstream(OutputFilename.c_str())) {
89 // If force is not specified, make sure not to overwrite a file!
90 std::cerr << argv[0] << ": error opening '" << OutputFilename
91 << "': file exists! Sending to standard output.\n";
92 } else {
93 Out = new std::ofstream(OutputFilename.c_str());
103 if (!Out->good()) {
104 std::cerr << argv[0] << ": error opening " << OutputFilename
105 << ": sending to stdout instead!\n";
106 Out = &std::cout;
107 }
94108
95 // Make sure that the Out file gets unlinked from the disk if we get a
96 // SIGINT
97 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
98 }
109 // All that dis does is write the assembly or C out to a file...
110 //
111 PassManager Passes;
112 Passes.add(new PrintModulePass(Out));
113 Passes.run(*M.get());
114
115 if (Out != &std::cout) {
116 ((std::ofstream*)Out)->close();
117 delete Out;
99118 }
119 return 0;
120 } catch (const std::string& msg) {
121 std::cerr << argv[0] << ": " << msg << "\n";
122 } catch (...) {
123 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
100124 }
101
102 if (!Out->good()) {
103 std::cerr << argv[0] << ": error opening " << OutputFilename
104 << ": sending to stdout instead!\n";
105 Out = &std::cout;
106 }
107
108 // All that dis does is write the assembly or C out to a file...
109 //
110 PassManager Passes;
111 Passes.add(new PrintModulePass(Out));
112 Passes.run(*M.get());
113
114 if (Out != &std::cout) {
115 ((std::ofstream*)Out)->close();
116 delete Out;
117 }
118 return 0;
125 return 1;
119126 }
120127
4444 cl::value_desc("function"));
4545
4646 int main(int argc, char **argv) {
47 cl::ParseCommandLineOptions(argc, argv, " llvm extractor\n");
48 sys::PrintStackTraceOnErrorSignal();
47 try {
48 cl::ParseCommandLineOptions(argc, argv, " llvm extractor\n");
49 sys::PrintStackTraceOnErrorSignal();
4950
50 std::auto_ptr M(ParseBytecodeFile(InputFilename));
51 if (M.get() == 0) {
52 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
53 return 1;
54 }
55
56 // Figure out which function we should extract
57 Function *F = M.get()->getNamedFunction(ExtractFunc);
58 if (F == 0) {
59 std::cerr << argv[0] << ": program doesn't contain function named '"
60 << ExtractFunc << "'!\n";
61 return 1;
62 }
63
64 // In addition to deleting all other functions, we also want to spiff it up a
65 // little bit. Do this now.
66 //
67 PassManager Passes;
68 Passes.add(new TargetData("extract", M.get())); // Use correct TargetData
69 // Either isolate the function or delete it from the Module
70 Passes.add(createFunctionExtractionPass(F, DeleteFn));
71 Passes.add(createGlobalDCEPass()); // Delete unreachable globals
72 Passes.add(createFunctionResolvingPass()); // Delete prototypes
73 Passes.add(createDeadTypeEliminationPass()); // Remove dead types...
74
75 std::ostream *Out = 0;
76
77 if (OutputFilename != "-") { // Not stdout?
78 if (!Force && std::ifstream(OutputFilename.c_str())) {
79 // If force is not specified, make sure not to overwrite a file!
80 std::cerr << argv[0] << ": error opening '" << OutputFilename
81 << "': file exists!\n"
82 << "Use -f command line argument to force output\n";
51 std::auto_ptr M(ParseBytecodeFile(InputFilename));
52 if (M.get() == 0) {
53 std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
8354 return 1;
8455 }
85 Out = new std::ofstream(OutputFilename.c_str());
86 } else { // Specified stdout
87 Out = &std::cout;
56
57 // Figure out which function we should extract
58 Function *F = M.get()->getNamedFunction(ExtractFunc);
59 if (F == 0) {
60 std::cerr << argv[0] << ": program doesn't contain function named '"
61 << ExtractFunc << "'!\n";
62 return 1;
63 }
64
65 // In addition to deleting all other functions, we also want to spiff it up a
66 // little bit. Do this now.
67 //
68 PassManager Passes;
69 Passes.add(new TargetData("extract", M.get())); // Use correct TargetData
70 // Either isolate the function or delete it from the Module
71 Passes.add(createFunctionExtractionPass(F, DeleteFn));
72 Passes.add(createGlobalDCEPass()); // Delete unreachable globals
73 Passes.add(createFunctionResolvingPass()); // Delete prototypes
74 Passes.add(createDeadTypeEliminationPass()); // Remove dead types...
75
76 std::ostream *Out = 0;
77
78 if (OutputFilename != "-") { // Not stdout?
79 if (!Force && std::ifstream(OutputFilename.c_str())) {
80 // If force is not specified, make sure not to overwrite a file!
81 std::cerr << argv[0] << ": error opening '" << OutputFilename
82 << "': file exists!\n"
83 << "Use -f command line argument to force output\n";
84 return 1;
85 }
86 Out = new std::ofstream(OutputFilename.c_str());
87 } else { // Specified stdout
88 Out = &std::cout;
89 }
90
91 Passes.add(new WriteBytecodePass(Out)); // Write bytecode to file...
92 Passes.run(*M.get());
93
94 if (Out != &std::cout)
95 delete Out;
96 return 0;
97 } catch (const std::string& msg) {
98 std::cerr << argv[0] << ": " << msg << "\n";
99 } catch (...) {
100 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
88101 }
89
90 Passes.add(new WriteBytecodePass(Out)); // Write bytecode to file...
91 Passes.run(*M.get());
92
93 if (Out != &std::cout)
94 delete Out;
95 return 0;
102 return 1;
96103 }
388388 }
389389
390390 int main(int argc, char **argv, char **envp) {
391 // Initial global variable above for convenience printing of program name.
392 progname = sys::Path(argv[0]).getBasename();
393 Linker TheLinker(progname, Verbose);
394
395 // Set up the library paths for the Linker
396 TheLinker.addPaths(LibPaths);
397 TheLinker.addSystemPaths();
398
399 // Parse the command line options
400 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
401 sys::PrintStackTraceOnErrorSignal();
402
403 // Remove any consecutive duplicates of the same library...
404 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
405 Libraries.end());
406
407 if (LinkAsLibrary) {
408 std::vector Files;
409 for (unsigned i = 0; i < InputFilenames.size(); ++i )
410 Files.push_back(sys::Path(InputFilenames[i]));
411 if (TheLinker.LinkInFiles(Files))
412 return 1; // Error already printed
413
414 // The libraries aren't linked in but are noted as "dependent" in the
415 // module.
416 for (cl::list::const_iterator I = Libraries.begin(),
417 E = Libraries.end(); I != E ; ++I) {
418 TheLinker.getModule()->addLibrary(*I);
391 try {
392 // Initial global variable above for convenience printing of program name.
393 progname = sys::Path(argv[0]).getBasename();
394 Linker TheLinker(progname, Verbose);
395
396 // Set up the library paths for the Linker
397 TheLinker.addPaths(LibPaths);
398 TheLinker.addSystemPaths();
399
400 // Parse the command line options
401 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
402 sys::PrintStackTraceOnErrorSignal();
403
404 // Remove any consecutive duplicates of the same library...
405 Libraries.erase(std::unique(Libraries.begin(), Libraries.end()),
406 Libraries.end());
407
408 if (LinkAsLibrary) {
409 std::vector Files;
410 for (unsigned i = 0; i < InputFilenames.size(); ++i )
411 Files.push_back(sys::Path(InputFilenames[i]));
412 if (TheLinker.LinkInFiles(Files))
413 return 1; // Error already printed
414
415 // The libraries aren't linked in but are noted as "dependent" in the
416 // module.
417 for (cl::list::const_iterator I = Libraries.begin(),
418 E = Libraries.end(); I != E ; ++I) {
419 TheLinker.getModule()->addLibrary(*I);
420 }
421 } else {
422 // Build a list of the items from our command line
423 Linker::ItemList Items;
424 BuildLinkItems(Items, InputFilenames, Libraries);
425
426 // Link all the items together
427 if (TheLinker.LinkInItems(Items) )
428 return 1;
419429 }
420 } else {
421 // Build a list of the items from our command line
422 Linker::ItemList Items;
423 BuildLinkItems(Items, InputFilenames, Libraries);
424
425 // Link all the items together
426 if (TheLinker.LinkInItems(Items) )
427 return 1;
428 }
429
430 std::auto_ptr Composite(TheLinker.releaseModule());
431
432 // Optimize the module
433 Optimize(Composite.get());
434
435 // Generate the bytecode for the optimized module.
436 std::string RealBytecodeOutput = OutputFilename;
437 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
438 GenerateBytecode(Composite.get(), RealBytecodeOutput);
439
440 // If we are not linking a library, generate either a native executable
441 // or a JIT shell script, depending upon what the user wants.
442 if (!LinkAsLibrary) {
443 // If the user wants to generate a native executable, compile it from the
444 // bytecode file.
445 //
446 // Otherwise, create a script that will run the bytecode through the JIT.
447 if (Native) {
448 // Name of the Assembly Language output file
449 sys::Path AssemblyFile ( OutputFilename);
450 AssemblyFile.appendSuffix("s");
451
452 // Mark the output files for removal if we get an interrupt.
453 sys::RemoveFileOnSignal(AssemblyFile);
454 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
455
456 // Determine the locations of the llc and gcc programs.
457 sys::Path llc = FindExecutable("llc", argv[0]);
458 if (llc.isEmpty())
459 return PrintAndReturn("Failed to find llc");
460
461 sys::Path gcc = FindExecutable("gcc", argv[0]);
462 if (gcc.isEmpty())
463 return PrintAndReturn("Failed to find gcc");
464
465 // Generate an assembly language file for the bytecode.
466 if (Verbose) std::cout << "Generating Assembly Code\n";
467 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
468 if (Verbose) std::cout << "Generating Native Code\n";
469 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
470 gcc, envp);
471
472 // Remove the assembly language file.
473 AssemblyFile.destroyFile();
474 } else if (NativeCBE) {
475 sys::Path CFile (OutputFilename);
476 CFile.appendSuffix("cbe.c");
477
478 // Mark the output files for removal if we get an interrupt.
479 sys::RemoveFileOnSignal(CFile);
480 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
481
482 // Determine the locations of the llc and gcc programs.
483 sys::Path llc = FindExecutable("llc", argv[0]);
484 if (llc.isEmpty())
485 return PrintAndReturn("Failed to find llc");
486
487 sys::Path gcc = FindExecutable("gcc", argv[0]);
488 if (gcc.isEmpty())
489 return PrintAndReturn("Failed to find gcc");
490
491 // Generate an assembly language file for the bytecode.
492 if (Verbose) std::cout << "Generating Assembly Code\n";
493 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
494 if (Verbose) std::cout << "Generating Native Code\n";
495 GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
496
497 // Remove the assembly language file.
498 CFile.destroyFile();
499
500 } else {
501 EmitShellScript(argv);
430
431 std::auto_ptr Composite(TheLinker.releaseModule());
432
433 // Optimize the module
434 Optimize(Composite.get());
435
436 // Generate the bytecode for the optimized module.
437 std::string RealBytecodeOutput = OutputFilename;
438 if (!LinkAsLibrary) RealBytecodeOutput += ".bc";
439 GenerateBytecode(Composite.get(), RealBytecodeOutput);
440
441 // If we are not linking a library, generate either a native executable
442 // or a JIT shell script, depending upon what the user wants.
443 if (!LinkAsLibrary) {
444 // If the user wants to generate a native executable, compile it from the
445 // bytecode file.
446 //
447 // Otherwise, create a script that will run the bytecode through the JIT.
448 if (Native) {
449 // Name of the Assembly Language output file
450 sys::Path AssemblyFile ( OutputFilename);
451 AssemblyFile.appendSuffix("s");
452
453 // Mark the output files for removal if we get an interrupt.
454 sys::RemoveFileOnSignal(AssemblyFile);
455 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
456
457 // Determine the locations of the llc and gcc programs.
458 sys::Path llc = FindExecutable("llc", argv[0]);
459 if (llc.isEmpty())
460 return PrintAndReturn("Failed to find llc");
461
462 sys::Path gcc = FindExecutable("gcc", argv[0]);
463 if (gcc.isEmpty())
464 return PrintAndReturn("Failed to find gcc");
465
466 // Generate an assembly language file for the bytecode.
467 if (Verbose) std::cout << "Generating Assembly Code\n";
468 GenerateAssembly(AssemblyFile.toString(), RealBytecodeOutput, llc);
469 if (Verbose) std::cout << "Generating Native Code\n";
470 GenerateNative(OutputFilename, AssemblyFile.toString(), Libraries,
471 gcc, envp);
472
473 // Remove the assembly language file.
474 AssemblyFile.destroyFile();
475 } else if (NativeCBE) {
476 sys::Path CFile (OutputFilename);
477 CFile.appendSuffix("cbe.c");
478
479 // Mark the output files for removal if we get an interrupt.
480 sys::RemoveFileOnSignal(CFile);
481 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
482
483 // Determine the locations of the llc and gcc programs.
484 sys::Path llc = FindExecutable("llc", argv[0]);
485 if (llc.isEmpty())
486 return PrintAndReturn("Failed to find llc");
487
488 sys::Path gcc = FindExecutable("gcc", argv[0]);
489 if (gcc.isEmpty())
490 return PrintAndReturn("Failed to find gcc");
491
492 // Generate an assembly language file for the bytecode.
493 if (Verbose) std::cout << "Generating Assembly Code\n";
494 GenerateCFile(CFile.toString(), RealBytecodeOutput, llc);
495 if (Verbose) std::cout << "Generating Native Code\n";
496 GenerateNative(OutputFilename, CFile.toString(), Libraries, gcc, envp);
497
498 // Remove the assembly language file.
499 CFile.destroyFile();
500
501 } else {
502 EmitShellScript(argv);
503 }
504
505 // Make the script executable...
506 sys::Path(OutputFilename).makeExecutable();
507
508 // Make the bytecode file readable and directly executable in LLEE as well
509 sys::Path(RealBytecodeOutput).makeExecutable();
510 sys::Path(RealBytecodeOutput).makeReadable();
502511 }
503
504 // Make the script executable...
505 sys::Path(OutputFilename).makeExecutable();
506
507 // Make the bytecode file readable and directly executable in LLEE as well
508 sys::Path(RealBytecodeOutput).makeExecutable();
509 sys::Path(RealBytecodeOutput).makeReadable();
510 }
511
512 return 0;
513 }
512
513 return 0;
514 } catch (const std::string& msg) {
515 std::cerr << argv[0] << ": " << msg << "\n";
516 } catch (...) {
517 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
518 }
519 return 1;
520 }
7474 }
7575
7676 int main(int argc, char **argv) {
77 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
78 sys::PrintStackTraceOnErrorSignal();
79 assert(InputFilenames.size() > 0 && "OneOrMore is not working");
77 try {
78 cl::ParseCommandLineOptions(argc, argv, " llvm linker\n");
79 sys::PrintStackTraceOnErrorSignal();
80 assert(InputFilenames.size() > 0 && "OneOrMore is not working");
8081
81 unsigned BaseArg = 0;
82 std::string ErrorMessage;
82 unsigned BaseArg = 0;
83 std::string ErrorMessage;
8384
84 std::auto_ptr Composite(LoadFile(InputFilenames[BaseArg]));
85 if (Composite.get() == 0) {
86 std::cerr << argv[0] << ": error loading file '"
87 << InputFilenames[BaseArg] << "'\n";
88 return 1;
89 }
90
91 for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
92 std::auto_ptr M(LoadFile(InputFilenames[i]));
93 if (M.get() == 0) {
85 std::auto_ptr Composite(LoadFile(InputFilenames[BaseArg]));
86 if (Composite.get() == 0) {
9487 std::cerr << argv[0] << ": error loading file '"
95 << InputFilenames[i] << "'\n";
88 << InputFilenames[BaseArg] << "'\n";
9689 return 1;
9790 }
9891
99 if (Verbose) std::cerr << "Linking in '" << InputFilenames[i] << "'\n";
92 for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
93 std::auto_ptr M(LoadFile(InputFilenames[i]));
94 if (M.get() == 0) {
95 std::cerr << argv[0] << ": error loading file '"
96 << InputFilenames[i] << "'\n";
97 return 1;
98 }
10099
101 if (Linker::LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
102 std::cerr << argv[0] << ": link error in '" << InputFilenames[i]
103 << "': " << ErrorMessage << "\n";
104 return 1;
100 if (Verbose) std::cerr << "Linking in '" << InputFilenames[i] << "'\n";
101
102 if (Linker::LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
103 std::cerr << argv[0] << ": link error in '" << InputFilenames[i]
104 << "': " << ErrorMessage << "\n";
105 return 1;
106 }
105107 }
106 }
107108
108 // TODO: Iterate over the -l list and link in any modules containing
109 // global symbols that have not been resolved so far.
109 // TODO: Iterate over the -l list and link in any modules containing
110 // global symbols that have not been resolved so far.
110111
111 if (DumpAsm) std::cerr << "Here's the assembly:\n" << Composite.get();
112 if (DumpAsm) std::cerr << "Here's the assembly:\n" << Composite.get();
112113
113 std::ostream *Out = &std::cout; // Default to printing to stdout...
114 if (OutputFilename != "-") {
115 if (!Force && std::ifstream(OutputFilename.c_str())) {
116 // If force is not specified, make sure not to overwrite a file!
117 std::cerr << argv[0] << ": error opening '" << OutputFilename
118 << "': file exists!\n"
119 << "Use -f command line argument to force output\n";
120 return 1;
114 std::ostream *Out = &std::cout; // Default to printing to stdout...
115 if (OutputFilename != "-") {
116 if (!Force && std::ifstream(OutputFilename.c_str())) {
117 // If force is not specified, make sure not to overwrite a file!
118 std::cerr << argv[0] << ": error opening '" << OutputFilename
119 << "': file exists!\n"
120 << "Use -f command line argument to force output\n";
121 return 1;
122 }
123 Out = new std::ofstream(OutputFilename.c_str());
124 if (!Out->good()) {
125 std::cerr << argv[0] << ": error opening '" << OutputFilename << "'!\n";
126 return 1;
127 }
128
129 // Make sure that the Out file gets unlinked from the disk if we get a
130 // SIGINT
131 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
121132 }
122 Out = new std::ofstream(OutputFilename.c_str());
123 if (!Out->good()) {
124 std::cerr << argv[0] << ": error opening '" << OutputFilename << "'!\n";
133
134 if (verifyModule(*Composite.get())) {
135 std::cerr << argv[0] << ": linked module is broken!\n";
125136 return 1;
126137 }
127138
128 // Make sure that the Out file gets unlinked from the disk if we get a
129 // SIGINT
130 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
139 if (Verbose) std::cerr << "Writing bytecode...\n";
140 WriteBytecodeToFile(Composite.get(), *Out, !NoCompress);
141
142 if (Out != &std::cout) delete Out;
143 return 0;
144 } catch (const std::string& msg) {
145 std::cerr << argv[0] << ": " << msg << "\n";
146 } catch (...) {
147 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
131148 }
132
133 if (verifyModule(*Composite.get())) {
134 std::cerr << argv[0] << ": linked module is broken!\n";
135 return 1;
136 }
137
138 if (Verbose) std::cerr << "Writing bytecode...\n";
139 WriteBytecodeToFile(Composite.get(), *Out, !NoCompress);
140
141 if (Out != &std::cout) delete Out;
142 return 0;
149 return 1;
143150 }
151151 }
152152
153153 int main(int argc, char **argv) {
154 cl::ParseCommandLineOptions(argc, argv, " llvm symbol table dumper\n");
155 sys::PrintStackTraceOnErrorSignal();
154 try {
155 cl::ParseCommandLineOptions(argc, argv, " llvm symbol table dumper\n");
156 sys::PrintStackTraceOnErrorSignal();
156157
157 ToolName = argv[0];
158 if (BSDFormat) OutputFormat = bsd;
159 if (POSIXFormat) OutputFormat = posix;
158 ToolName = argv[0];
159 if (BSDFormat) OutputFormat = bsd;
160 if (POSIXFormat) OutputFormat = posix;
160161
161 switch (InputFilenames.size()) {
162 case 0: InputFilenames.push_back("-");
163 case 1: break;
164 default: MultipleFiles = true;
162 switch (InputFilenames.size()) {
163 case 0: InputFilenames.push_back("-");
164 case 1: break;
165 default: MultipleFiles = true;
166 }
167
168 std::for_each (InputFilenames.begin (), InputFilenames.end (),
169 DumpSymbolNamesFromFile);
170 return 0;
171 } catch (const std::string& msg) {
172 std::cerr << argv[0] << ": " << msg << "\n";
173 } catch (...) {
174 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
165175 }
166
167 std::for_each (InputFilenames.begin (), InputFilenames.end (),
168 DumpSymbolNamesFromFile);
169 return 0;
176 return 1;
170177 }
106106
107107
108108 int main(int argc, char **argv) {
109 cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n");
110 sys::PrintStackTraceOnErrorSignal();
111
112 // Read in the bytecode file...
113 std::string ErrorMessage;
114 Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage);
115 if (M == 0) {
116 std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage
117 << "\n";
118 return 1;
109 try {
110 cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n");
111 sys::PrintStackTraceOnErrorSignal();
112
113 // Read in the bytecode file...
114 std::string ErrorMessage;
115 Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage);
116 if (M == 0) {
117 std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage
118 << "\n";
119 return 1;
120 }
121
122 // Read the profiling information
123 ProfileInfoLoader PI(argv[0], ProfileDataFile, *M);
124
125 std::map FuncFreqs;
126 std::map BlockFreqs;
127 std::map EdgeFreqs;
128
129 // Output a report. Eventually, there will be multiple reports selectable on
130 // the command line, for now, just keep things simple.
131
132 // Emit the most frequent function table...
133 std::vector > FunctionCounts;
134 PI.getFunctionCounts(FunctionCounts);
135 FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end());
136
137 // Sort by the frequency, backwards.
138 std::sort(FunctionCounts.begin(), FunctionCounts.end(),
139 PairSecondSortReverse());
140
141 unsigned long long TotalExecutions = 0;
142 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
143 TotalExecutions += FunctionCounts[i].second;
144
145 std::cout << "===" << std::string(73, '-') << "===\n"
146 << "LLVM profiling output for execution";
147 if (PI.getNumExecutions() != 1) std::cout << "s";
148 std::cout << ":\n";
149
150 for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
151 std::cout << " ";
152 if (e != 1) std::cout << i+1 << ". ";
153 std::cout << PI.getExecution(i) << "\n";
154 }
155
156 std::cout << "\n===" << std::string(73, '-') << "===\n";
157 std::cout << "Function execution frequencies:\n\n";
158
159 // Print out the function frequencies...
160 printf(" ## Frequency\n");
161 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
162 if (FunctionCounts[i].second == 0) {
163 printf("\n NOTE: %d function%s never executed!\n",
164 e-i, e-i-1 ? "s were" : " was");
165 break;
166 }
167
168 printf("%3d. %5u/%llu %s\n", i+1, FunctionCounts[i].second, TotalExecutions,
169 FunctionCounts[i].first->getName().c_str());
170 }
171
172 std::set FunctionsToPrint;
173
174 // If we have block count information, print out the LLVM module with
175 // frequency annotations.
176 if (PI.hasAccurateBlockCounts()) {
177 std::vector > Counts;
178 PI.getBlockCounts(Counts);
179
180 TotalExecutions = 0;
181 for (unsigned i = 0, e = Counts.size(); i != e; ++i)
182 TotalExecutions += Counts[i].second;
183
184 // Sort by the frequency, backwards.
185 std::sort(Counts.begin(), Counts.end(),
186 PairSecondSortReverse());
187
188 std::cout << "\n===" << std::string(73, '-') << "===\n";
189 std::cout << "Top 20 most frequently executed basic blocks:\n\n";
190
191 // Print out the function frequencies...
192 printf(" ## %%%% \tFrequency\n");
193 unsigned BlocksToPrint = Counts.size();
194 if (BlocksToPrint > 20) BlocksToPrint = 20;
195 for (unsigned i = 0; i != BlocksToPrint; ++i) {
196 if (Counts[i].second == 0) break;
197 Function *F = Counts[i].first->getParent();
198 printf("%3d. %5.2f%% %5u/%llu\t%s() - %s\n", i+1,
199 Counts[i].second/(double)TotalExecutions*100,
200 Counts[i].second, TotalExecutions,
201 F->getName().c_str(), Counts[i].first->getName().c_str());
202 FunctionsToPrint.insert(F);
203 }
204
205 BlockFreqs.insert(Counts.begin(), Counts.end());
206 }
207
208 if (PI.hasAccurateEdgeCounts()) {
209 std::vector > Counts;
210 PI.getEdgeCounts(Counts);
211 EdgeFreqs.insert(Counts.begin(), Counts.end());
212 }
213
214 if (PrintAnnotatedLLVM || PrintAllCode) {
215 std::cout << "\n===" << std::string(73, '-') << "===\n";
216 std::cout << "Annotated LLVM code for the module:\n\n";
217
218 ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs);
219
220 if (FunctionsToPrint.empty() || PrintAllCode)
221 M->print(std::cout, &PA);
222 else
223 // Print just a subset of the functions...
224 for (std::set::iterator I = FunctionsToPrint.begin(),
225 E = FunctionsToPrint.end(); I != E; ++I)
226 (*I)->print(std::cout, &PA);
227 }
228
229 return 0;
230 } catch (const std::string& msg) {
231 std::cerr << argv[0] << ": " << msg << "\n";
232 } catch (...) {
233 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
119234 }
120
121 // Read the profiling information
122 ProfileInfoLoader PI(argv[0], ProfileDataFile, *M);
123
124 std::map FuncFreqs;
125 std::map BlockFreqs;
126 std::map EdgeFreqs;
127
128 // Output a report. Eventually, there will be multiple reports selectable on
129 // the command line, for now, just keep things simple.
130
131 // Emit the most frequent function table...
132 std::vector > FunctionCounts;
133 PI.getFunctionCounts(FunctionCounts);
134 FuncFreqs.insert(FunctionCounts.begin(), FunctionCounts.end());
135
136 // Sort by the frequency, backwards.
137 std::sort(FunctionCounts.begin(), FunctionCounts.end(),
138 PairSecondSortReverse());
139
140 unsigned long long TotalExecutions = 0;
141 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
142 TotalExecutions += FunctionCounts[i].second;
143
144 std::cout << "===" << std::string(73, '-') << "===\n"
145 << "LLVM profiling output for execution";
146 if (PI.getNumExecutions() != 1) std::cout << "s";
147 std::cout << ":\n";
148
149 for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
150 std::cout << " ";
151 if (e != 1) std::cout << i+1 << ". ";
152 std::cout << PI.getExecution(i) << "\n";
153 }
154
155 std::cout << "\n===" << std::string(73, '-') << "===\n";
156 std::cout << "Function execution frequencies:\n\n";
157
158 // Print out the function frequencies...
159 printf(" ## Frequency\n");
160 for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
161 if (FunctionCounts[i].second == 0) {
162 printf("\n NOTE: %d function%s never executed!\n",
163 e-i, e-i-1 ? "s were" : " was");
164 break;
165 }
166
167 printf("%3d. %5u/%llu %s\n", i+1, FunctionCounts[i].second, TotalExecutions,
168 FunctionCounts[i].first->getName().c_str());
169 }
170
171 std::set FunctionsToPrint;
172
173 // If we have block count information, print out the LLVM module with
174 // frequency annotations.
175 if (PI.hasAccurateBlockCounts()) {
176 std::vector > Counts;
177 PI.getBlockCounts(Counts);
178
179 TotalExecutions = 0;
180 for (unsigned i = 0, e = Counts.size(); i != e; ++i)
181 TotalExecutions += Counts[i].second;
182
183 // Sort by the frequency, backwards.
184 std::sort(Counts.begin(), Counts.end(),
185 PairSecondSortReverse());
186
187 std::cout << "\n===" << std::string(73, '-') << "===\n";
188 std::cout << "Top 20 most frequently executed basic blocks:\n\n";
189
190 // Print out the function frequencies...
191 printf(" ## %%%% \tFrequency\n");
192 unsigned BlocksToPrint = Counts.size();
193 if (BlocksToPrint > 20) BlocksToPrint = 20;
194 for (unsigned i = 0; i != BlocksToPrint; ++i) {
195 if (Counts[i].second == 0) break;
196 Function *F = Counts[i].first->getParent();
197 printf("%3d. %5.2f%% %5u/%llu\t%s() - %s\n", i+1,
198 Counts[i].second/(double)TotalExecutions*100,
199 Counts[i].second, TotalExecutions,
200 F->getName().c_str(), Counts[i].first->getName().c_str());
201 FunctionsToPrint.insert(F);
202 }
203
204 BlockFreqs.insert(Counts.begin(), Counts.end());
205 }
206
207 if (PI.hasAccurateEdgeCounts()) {
208 std::vector > Counts;
209 PI.getEdgeCounts(Counts);
210 EdgeFreqs.insert(Counts.begin(), Counts.end());
211 }
212
213 if (PrintAnnotatedLLVM || PrintAllCode) {
214 std::cout << "\n===" << std::string(73, '-') << "===\n";
215 std::cout << "Annotated LLVM code for the module:\n\n";
216
217 ProfileAnnotator PA(FuncFreqs, BlockFreqs, EdgeFreqs);
218
219 if (FunctionsToPrint.empty() || PrintAllCode)
220 M->print(std::cout, &PA);
221 else
222 // Print just a subset of the functions...
223 for (std::set::iterator I = FunctionsToPrint.begin(),
224 E = FunctionsToPrint.end(); I != E; ++I)
225 (*I)->print(std::cout, &PA);
226 }
227
228 return 0;
235 return 1;
229236 }
367367 } catch (...) {
368368 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
369369 }
370 return 1;
370371 }
6969 // main for opt
7070 //
7171 int main(int argc, char **argv) {
72 cl::ParseCommandLineOptions(argc, argv,
73 " llvm .bc -> .bc modular optimizer\n");
74 sys::PrintStackTraceOnErrorSignal();
72 try {
73 cl::ParseCommandLineOptions(argc, argv,
74 " llvm .bc -> .bc modular optimizer\n");
75 sys::PrintStackTraceOnErrorSignal();
7576
76 // Allocate a full target machine description only if necessary...
77 // FIXME: The choice of target should be controllable on the command line.
78 std::auto_ptr target;
77 // Allocate a full target machine description only if necessary...
78 // FIXME: The choice of target should be controllable on the command line.
79 std::auto_ptr target;
7980
80 TargetMachine* TM = NULL;
81 std::string ErrorMessage;
81 TargetMachine* TM = NULL;
82 std::string ErrorMessage;
8283
83 // Load the input module...
84 std::auto_ptr M(ParseBytecodeFile(InputFilename, &ErrorMessage));
85 if (M.get() == 0) {
86 std::cerr << argv[0] << ": ";
87 if (ErrorMessage.size())
88 std::cerr << ErrorMessage << "\n";
89 else
90 std::cerr << "bytecode didn't read correctly.\n";
91 return 1;
92 }
93
94 // Figure out what stream we are supposed to write to...
95 std::ostream *Out = &std::cout; // Default to printing to stdout...
96 if (OutputFilename != "-") {
97 if (!Force && std::ifstream(OutputFilename.c_str())) {
98 // If force is not specified, make sure not to overwrite a file!
99 std::cerr << argv[0] << ": error opening '" << OutputFilename
100 << "': file exists!\n"
101 << "Use -f command line argument to force output\n";
102 return 1;
103 }
104 Out = new std::ofstream(OutputFilename.c_str());
105
106 if (!Out->good()) {
107 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
84 // Load the input module...
85 std::auto_ptr M(ParseBytecodeFile(InputFilename, &ErrorMessage));
86 if (M.get() == 0) {
87 std::cerr << argv[0] << ": ";
88 if (ErrorMessage.size())
89 std::cerr << ErrorMessage << "\n";
90 else
91 std::cerr << "bytecode didn't read correctly.\n";
10892 return 1;
10993 }
11094
111 // Make sure that the Output file gets unlinked from the disk if we get a
112 // SIGINT
113 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
95 // Figure out what stream we are supposed to write to...
96 std::ostream *Out = &std::cout; // Default to printing to stdout...
97 if (OutputFilename != "-") {
98 if (!Force && std::ifstream(OutputFilename.c_str())) {
99 // If force is not specified, make sure not to overwrite a file!
100 std::cerr << argv[0] << ": error opening '" << OutputFilename
101 << "': file exists!\n"
102 << "Use -f command line argument to force output\n";
103 return 1;
104 }
105 Out = new std::ofstream(OutputFilename.c_str());
106
107 if (!Out->good()) {
108 std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
109 return 1;
110 }
111
112 // Make sure that the Output file gets unlinked from the disk if we get a
113 // SIGINT
114 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
115 }
116
117 // If the output is set to be emitted to standard out, and standard out is a
118 // console, print out a warning message and refuse to do it. We don't impress
119 // anyone by spewing tons of binary goo to a terminal.
120 if (Out == &std::cout && isStandardOutAConsole() && !Force && !NoOutput
121 && !Quiet) {
122 std::cerr << "WARNING: It looks like you're attempting to print out a "
123 << "bytecode file. I'm\ngoing to pretend you didn't ask me to do"
124 << " this (for your own good). If you\nREALLY want to taste LLVM"
125 << " bytecode first-hand, you can force output with the\n`-f'"
126 << " option.\n\n";
127 NoOutput = true;
128 }
129
130 // Create a PassManager to hold and optimize the collection of passes we are
131 // about to build...
132 //
133 PassManager Passes;
134
135 // Add an appropriate TargetData instance for this module...
136 Passes.add(new TargetData("opt", M.get()));
137
138 // Create a new optimization pass for each one specified on the command line
139 for (unsigned i = 0; i < OptimizationList.size(); ++i) {
140 const PassInfo *Opt = OptimizationList[i];
141
142 if (Opt->getNormalCtor())
143 Passes.add(Opt->getNormalCtor()());
144 else if (Opt->getTargetCtor()) {
145 #if 0
146 if (target.get() == NULL)
147 target.reset(allocateSparcTargetMachine()); // FIXME: target option
148 #endif
149 assert(target.get() && "Could not allocate target machine!");
150 Passes.add(Opt->getTargetCtor()(*target.get()));
151 } else
152 std::cerr << argv[0] << ": cannot create pass: " << Opt->getPassName()
153 << "\n";
154
155 if (PrintEachXForm)
156 Passes.add(new PrintModulePass(&std::cerr));
157 }
158
159 // Check that the module is well formed on completion of optimization
160 if (!NoVerify)
161 Passes.add(createVerifierPass());
162
163 // Write bytecode out to disk or cout as the last step...
164 if (!NoOutput)
165 Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
166
167 // Now that we have all of the passes ready, run them.
168 Passes.run(*M.get());
169
170 return 0;
171 } catch (const std::string& msg) {
172 std::cerr << argv[0] << ": " << msg << "\n";
173 } catch (...) {
174 std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
114175 }
115
116 // If the output is set to be emitted to standard out, and standard out is a
117 // console, print out a warning message and refuse to do it. We don't impress
118 // anyone by spewing tons of binary goo to a terminal.
119 if (Out == &std::cout && isStandardOutAConsole() && !Force && !NoOutput
120 && !Quiet) {
121 std::cerr << "WARNING: It looks like you're attempting to print out a "
122 << "bytecode file. I'm\ngoing to pretend you didn't ask me to do"
123 << " this (for your own good). If you\nREALLY want to taste LLVM"
124 << " bytecode first-hand, you can force output with the\n`-f'"
125 << " option.\n\n";
126 NoOutput = true;
127 }
128
129 // Create a PassManager to hold and optimize the collection of passes we are
130 // about to build...
131 //
132 PassManager Passes;
133
134 // Add an appropriate TargetData instance for this module...
135 Passes.add(new TargetData("opt", M.get()));
136
137 // Create a new optimization pass for each one specified on the command line
138 for (unsigned i = 0; i < OptimizationList.size(); ++i) {
139 const PassInfo *Opt = OptimizationList[i];
140
141 if (Opt->getNormalCtor())
142 Passes.add(Opt->getNormalCtor()());
143 else if (Opt->getTargetCtor()) {
144 #if 0
145 if (target.get() == NULL)
146 target.reset(allocateSparcTargetMachine()); // FIXME: target option
147 #endif
148 assert(target.get() && "Could not allocate target machine!");
149 Passes.add(Opt->getTargetCtor()(*target.get()));
150 } else
151 std::cerr << argv[0] << ": cannot create pass: " << Opt->getPassName()
152 << "\n";
153
154 if (PrintEachXForm)
155 Passes.add(new PrintModulePass(&std::cerr));
156 }
157
158 // Check that the module is well formed on completion of optimization
159 if (!NoVerify)
160 Passes.add(createVerifierPass());
161
162 // Write bytecode out to disk or cout as the last step...
163 if (!NoOutput)
164 Passes.add(new WriteBytecodePass(Out, Out != &std::cout));
165
166 // Now that we have all of the passes ready, run them.
167 Passes.run(*M.get());
168
169 return 0;
176 return 1;
170177 }