Bug Summary

File:llvm/tools/llc/llc.cpp
Warning:line 668, column 13
Potential leak of memory pointed to by 'MMIWP'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name llc.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/llc -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/tools/llc -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/tools/llc/llc.cpp
1//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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// This is the llc code generator driver. It provides a convenient
10// command-line interface for generating native assembly-language code
11// or C code, given LLVM bitcode.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/ScopeExit.h"
17#include "llvm/ADT/Triple.h"
18#include "llvm/Analysis/TargetLibraryInfo.h"
19#include "llvm/CodeGen/CommandFlags.h"
20#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21#include "llvm/CodeGen/LinkAllCodegenComponents.h"
22#include "llvm/CodeGen/MIRParser/MIRParser.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/CodeGen/TargetPassConfig.h"
26#include "llvm/CodeGen/TargetSubtargetInfo.h"
27#include "llvm/IR/AutoUpgrade.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/DiagnosticPrinter.h"
31#include "llvm/IR/IRPrintingPasses.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/LLVMRemarkStreamer.h"
34#include "llvm/IR/LegacyPassManager.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/Verifier.h"
37#include "llvm/IRReader/IRReader.h"
38#include "llvm/InitializePasses.h"
39#include "llvm/MC/SubtargetFeature.h"
40#include "llvm/MC/TargetRegistry.h"
41#include "llvm/Pass.h"
42#include "llvm/Remarks/HotnessThresholdParser.h"
43#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Support/FileSystem.h"
46#include "llvm/Support/FormattedStream.h"
47#include "llvm/Support/Host.h"
48#include "llvm/Support/InitLLVM.h"
49#include "llvm/Support/ManagedStatic.h"
50#include "llvm/Support/PluginLoader.h"
51#include "llvm/Support/SourceMgr.h"
52#include "llvm/Support/TargetSelect.h"
53#include "llvm/Support/TimeProfiler.h"
54#include "llvm/Support/ToolOutputFile.h"
55#include "llvm/Support/WithColor.h"
56#include "llvm/Target/TargetLoweringObjectFile.h"
57#include "llvm/Target/TargetMachine.h"
58#include "llvm/Transforms/Utils/Cloning.h"
59#include <memory>
60using namespace llvm;
61
62static codegen::RegisterCodeGenFlags CGF;
63
64// General options for llc. Other pass-specific options are specified
65// within the corresponding llc passes, and target-specific options
66// and back-end code generation options are specified with the target machine.
67//
68static cl::opt<std::string>
69InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
70
71static cl::opt<std::string>
72InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
73
74static cl::opt<std::string>
75OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
76
77static cl::opt<std::string>
78 SplitDwarfOutputFile("split-dwarf-output",
79 cl::desc(".dwo output filename"),
80 cl::value_desc("filename"));
81
82static cl::opt<unsigned>
83TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
84 cl::value_desc("N"),
85 cl::desc("Repeat compilation N times for timing"));
86
87static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
88
89static cl::opt<unsigned> TimeTraceGranularity(
90 "time-trace-granularity",
91 cl::desc(
92 "Minimum time granularity (in microseconds) traced by time profiler"),
93 cl::init(500), cl::Hidden);
94
95static cl::opt<std::string>
96 TimeTraceFile("time-trace-file",
97 cl::desc("Specify time trace file destination"),
98 cl::value_desc("filename"));
99
100static cl::opt<std::string>
101 BinutilsVersion("binutils-version", cl::Hidden,
102 cl::desc("Produced object files can use all ELF features "
103 "supported by this binutils version and newer."
104 "If -no-integrated-as is specified, the generated "
105 "assembly will consider GNU as support."
106 "'none' means that all ELF features can be used, "
107 "regardless of binutils support"));
108
109static cl::opt<bool>
110NoIntegratedAssembler("no-integrated-as", cl::Hidden,
111 cl::desc("Disable integrated assembler"));
112
113static cl::opt<bool>
114 PreserveComments("preserve-as-comments", cl::Hidden,
115 cl::desc("Preserve Comments in outputted assembly"),
116 cl::init(true));
117
118// Determine optimization level.
119static cl::opt<char>
120OptLevel("O",
121 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
122 "(default = '-O2')"),
123 cl::Prefix,
124 cl::ZeroOrMore,
125 cl::init(' '));
126
127static cl::opt<std::string>
128TargetTriple("mtriple", cl::desc("Override target triple for module"));
129
130static cl::opt<std::string> SplitDwarfFile(
131 "split-dwarf-file",
132 cl::desc(
133 "Specify the name of the .dwo file to encode in the DWARF output"));
134
135static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
136 cl::desc("Do not verify input module"));
137
138static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
139 cl::desc("Disable simplify-libcalls"));
140
141static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
142 cl::desc("Show encoding in .s output"));
143
144static cl::opt<bool>
145 DwarfDirectory("dwarf-directory", cl::Hidden,
146 cl::desc("Use .file directives with an explicit directory"),
147 cl::init(true));
148
149static cl::opt<bool> AsmVerbose("asm-verbose",
150 cl::desc("Add comments to directives."),
151 cl::init(true));
152
153static cl::opt<bool>
154 CompileTwice("compile-twice", cl::Hidden,
155 cl::desc("Run everything twice, re-using the same pass "
156 "manager and verify the result is the same."),
157 cl::init(false));
158
159static cl::opt<bool> DiscardValueNames(
160 "discard-value-names",
161 cl::desc("Discard names from Value (other than GlobalValue)."),
162 cl::init(false), cl::Hidden);
163
164static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
165
166static cl::opt<bool> RemarksWithHotness(
167 "pass-remarks-with-hotness",
168 cl::desc("With PGO, include profile count in optimization remarks"),
169 cl::Hidden);
170
171static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
172 RemarksHotnessThreshold(
173 "pass-remarks-hotness-threshold",
174 cl::desc("Minimum profile count required for "
175 "an optimization remark to be output. "
176 "Use 'auto' to apply the threshold from profile summary."),
177 cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
178
179static cl::opt<std::string>
180 RemarksFilename("pass-remarks-output",
181 cl::desc("Output filename for pass remarks"),
182 cl::value_desc("filename"));
183
184static cl::opt<std::string>
185 RemarksPasses("pass-remarks-filter",
186 cl::desc("Only record optimization remarks from passes whose "
187 "names match the given regular expression"),
188 cl::value_desc("regex"));
189
190static cl::opt<std::string> RemarksFormat(
191 "pass-remarks-format",
192 cl::desc("The format used for serializing remarks (default: YAML)"),
193 cl::value_desc("format"), cl::init("yaml"));
194
195namespace {
196static ManagedStatic<std::vector<std::string>> RunPassNames;
197
198struct RunPassOption {
199 void operator=(const std::string &Val) const {
200 if (Val.empty())
201 return;
202 SmallVector<StringRef, 8> PassNames;
203 StringRef(Val).split(PassNames, ',', -1, false);
204 for (auto PassName : PassNames)
205 RunPassNames->push_back(std::string(PassName));
206 }
207};
208}
209
210static RunPassOption RunPassOpt;
211
212static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
213 "run-pass",
214 cl::desc("Run compiler only for specified passes (comma separated list)"),
215 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
216
217static int compileModule(char **, LLVMContext &);
218
219[[noreturn]] static void reportError(Twine Msg, StringRef Filename = "") {
220 SmallString<256> Prefix;
221 if (!Filename.empty()) {
222 if (Filename == "-")
223 Filename = "<stdin>";
224 ("'" + Twine(Filename) + "': ").toStringRef(Prefix);
225 }
226 WithColor::error(errs(), "llc") << Prefix << Msg << "\n";
227 exit(1);
228}
229
230[[noreturn]] static void reportError(Error Err, StringRef Filename) {
231 assert(Err)(static_cast <bool> (Err) ? void (0) : __assert_fail ("Err"
, "llvm/tools/llc/llc.cpp", 231, __extension__ __PRETTY_FUNCTION__
))
;
232 handleAllErrors(createFileError(Filename, std::move(Err)),
233 [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
234 llvm_unreachable("reportError() should not return")::llvm::llvm_unreachable_internal("reportError() should not return"
, "llvm/tools/llc/llc.cpp", 234)
;
235}
236
237static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
238 Triple::OSType OS,
239 const char *ProgName) {
240 // If we don't yet have an output filename, make one.
241 if (OutputFilename.empty()) {
242 if (InputFilename == "-")
243 OutputFilename = "-";
244 else {
245 // If InputFilename ends in .bc or .ll, remove it.
246 StringRef IFN = InputFilename;
247 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
248 OutputFilename = std::string(IFN.drop_back(3));
249 else if (IFN.endswith(".mir"))
250 OutputFilename = std::string(IFN.drop_back(4));
251 else
252 OutputFilename = std::string(IFN);
253
254 switch (codegen::getFileType()) {
255 case CGFT_AssemblyFile:
256 if (TargetName[0] == 'c') {
257 if (TargetName[1] == 0)
258 OutputFilename += ".cbe.c";
259 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
260 OutputFilename += ".cpp";
261 else
262 OutputFilename += ".s";
263 } else
264 OutputFilename += ".s";
265 break;
266 case CGFT_ObjectFile:
267 if (OS == Triple::Win32)
268 OutputFilename += ".obj";
269 else
270 OutputFilename += ".o";
271 break;
272 case CGFT_Null:
273 OutputFilename = "-";
274 break;
275 }
276 }
277 }
278
279 // Decide if we need "binary" output.
280 bool Binary = false;
281 switch (codegen::getFileType()) {
282 case CGFT_AssemblyFile:
283 break;
284 case CGFT_ObjectFile:
285 case CGFT_Null:
286 Binary = true;
287 break;
288 }
289
290 // Open the file.
291 std::error_code EC;
292 sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
293 if (!Binary)
294 OpenFlags |= sys::fs::OF_TextWithCRLF;
295 auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
296 if (EC) {
297 reportError(EC.message());
298 return nullptr;
299 }
300
301 return FDOut;
302}
303
304struct LLCDiagnosticHandler : public DiagnosticHandler {
305 bool *HasError;
306 LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
307 bool handleDiagnostics(const DiagnosticInfo &DI) override {
308 if (DI.getKind() == llvm::DK_SrcMgr) {
309 const auto &DISM = cast<DiagnosticInfoSrcMgr>(DI);
310 const SMDiagnostic &SMD = DISM.getSMDiag();
311
312 if (SMD.getKind() == SourceMgr::DK_Error)
313 *HasError = true;
314
315 SMD.print(nullptr, errs());
316
317 // For testing purposes, we print the LocCookie here.
318 if (DISM.isInlineAsmDiag() && DISM.getLocCookie())
319 WithColor::note() << "!srcloc = " << DISM.getLocCookie() << "\n";
320
321 return true;
322 }
323
324 if (DI.getSeverity() == DS_Error)
325 *HasError = true;
326
327 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
328 if (!Remark->isEnabled())
329 return true;
330
331 DiagnosticPrinterRawOStream DP(errs());
332 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
333 DI.print(DP);
334 errs() << "\n";
335 return true;
336 }
337};
338
339// main - Entry point for the llc compiler.
340//
341int main(int argc, char **argv) {
342 InitLLVM X(argc, argv);
343
344 // Enable debug stream buffering.
345 EnableDebugBuffering = true;
346
347 // Initialize targets first, so that --version shows registered targets.
348 InitializeAllTargets();
349 InitializeAllTargetMCs();
350 InitializeAllAsmPrinters();
351 InitializeAllAsmParsers();
352
353 // Initialize codegen and IR passes used by llc so that the -print-after,
354 // -print-before, and -stop-after options work.
355 PassRegistry *Registry = PassRegistry::getPassRegistry();
356 initializeCore(*Registry);
357 initializeCodeGen(*Registry);
358 initializeLoopStrengthReducePass(*Registry);
359 initializeLowerIntrinsicsPass(*Registry);
360 initializeEntryExitInstrumenterPass(*Registry);
361 initializePostInlineEntryExitInstrumenterPass(*Registry);
362 initializeUnreachableBlockElimLegacyPassPass(*Registry);
363 initializeConstantHoistingLegacyPassPass(*Registry);
364 initializeScalarOpts(*Registry);
365 initializeVectorization(*Registry);
366 initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);
367 initializeExpandReductionsPass(*Registry);
368 initializeExpandVectorPredicationPass(*Registry);
369 initializeHardwareLoopsPass(*Registry);
370 initializeTransformUtils(*Registry);
371 initializeReplaceWithVeclibLegacyPass(*Registry);
372
373 // Initialize debugging passes.
374 initializeScavengerTestPass(*Registry);
375
376 // Register the target printer for --version.
377 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
378
379 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
380
381 if (TimeTrace)
382 timeTraceProfilerInitialize(TimeTraceGranularity, argv[0]);
383 auto TimeTraceScopeExit = make_scope_exit([]() {
384 if (TimeTrace) {
385 if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
386 handleAllErrors(std::move(E), [&](const StringError &SE) {
387 errs() << SE.getMessage() << "\n";
388 });
389 return;
390 }
391 timeTraceProfilerCleanup();
392 }
393 });
394
395 LLVMContext Context;
396 Context.setDiscardValueNames(DiscardValueNames);
397
398 // Set a diagnostic handler that doesn't exit on the first error
399 bool HasError = false;
400 Context.setDiagnosticHandler(
401 std::make_unique<LLCDiagnosticHandler>(&HasError));
402
403 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
404 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
405 RemarksFormat, RemarksWithHotness,
406 RemarksHotnessThreshold);
407 if (Error E = RemarksFileOrErr.takeError())
408 reportError(std::move(E), RemarksFilename);
409 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
410
411 if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")
412 reportError("input language must be '', 'IR' or 'MIR'");
413
414 // Compile the module TimeCompilations times to give better compile time
415 // metrics.
416 for (unsigned I = TimeCompilations; I; --I)
417 if (int RetVal = compileModule(argv, Context))
418 return RetVal;
419
420 if (RemarksFile)
421 RemarksFile->keep();
422 return 0;
423}
424
425static bool addPass(PassManagerBase &PM, const char *argv0,
426 StringRef PassName, TargetPassConfig &TPC) {
427 if (PassName == "none")
428 return false;
429
430 const PassRegistry *PR = PassRegistry::getPassRegistry();
431 const PassInfo *PI = PR->getPassInfo(PassName);
432 if (!PI) {
433 WithColor::error(errs(), argv0)
434 << "run-pass " << PassName << " is not registered.\n";
435 return true;
436 }
437
438 Pass *P;
439 if (PI->getNormalCtor())
440 P = PI->getNormalCtor()();
441 else {
442 WithColor::error(errs(), argv0)
443 << "cannot create pass: " << PI->getPassName() << "\n";
444 return true;
445 }
446 std::string Banner = std::string("After ") + std::string(P->getPassName());
447 TPC.addMachinePrePasses();
448 PM.add(P);
449 TPC.addMachinePostPasses(Banner);
450
451 return false;
452}
453
454static int compileModule(char **argv, LLVMContext &Context) {
455 // Load the module to be compiled...
456 SMDiagnostic Err;
457 std::unique_ptr<Module> M;
458 std::unique_ptr<MIRParser> MIR;
459 Triple TheTriple;
460 std::string CPUStr = codegen::getCPUStr(),
461 FeaturesStr = codegen::getFeaturesStr();
462
463 // Set attributes on functions as loaded from MIR from command line arguments.
464 auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {
465 codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);
466 };
467
468 auto MAttrs = codegen::getMAttrs();
469 bool SkipModule = codegen::getMCPU() == "help" ||
470 (!MAttrs.empty() && MAttrs.front() == "help");
1
Assuming the condition is false
471
472 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
473 switch (OptLevel) {
2
Control jumps to 'case 32:' at line 477
474 default:
475 WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
476 return 1;
477 case ' ': break;
478 case '0': OLvl = CodeGenOpt::None; break;
479 case '1': OLvl = CodeGenOpt::Less; break;
480 case '2': OLvl = CodeGenOpt::Default; break;
481 case '3': OLvl = CodeGenOpt::Aggressive; break;
482 }
483
484 // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we
485 // use that to indicate the MC default.
486 if (!BinutilsVersion.empty() && BinutilsVersion != "none") {
3
Assuming the condition is false
487 StringRef V = BinutilsVersion.getValue();
488 unsigned Num;
489 if (V.consumeInteger(10, Num) || Num == 0 ||
490 !(V.empty() ||
491 (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {
492 WithColor::error(errs(), argv[0])
493 << "invalid -binutils-version, accepting 'none' or major.minor\n";
494 return 1;
495 }
496 }
497 TargetOptions Options;
498 auto InitializeOptions = [&](const Triple &TheTriple) {
499 Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
500 Options.BinutilsVersion =
501 TargetMachine::parseBinutilsVersion(BinutilsVersion);
502 Options.DisableIntegratedAS = NoIntegratedAssembler;
503 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
504 Options.MCOptions.MCUseDwarfDirectory = DwarfDirectory;
505 Options.MCOptions.AsmVerbose = AsmVerbose;
506 Options.MCOptions.PreserveAsmComments = PreserveComments;
507 Options.MCOptions.IASSearchPaths = IncludeDirs;
508 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
509 };
510
511 Optional<Reloc::Model> RM = codegen::getExplicitRelocModel();
512
513 const Target *TheTarget = nullptr;
514 std::unique_ptr<TargetMachine> Target;
515
516 // If user just wants to list available options, skip module loading
517 if (!SkipModule
3.1
'SkipModule' is false
) {
4
Taking true branch
518 auto SetDataLayout =
519 [&](StringRef DataLayoutTargetTriple) -> Optional<std::string> {
520 // If we are supposed to override the target triple, do so now.
521 std::string IRTargetTriple = DataLayoutTargetTriple.str();
522 if (!TargetTriple.empty())
523 IRTargetTriple = Triple::normalize(TargetTriple);
524 TheTriple = Triple(IRTargetTriple);
525 if (TheTriple.getTriple().empty())
526 TheTriple.setTriple(sys::getDefaultTargetTriple());
527
528 std::string Error;
529 TheTarget =
530 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
531 if (!TheTarget) {
532 WithColor::error(errs(), argv[0]) << Error;
533 exit(1);
534 }
535
536 // On AIX, setting the relocation model to anything other than PIC is
537 // considered a user error.
538 if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_)
539 reportError("invalid relocation model, AIX only supports PIC",
540 InputFilename);
541
542 InitializeOptions(TheTriple);
543 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
544 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
545 codegen::getExplicitCodeModel(), OLvl));
546 assert(Target && "Could not allocate target machine!")(static_cast <bool> (Target && "Could not allocate target machine!"
) ? void (0) : __assert_fail ("Target && \"Could not allocate target machine!\""
, "llvm/tools/llc/llc.cpp", 546, __extension__ __PRETTY_FUNCTION__
))
;
547
548 return Target->createDataLayout().getStringRepresentation();
549 };
550 if (InputLanguage == "mir" ||
5
Taking false branch
551 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
552 MIR = createMIRParserFromFile(InputFilename, Err, Context,
553 setMIRFunctionAttributes);
554 if (MIR)
555 M = MIR->parseIRModule(SetDataLayout);
556 } else {
557 M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
558 }
559 if (!M) {
6
Taking false branch
560 Err.print(argv[0], WithColor::error(errs(), argv[0]));
561 return 1;
562 }
563 if (!TargetTriple.empty())
7
Assuming the condition is false
564 M->setTargetTriple(Triple::normalize(TargetTriple));
565 } else {
566 TheTriple = Triple(Triple::normalize(TargetTriple));
567 if (TheTriple.getTriple().empty())
568 TheTriple.setTriple(sys::getDefaultTargetTriple());
569
570 // Get the target specific parser.
571 std::string Error;
572 TheTarget =
573 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
574 if (!TheTarget) {
575 WithColor::error(errs(), argv[0]) << Error;
576 return 1;
577 }
578
579 // On AIX, setting the relocation model to anything other than PIC is
580 // considered a user error.
581 if (TheTriple.isOSAIX() && RM.hasValue() && *RM != Reloc::PIC_) {
582 WithColor::error(errs(), argv[0])
583 << "invalid relocation model, AIX only supports PIC.\n";
584 return 1;
585 }
586
587 InitializeOptions(TheTriple);
588 Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
589 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, RM,
590 codegen::getExplicitCodeModel(), OLvl));
591 assert(Target && "Could not allocate target machine!")(static_cast <bool> (Target && "Could not allocate target machine!"
) ? void (0) : __assert_fail ("Target && \"Could not allocate target machine!\""
, "llvm/tools/llc/llc.cpp", 591, __extension__ __PRETTY_FUNCTION__
))
;
592
593 // If we don't have a module then just exit now. We do this down
594 // here since the CPU/Feature help is underneath the target machine
595 // creation.
596 return 0;
597 }
598
599 assert(M && "Should have exited if we didn't have a module!")(static_cast <bool> (M && "Should have exited if we didn't have a module!"
) ? void (0) : __assert_fail ("M && \"Should have exited if we didn't have a module!\""
, "llvm/tools/llc/llc.cpp", 599, __extension__ __PRETTY_FUNCTION__
))
;
8
Taking false branch
9
'?' condition is true
600 if (codegen::getFloatABIForCalls() != FloatABI::Default)
10
Assuming the condition is false
11
Taking false branch
601 Options.FloatABIType = codegen::getFloatABIForCalls();
602
603 // Figure out where we are going to send the output.
604 std::unique_ptr<ToolOutputFile> Out =
605 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
606 if (!Out) return 1;
12
Taking false branch
607
608 // Ensure the filename is passed down to CodeViewDebug.
609 Target->Options.ObjectFilenameForDebug = Out->outputFilename();
610
611 std::unique_ptr<ToolOutputFile> DwoOut;
612 if (!SplitDwarfOutputFile.empty()) {
13
Assuming the condition is false
14
Taking false branch
613 std::error_code EC;
614 DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
615 sys::fs::OF_None);
616 if (EC)
617 reportError(EC.message(), SplitDwarfOutputFile);
618 }
619
620 // Build up all of the passes that we want to do to the module.
621 legacy::PassManager PM;
622
623 // Add an appropriate TargetLibraryInfo pass for the module's triple.
624 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
625
626 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
627 if (DisableSimplifyLibCalls)
15
Assuming the condition is true
16
Taking true branch
628 TLII.disableAllFunctions();
629 PM.add(new TargetLibraryInfoWrapperPass(TLII));
630
631 // Verify module immediately to catch problems before doInitialization() is
632 // called on any passes.
633 if (!NoVerify && verifyModule(*M, &errs()))
17
Assuming the condition is false
634 reportError("input module cannot be verified", InputFilename);
635
636 // Override function attributes based on CPUStr, FeaturesStr, and command line
637 // flags.
638 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
639
640 if (mc::getExplicitRelaxAll() && codegen::getFileType() != CGFT_ObjectFile)
18
Assuming the condition is true
19
Assuming the condition is true
20
Taking true branch
641 WithColor::warning(errs(), argv[0])
642 << ": warning: ignoring -mc-relax-all because filetype != obj";
643
644 {
645 raw_pwrite_stream *OS = &Out->os();
646
647 // Manually do the buffering rather than using buffer_ostream,
648 // so we can memcmp the contents in CompileTwice mode
649 SmallVector<char, 0> Buffer;
650 std::unique_ptr<raw_svector_ostream> BOS;
651 if ((codegen::getFileType() != CGFT_AssemblyFile &&
21
Assuming the condition is false
23
Taking false branch
652 !Out->os().supportsSeeking()) ||
653 CompileTwice) {
22
Assuming the condition is false
654 BOS = std::make_unique<raw_svector_ostream>(Buffer);
655 OS = BOS.get();
656 }
657
658 const char *argv0 = argv[0];
659 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
660 MachineModuleInfoWrapperPass *MMIWP =
661 new MachineModuleInfoWrapperPass(&LLVMTM);
24
Memory is allocated
662
663 // Construct a custom pass pipeline that starts after instruction
664 // selection.
665 if (!RunPassNames->empty()) {
25
Assuming the condition is true
26
Taking true branch
666 if (!MIR) {
27
Taking true branch
667 WithColor::warning(errs(), argv[0])
668 << "run-pass is for .mir file only.\n";
28
Potential leak of memory pointed to by 'MMIWP'
669 return 1;
670 }
671 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
672 if (TPC.hasLimitedCodeGenPipeline()) {
673 WithColor::warning(errs(), argv[0])
674 << "run-pass cannot be used with "
675 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
676 return 1;
677 }
678
679 TPC.setDisableVerify(NoVerify);
680 PM.add(&TPC);
681 PM.add(MMIWP);
682 TPC.printAndVerify("");
683 for (const std::string &RunPassName : *RunPassNames) {
684 if (addPass(PM, argv0, RunPassName, TPC))
685 return 1;
686 }
687 TPC.setInitialized();
688 PM.add(createPrintMIRPass(*OS));
689 PM.add(createFreeMachineFunctionPass());
690 } else if (Target->addPassesToEmitFile(
691 PM, *OS, DwoOut ? &DwoOut->os() : nullptr,
692 codegen::getFileType(), NoVerify, MMIWP)) {
693 reportError("target does not support generation of this file type");
694 }
695
696 const_cast<TargetLoweringObjectFile *>(LLVMTM.getObjFileLowering())
697 ->Initialize(MMIWP->getMMI().getContext(), *Target);
698 if (MIR) {
699 assert(MMIWP && "Forgot to create MMIWP?")(static_cast <bool> (MMIWP && "Forgot to create MMIWP?"
) ? void (0) : __assert_fail ("MMIWP && \"Forgot to create MMIWP?\""
, "llvm/tools/llc/llc.cpp", 699, __extension__ __PRETTY_FUNCTION__
))
;
700 if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
701 return 1;
702 }
703
704 // Before executing passes, print the final values of the LLVM options.
705 cl::PrintOptionValues();
706
707 // If requested, run the pass manager over the same module again,
708 // to catch any bugs due to persistent state in the passes. Note that
709 // opt has the same functionality, so it may be worth abstracting this out
710 // in the future.
711 SmallVector<char, 0> CompileTwiceBuffer;
712 if (CompileTwice) {
713 std::unique_ptr<Module> M2(llvm::CloneModule(*M));
714 PM.run(*M2);
715 CompileTwiceBuffer = Buffer;
716 Buffer.clear();
717 }
718
719 PM.run(*M);
720
721 auto HasError =
722 ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
723 if (*HasError)
724 return 1;
725
726 // Compare the two outputs and make sure they're the same
727 if (CompileTwice) {
728 if (Buffer.size() != CompileTwiceBuffer.size() ||
729 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
730 0)) {
731 errs()
732 << "Running the pass manager twice changed the output.\n"
733 "Writing the result of the second run to the specified output\n"
734 "To generate the one-run comparison binary, just run without\n"
735 "the compile-twice option\n";
736 Out->os() << Buffer;
737 Out->keep();
738 return 1;
739 }
740 }
741
742 if (BOS) {
743 Out->os() << Buffer;
744 }
745 }
746
747 // Declare success.
748 Out->keep();
749 if (DwoOut)
750 DwoOut->keep();
751
752 return 0;
753}