clang: lib/CodeGen/CodeGenAction.cpp Source File (original) (raw)

1

2

3

4

5

6

7

8

31#include "llvm/ADT/Hashing.h"

32#include "llvm/ADT/ScopeExit.h"

33#include "llvm/Bitcode/BitcodeReader.h"

34#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"

35#include "llvm/Demangle/Demangle.h"

36#include "llvm/IR/DebugInfo.h"

37#include "llvm/IR/DiagnosticInfo.h"

38#include "llvm/IR/DiagnosticPrinter.h"

39#include "llvm/IR/GlobalValue.h"

40#include "llvm/IR/LLVMContext.h"

41#include "llvm/IR/LLVMRemarkStreamer.h"

42#include "llvm/IR/Module.h"

43#include "llvm/IR/Verifier.h"

44#include "llvm/IRReader/IRReader.h"

45#include "llvm/LTO/LTOBackend.h"

46#include "llvm/Linker/Linker.h"

47#include "llvm/Pass.h"

48#include "llvm/Support/MemoryBuffer.h"

49#include "llvm/Support/SourceMgr.h"

50#include "llvm/Support/TimeProfiler.h"

51#include "llvm/Support/Timer.h"

52#include "llvm/Support/ToolOutputFile.h"

53#include "llvm/Transforms/IPO/Internalize.h"

54#include "llvm/Transforms/Utils/Cloning.h"

55

56#include

57using namespace clang;

58using namespace llvm;

59

60#define DEBUG_TYPE "codegenaction"

61

65public:

67 : CodeGenOpts(CGOpts), BackendCon(BCon) {}

68

70

72 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);

73 }

75 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);

76 }

78 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);

79 }

80

82 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||

83 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||

84 CodeGenOpts.OptimizationRemark.hasValidPattern();

85 }

86

87private:

90};

91

94 handleAllErrors(

95 std::move(E),

96 [&](const LLVMRemarkSetupFileError &E) {

97 Diags.Report(diag::err_cannot_open_file)

99 },

100 [&](const LLVMRemarkSetupPatternError &E) {

101 Diags.Report(diag::err_drv_optimization_remark_pattern)

103 },

104 [&](const LLVMRemarkSetupFormatError &E) {

105 Diags.Report(diag::err_drv_optimization_remark_format)

107 });

108}

109

112 LLVMContext &C,

114 StringRef InFile,

115 std::unique_ptr<raw_pwrite_stream> OS,

117 llvm::Module *CurLinkModule)

118 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),

119 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),

120 AsmOutStream(std::move(OS)), FS(VFS), Action(Action),

122 CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),

123 CI.getCodeGenOpts(), C, CoverageInfo)),

124 LinkModules(std::move(LinkModules)), CurLinkModule(CurLinkModule) {

125 TimerIsEnabled = CodeGenOpts.TimePasses;

126 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;

127 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;

128 if (CodeGenOpts.TimePasses)

129 LLVMIRGeneration.init("irgen", "LLVM IR generation", CI.getTimerGroup());

130}

131

133 return Gen->GetModule();

134}

135

137 return std::unique_ptrllvm::Module(Gen->ReleaseModule());

138}

139

141 return Gen.get();

142}

143

147

149 assert(!Context && "initialized multiple times");

150

151 Context = &Ctx;

152

153 if (TimerIsEnabled)

154 LLVMIRGeneration.startTimer();

155

156 Gen->Initialize(Ctx);

157

158 if (TimerIsEnabled)

159 LLVMIRGeneration.stopTimer();

160}

161

164 Context->getSourceManager(),

165 "LLVM IR generation of declaration");

166

167

168 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)

169 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);

170

171 Gen->HandleTopLevelDecl(D);

172

173 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)

174 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());

175

176 return true;

177}

178

181 Context->getSourceManager(),

182 "LLVM IR generation of inline function");

183 if (TimerIsEnabled)

184 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);

185

186 Gen->HandleInlineFunctionDefinition(D);

187

188 if (TimerIsEnabled)

189 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());

190}

191

195

196

198 for (auto &LM : LinkModules) {

199 assert(LM.Module && "LinkModule does not actually have a module");

200

201 if (LM.PropagateAttrs)

202 for (Function &F : *LM.Module) {

203

204

205 if (F.isIntrinsic())

206 continue;

208 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);

209 }

210

211 CurLinkModule = LM.Module.get();

212 bool Err;

213

214 if (LM.Internalize) {

215 Err = Linker::linkModules(

216 *M, std::move(LM.Module), LM.LinkFlags,

217 [](llvm::Module &M, const llvm::StringSet<> &GVS) {

218 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {

219 return !GV.hasName() || (GVS.count(GV.getName()) == 0);

220 });

221 });

222 } else

223 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);

224

225 if (Err)

226 return true;

227 }

228

229 LinkModules.clear();

230 return false;

231}

232

234 {

235 llvm::TimeTraceScope TimeScope("Frontend");

236 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");

237 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)

238 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);

239

240 Gen->HandleTranslationUnit(C);

241

242 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)

243 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());

244 }

245

246

248 return;

249

250 LLVMContext &Ctx = getModule()->getContext();

251 std::unique_ptr OldDiagnosticHandler =

252 Ctx.getDiagnosticHandler();

253 Ctx.setDiagnosticHandler(std::make_unique(

254 CodeGenOpts, this));

255

256 Ctx.setDefaultTargetCPU(TargetOpts.CPU);

257 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));

258

260 setupLLVMOptimizationRemarks(

261 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,

262 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,

263 CodeGenOpts.DiagnosticsHotnessThreshold);

264

265 if (Error E = OptRecordFileOrErr.takeError()) {

267 return;

268 }

269

270 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);

271

272 if (OptRecordFile && CodeGenOpts.getProfileUse() !=

273 llvm::driver::ProfileInstrKind::ProfileNone)

274 Ctx.setDiagnosticsHotnessRequested(true);

275

276 if (CodeGenOpts.MisExpect) {

277 Ctx.setMisExpectWarningRequested(true);

278 }

279

280 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {

281 Ctx.setDiagnosticsMisExpectTolerance(

282 CodeGenOpts.DiagnosticsMisExpectTolerance);

283 }

284

285

287 return;

288

289 for (auto &F : getModule()->functions()) {

290 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {

291 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());

292

294 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));

295 }

296 }

297

298 if (CodeGenOpts.ClearASTBeforeBackend) {

299 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");

300

301

302

303

304

305

306 C.cleanup();

307 C.getAllocator().Reset();

308 }

309

311

313 C.getTargetInfo().getDataLayoutString(), getModule(),

314 Action, FS, std::move(AsmOutStream), this);

315

316 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));

317

318 if (OptRecordFile)

319 OptRecordFile->keep();

320}

321

324 Context->getSourceManager(),

325 "LLVM IR generation of declaration");

326 Gen->HandleTagDeclDefinition(D);

327}

328

330 Gen->HandleTagDeclRequiredDefinition(D);

331}

332

334 Gen->CompleteTentativeDefinition(D);

335}

336

338 Gen->CompleteExternalDeclaration(D);

339}

340

342 Gen->AssignInheritanceModel(RD);

343}

344

346 Gen->HandleVTable(RD);

347}

348

349void BackendConsumer::anchor() { }

350

351}

352

354 BackendCon->DiagnosticHandlerImpl(DI);

355 return true;

356}

357

358

359

362

363

364

365 const llvm::SourceMgr &LSM = *D.getSourceMgr();

366

367

368

369 const MemoryBuffer *LBuf =

370 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));

371

372

373

374 std::unique_ptrllvm::MemoryBuffer CBuf =

375 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),

376 LBuf->getBufferIdentifier());

377

379

380

381 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();

385}

386

387#define ComputeDiagID(Severity, GroupName, DiagID) \

388 do { \

389 switch (Severity) { \

390 case llvm::DS_Error: \

391 DiagID = diag::err_fe_##GroupName; \

392 break; \

393 case llvm::DS_Warning: \

394 DiagID = diag::warn_fe_##GroupName; \

395 break; \

396 case llvm::DS_Remark: \

397 llvm_unreachable("'remark' severity not expected"); \

398 break; \

399 case llvm::DS_Note: \

400 DiagID = diag::note_fe_##GroupName; \

401 break; \

402 } \

403 } while (false)

404

405#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \

406 do { \

407 switch (Severity) { \

408 case llvm::DS_Error: \

409 DiagID = diag::err_fe_##GroupName; \

410 break; \

411 case llvm::DS_Warning: \

412 DiagID = diag::warn_fe_##GroupName; \

413 break; \

414 case llvm::DS_Remark: \

415 DiagID = diag::remark_fe_##GroupName; \

416 break; \

417 case llvm::DS_Note: \

418 DiagID = diag::note_fe_##GroupName; \

419 break; \

420 } \

421 } while (false)

422

424 const llvm::SMDiagnostic &D = DI.getSMDiag();

425

426 unsigned DiagID;

427 if (DI.isInlineAsmDiag())

428 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);

429 else

430 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);

431

432

433

434 if (!Context) {

435 D.print(nullptr, llvm::errs());

436 Diags.Report(DiagID).AddString("cannot compile inline asm");

437 return;

438 }

439

440

441

442

443

444 StringRef Message = D.getMessage();

445 (void)Message.consume_front("error: ");

446

447

449 if (D.getLoc() != SMLoc())

451

452

453

454

455 if (DI.isInlineAsmDiag()) {

458 if (LocCookie.isValid()) {

459 Diags.Report(LocCookie, DiagID).AddString(Message);

460

461 if (D.getLoc().isValid()) {

462 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);

463

464

465 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {

466 unsigned Column = D.getColumnNo();

469 }

470 }

471 return;

472 }

473 }

474

475

476

477

478 Diags.Report(Loc, DiagID).AddString(Message);

479}

480

481bool

483 unsigned DiagID;

484 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);

485 std::string Message = D.getMsgStr().str();

486

487

488

489

493 Diags.Report(LocCookie, DiagID).AddString(Message);

494 else {

495

496

497

498

500 Diags.Report(Loc, DiagID).AddString(Message);

501 }

502

503 return true;

504}

505

506bool

508 if (D.getSeverity() != llvm::DS_Warning)

509

510

511 return false;

512

514 if (!Loc)

515 return false;

516

517 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)

518 << D.getStackSize() << D.getStackLimit()

519 << llvm::demangle(D.getFunction().getName());

520 return true;

521}

522

524 const llvm::DiagnosticInfoResourceLimit &D) {

526 if (!Loc)

527 return false;

528 unsigned DiagID = diag::err_fe_backend_resource_limit;

529 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);

530

531 Diags.Report(*Loc, DiagID)

532 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()

533 << llvm::demangle(D.getFunction().getName());

534 return true;

535}

536

538 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,

539 StringRef &Filename, unsigned &Line, unsigned &Column) const {

540 SourceManager &SourceMgr = Context->getSourceManager();

543

544 if (D.isLocationAvailable()) {

545 D.getLocation(Filename, Line, Column);

546 if (Line > 0) {

547 auto FE = FileMgr.getOptionalFileRef(Filename);

548 if (!FE)

549 FE = FileMgr.getOptionalFileRef(D.getAbsolutePath());

550 if (FE) {

551

552

553 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);

554 }

555 }

556 BadDebugInfo = DILoc.isInvalid();

557 }

558

559

560

561

565 Loc = *MaybeLoc;

566 }

567

568 if (DILoc.isInvalid() && D.isLocationAvailable())

569

570

571

572

573 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)

575

576 return Loc;

577}

578

579std::optional

582 for (const auto &Pair : ManglingFullSourceLocs) {

583 if (Pair.first == Hash)

584 return Pair.second;

585 }

586 return std::nullopt;

587}

588

590 const llvm::DiagnosticInfoUnsupported &D) {

591

592 assert(D.getSeverity() == llvm::DS_Error ||

593 D.getSeverity() == llvm::DS_Warning);

594

595 StringRef Filename;

597 bool BadDebugInfo = false;

599 std::string Msg;

600 raw_string_ostream MsgStream(Msg);

601

602

603

604 if (Context != nullptr) {

606 MsgStream << D.getMessage();

607 } else {

608 DiagnosticPrinterRawOStream DP(MsgStream);

609 D.print(DP);

610 }

611

612 auto DiagType = D.getSeverity() == llvm::DS_Error

613 ? diag::err_fe_backend_unsupported

614 : diag::warn_fe_backend_unsupported;

615 Diags.Report(Loc, DiagType) << Msg;

616

617 if (BadDebugInfo)

618

619

620

621

622 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)

624}

625

627 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {

628

629 assert(D.getSeverity() == llvm::DS_Remark ||

630 D.getSeverity() == llvm::DS_Warning);

631

632 StringRef Filename;

634 bool BadDebugInfo = false;

636 std::string Msg;

637 raw_string_ostream MsgStream(Msg);

638

639

640

641 if (Context != nullptr) {

643 MsgStream << D.getMsg();

644 } else {

645 DiagnosticPrinterRawOStream DP(MsgStream);

646 D.print(DP);

647 }

648

649 if (D.getHotness())

650 MsgStream << " (hotness: " << *D.getHotness() << ")";

651

652 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;

653

654 if (BadDebugInfo)

655

656

657

658

659 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)

661}

662

664 const llvm::DiagnosticInfoOptimizationBase &D) {

665

666 if (D.isVerbose() && !D.getHotness())

667 return;

668

669 if (D.isPassed()) {

670

671

672 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))

674 } else if (D.isMissed()) {

675

676

677

678 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))

680 D, diag::remark_fe_backend_optimization_remark_missed);

681 } else {

682 assert(D.isAnalysis() && "Unknown remark type");

683

684 bool ShouldAlwaysPrint = false;

685 if (auto *ORA = dyn_castllvm::OptimizationRemarkAnalysis(&D))

686 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();

687

688 if (ShouldAlwaysPrint ||

689 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))

691 D, diag::remark_fe_backend_optimization_remark_analysis);

692 }

693}

694

696 const llvm::OptimizationRemarkAnalysisFPCommute &D) {

697

698

699

700

701 if (D.shouldAlwaysPrint() ||

702 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))

704 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);

705}

706

708 const llvm::OptimizationRemarkAnalysisAliasing &D) {

709

710

711

712

713 if (D.shouldAlwaysPrint() ||

714 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))

716 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);

717}

718

720 const llvm::DiagnosticInfoOptimizationFailure &D) {

722}

723

727

728

729

730 if (!LocCookie.isValid())

731 return;

732

733 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error

734 ? diag::err_fe_backend_error_attr

735 : diag::warn_fe_backend_warning_attr)

736 << llvm::demangle(D.getFunctionName()) << D.getNote();

737}

738

740 const llvm::DiagnosticInfoMisExpect &D) {

741 StringRef Filename;

743 bool BadDebugInfo = false;

746

747 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();

748

749 if (BadDebugInfo)

750

751

752

753

754 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)

756}

757

758

759

761 unsigned DiagID = diag::err_fe_inline_asm;

762 llvm::DiagnosticSeverity Severity = DI.getSeverity();

763

764 switch (DI.getKind()) {

765 case llvm::DK_InlineAsm:

767 return;

769 break;

770 case llvm::DK_SrcMgr:

772 return;

773 case llvm::DK_StackSize:

775 return;

776 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);

777 break;

778 case llvm::DK_ResourceLimit:

780 return;

781 ComputeDiagID(Severity, backend_resource_limit, DiagID);

782 break;

783 case DK_Linker:

785 break;

786 case llvm::DK_OptimizationRemark:

787

788

790 return;

791 case llvm::DK_OptimizationRemarkMissed:

792

793

795 return;

796 case llvm::DK_OptimizationRemarkAnalysis:

797

798

800 return;

801 case llvm::DK_OptimizationRemarkAnalysisFPCommute:

802

803

805 return;

806 case llvm::DK_OptimizationRemarkAnalysisAliasing:

807

808

810 return;

811 case llvm::DK_MachineOptimizationRemark:

812

813

815 return;

816 case llvm::DK_MachineOptimizationRemarkMissed:

817

818

820 return;

821 case llvm::DK_MachineOptimizationRemarkAnalysis:

822

823

825 return;

826 case llvm::DK_OptimizationFailure:

827

828

830 return;

831 case llvm::DK_Unsupported:

833 return;

834 case llvm::DK_DontCall:

836 return;

837 case llvm::DK_MisExpect:

839 return;

840 default:

841

843 break;

844 }

845 std::string MsgStorage;

846 {

847 raw_string_ostream Stream(MsgStorage);

848 DiagnosticPrinterRawOStream DP(Stream);

849 DI.print(DP);

850 }

851

852 if (DI.getKind() == DK_Linker) {

853 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");

854 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;

855 return;

856 }

857

858

860 Diags.Report(Loc, DiagID).AddString(MsgStorage);

861}

862#undef ComputeDiagID

863

865 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),

866 OwnsVMContext(!_VMContext) {}

867

869 TheModule.reset();

870 if (OwnsVMContext)

871 delete VMContext;

872}

873

875 if (!LinkModules.empty())

876 return false;

877

881 if (!BCBuf) {

883 << F.Filename << BCBuf.getError().message();

884 LinkModules.clear();

885 return true;

886 }

887

889 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);

890 if (!ModuleOrErr) {

891 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {

892 CI.getDiagnostics().Report(diag::err_cannot_open_file)

893 << F.Filename << EIB.message();

894 });

895 LinkModules.clear();

896 return true;

897 }

898 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,

899 F.Internalize, F.LinkFlags});

900 }

901 return false;

902}

903

905

908

909

911 return;

912

913

914 TheModule = BEConsumer->takeModule();

915}

916

918 return std::move(TheModule);

919}

920

922 OwnsVMContext = false;

923 return VMContext;

924}

925

929

935

936static std::unique_ptr<raw_pwrite_stream>

938 switch (Action) {

946 return nullptr;

951 }

952

953 llvm_unreachable("Invalid action!");

954}

955

956std::unique_ptr

959 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();

960 if (!OS)

962

964 return nullptr;

965

966

967 if (loadLinkModules(CI))

968 return nullptr;

969

971

975

978 InFile, std::move(OS), CoverageInfo));

980

981

982

983 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&

985 std::unique_ptr Callbacks =

986 std::make_unique(BEConsumer->getCodeGenerator(),

989 }

990

993 std::vector<std::unique_ptr> Consumers(2);

994 Consumers[0] = std::make_unique(

997 Consumers[1] = std::move(Result);

998 return std::make_unique(std::move(Consumers));

999 }

1000

1001 return std::move(Result);

1002}

1003

1004std::unique_ptrllvm::Module

1005CodeGenAction::loadModule(MemoryBufferRef MBRef) {

1008

1009 auto DiagErrors = [&](Error E) -> std::unique_ptrllvm::Module {

1010 unsigned DiagID =

1012 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {

1014 });

1015 return {};

1016 };

1017

1018

1019

1020

1022 VMContext->enableDebugTypeODRUniquing();

1023

1024 Expected<std::vector> BMsOrErr = getBitcodeModuleList(MBRef);

1025 if (!BMsOrErr)

1026 return DiagErrors(BMsOrErr.takeError());

1027 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);

1028

1029

1030

1031

1032 if (!Bm) {

1033 auto M = std::make_uniquellvm::Module("empty", *VMContext);

1035 return M;

1036 }

1037 Expected<std::unique_ptrllvm::Module> MOrErr =

1038 Bm->parseModule(*VMContext);

1039 if (!MOrErr)

1040 return DiagErrors(MOrErr.takeError());

1041 return std::move(*MOrErr);

1042 }

1043

1044

1045 if (loadLinkModules(CI))

1046 return nullptr;

1047

1048

1049 llvm::SMDiagnostic Err;

1050 if (std::unique_ptrllvm::Module M = parseIR(MBRef, Err, *VMContext)) {

1051

1052

1053 std::string VerifierErr;

1054 raw_string_ostream VerifierErrStream(VerifierErr);

1055 if (llvm::verifyModule(*M, &VerifierErrStream)) {

1057 return {};

1058 }

1059 return M;

1060 }

1061

1062

1063

1064

1065 Expected<std::vector> BMsOrErr = getBitcodeModuleList(MBRef);

1066 if (BMsOrErr && BMsOrErr->size()) {

1067 std::unique_ptrllvm::Module FirstM;

1068 for (auto &BM : *BMsOrErr) {

1069 Expected<std::unique_ptrllvm::Module> MOrErr =

1070 BM.parseModule(*VMContext);

1071 if (!MOrErr)

1072 return DiagErrors(MOrErr.takeError());

1073 if (FirstM)

1074 LinkModules.push_back({std::move(*MOrErr), false,

1075 false, {}});

1076 else

1077 FirstM = std::move(*MOrErr);

1078 }

1079 if (FirstM)

1080 return FirstM;

1081 }

1082

1083

1084 consumeError(BMsOrErr.takeError());

1085

1086

1087

1088

1089 SourceLocation Loc;

1090 if (Err.getLineNo() > 0) {

1091 assert(Err.getColumnNo() >= 0);

1092 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),

1093 Err.getLineNo(), Err.getColumnNo() + 1);

1094 }

1095

1096

1097 StringRef Msg = Err.getMessage();

1098 Msg.consume_front("error: ");

1099

1100 unsigned DiagID =

1102

1104 return {};

1105}

1106

1110 return;

1111 }

1112

1113

1118 std::unique_ptr<raw_pwrite_stream> OS =

1121 return;

1122

1124 FileID FID = SM.getMainFileID();

1125 std::optional MainFile = SM.getBufferOrNone(FID);

1126 if (!MainFile)

1127 return;

1128

1129 TheModule = loadModule(*MainFile);

1130 if (!TheModule)

1131 return;

1132

1134 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {

1135 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)

1136 << TargetOpts.Triple;

1137 TheModule->setTargetTriple(Triple(TargetOpts.Triple));

1138 }

1139

1141 Diagnostics);

1142 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);

1143

1144 LLVMContext &Ctx = TheModule->getContext();

1145

1146

1147

1148 struct RAII {

1149 LLVMContext &Ctx;

1150 std::unique_ptr PrevHandler = Ctx.getDiagnosticHandler();

1151 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }

1152 } _{Ctx};

1153

1154

1155

1157 std::move(LinkModules), "", nullptr, nullptr,

1158 TheModule.get());

1159

1160

1161 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))

1162 return;

1163

1164

1165

1166 Ctx.setDiscardValueNames(false);

1167 Ctx.setDiagnosticHandler(

1168 std::make_unique(CodeGenOpts, &Result));

1169

1170 Ctx.setDefaultTargetCPU(TargetOpts.CPU);

1171 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));

1172

1174 setupLLVMOptimizationRemarks(

1175 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,

1176 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,

1177 CodeGenOpts.DiagnosticsHotnessThreshold);

1178

1179 if (Error E = OptRecordFileOrErr.takeError()) {

1181 return;

1182 }

1183 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);

1184

1188 std::move(OS));

1189 if (OptRecordFile)

1190 OptRecordFile->keep();

1191}

1192

1193

1194

1195void EmitAssemblyAction::anchor() { }

1198

1199void EmitBCAction::anchor() { }

1202

1203void EmitLLVMAction::anchor() { }

1206

1207void EmitLLVMOnlyAction::anchor() { }

1210

1211void EmitCodeGenOnlyAction::anchor() { }

1214

1215void EmitObjAction::anchor() { }

Defines the clang::ASTContext interface.

#define ComputeDiagID(Severity, GroupName, DiagID)

Definition CodeGenAction.cpp:387

static std::unique_ptr< raw_pwrite_stream > GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action)

Definition CodeGenAction.cpp:937

#define ComputeDiagRemarkID(Severity, GroupName, DiagID)

Definition CodeGenAction.cpp:405

static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM)

ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr buffer to be a valid FullS...

Definition CodeGenAction.cpp:360

Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....

Defines the clang::FileManager interface and associated types.

Defines the clang::Preprocessor interface.

Defines the SourceManager interface.

virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)

HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.

Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...

void ExecuteAction() override

Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.

llvm::Module * getModule() const

Definition CodeGenAction.cpp:132

void CompleteExternalDeclaration(DeclaratorDecl *D) override

CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...

Definition CodeGenAction.cpp:337

void OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D)

Definition CodeGenAction.cpp:663

bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D)

Specialized handler for StackSize diagnostic.

Definition CodeGenAction.cpp:507

void HandleVTable(CXXRecordDecl *RD) override

Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...

Definition CodeGenAction.cpp:345

void HandleTagDeclDefinition(TagDecl *D) override

HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.

Definition CodeGenAction.cpp:322

bool HandleTopLevelDecl(DeclGroupRef D) override

HandleTopLevelDecl - Handle the specified top-level declaration.

Definition CodeGenAction.cpp:162

void Initialize(ASTContext &Ctx) override

Initialize - This is called to initialize the consumer, providing the ASTContext.

Definition CodeGenAction.cpp:148

void HandleInlineFunctionDefinition(FunctionDecl *D) override

This callback is invoked each time an inline (method or friend) function definition in a class is com...

Definition CodeGenAction.cpp:179

void OptimizationFailureHandler(const llvm::DiagnosticInfoOptimizationFailure &D)

Definition CodeGenAction.cpp:719

void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI)

This function is invoked when the backend needs to report something to the user.

Definition CodeGenAction.cpp:760

void HandleTagDeclRequiredDefinition(const TagDecl *D) override

This callback is invoked the first time each TagDecl is required to be complete.

Definition CodeGenAction.cpp:329

void HandleInterestingDecl(DeclGroupRef D) override

HandleInterestingDecl - Handle the specified interesting declaration.

Definition CodeGenAction.cpp:192

void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override

HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.

Definition CodeGenAction.cpp:144

std::optional< FullSourceLoc > getFunctionSourceLocation(const llvm::Function &F) const

Definition CodeGenAction.cpp:580

bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D)

Specialized handler for ResourceLimit diagnostic.

Definition CodeGenAction.cpp:523

std::unique_ptr< llvm::Module > takeModule()

Definition CodeGenAction.cpp:136

void AssignInheritanceModel(CXXRecordDecl *RD) override

Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.

Definition CodeGenAction.cpp:341

void HandleTranslationUnit(ASTContext &C) override

HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...

Definition CodeGenAction.cpp:233

void CompleteTentativeDefinition(VarDecl *D) override

CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...

Definition CodeGenAction.cpp:333

void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D)

Specialized handler for unsupported backend feature diagnostic.

Definition CodeGenAction.cpp:589

bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D)

Specialized handler for InlineAsm diagnostic.

Definition CodeGenAction.cpp:482

bool LinkInModules(llvm::Module *M)

Definition CodeGenAction.cpp:197

const FullSourceLoc getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const

Get the best possible source location to represent a diagnostic that may have associated debug info.

Definition CodeGenAction.cpp:537

void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID)

Specialized handlers for optimization remarks.

Definition CodeGenAction.cpp:626

void DontCallDiagHandler(const llvm::DiagnosticInfoDontCall &D)

Definition CodeGenAction.cpp:724

void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D)

Specialized handler for misexpect warnings.

Definition CodeGenAction.cpp:739

CodeGenerator * getCodeGenerator()

Definition CodeGenAction.cpp:140

void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D)

Specialized handler for diagnostics reported using SMDiagnostic.

Definition CodeGenAction.cpp:423

BackendConsumer(CompilerInstance &CI, BackendAction Action, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, llvm::LLVMContext &C, SmallVector< LinkModule, 4 > LinkModules, StringRef InFile, std::unique_ptr< raw_pwrite_stream > OS, CoverageSourceInfo *CoverageInfo, llvm::Module *CurLinkModule=nullptr)

Definition CodeGenAction.cpp:110

Represents a C++ struct/union/class.

bool isMissedOptRemarkEnabled(StringRef PassName) const override

Definition CodeGenAction.cpp:74

bool handleDiagnostics(const DiagnosticInfo &DI) override

Definition CodeGenAction.cpp:353

ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)

Definition CodeGenAction.cpp:66

bool isPassedOptRemarkEnabled(StringRef PassName) const override

Definition CodeGenAction.cpp:77

bool isAnyRemarkEnabled() const override

Definition CodeGenAction.cpp:81

bool isAnalysisRemarkEnabled(StringRef PassName) const override

Definition CodeGenAction.cpp:71

std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override

Create the AST consumer object for this action, if supported.

Definition CodeGenAction.cpp:957

CodeGenerator * getCodeGenerator() const

Definition CodeGenAction.cpp:926

friend class BackendConsumer

void EndSourceFileAction() override

Callback at the end of processing a single input.

Definition CodeGenAction.cpp:906

bool BeginSourceFileAction(CompilerInstance &CI) override

Callback at the start of processing a single input.

Definition CodeGenAction.cpp:930

~CodeGenAction() override

Definition CodeGenAction.cpp:868

CodeGenAction(unsigned _Act, llvm::LLVMContext *_VMContext=nullptr)

Create a new code generation action.

Definition CodeGenAction.cpp:864

llvm::LLVMContext * takeLLVMContext()

Take the LLVM context used by this action.

Definition CodeGenAction.cpp:921

BackendConsumer * BEConsumer

bool hasIRSupport() const override

Does this action support use with IR files?

Definition CodeGenAction.cpp:904

void ExecuteAction() override

Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.

Definition CodeGenAction.cpp:1107

std::unique_ptr< llvm::Module > takeModule()

Take the generated LLVM module, for use after the action has been run.

Definition CodeGenAction.cpp:917

CodeGenOptions - Track various options which control how the code is optimized and passed to the back...

std::string OptRecordFile

The name of the file to which the backend should save YAML optimization records.

std::vector< BitcodeFileToLink > LinkBitcodeFiles

The files specified here are linked in to the module before optimizations.

std::string OptRecordPasses

The regex that filters the passes that should be saved to the optimization records.

std::string ThinLTOIndexFile

Name of the function summary index file to use for ThinLTO function importing.

std::string OptRecordFormat

The format used for serializing remarks (default: YAML)

static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)

The primary public interface to the Clang code generator.

CompilerInstance - Helper class for managing a single instance of the Clang compiler.

DiagnosticsEngine & getDiagnostics() const

Get the current diagnostics engine.

std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)

Create the default output file (from the invocation's options) and add it to the list of tracked outp...

FileManager & getFileManager() const

Return the current file manager to the caller.

ModuleCache & getModuleCache() const

Preprocessor & getPreprocessor() const

Return the current preprocessor.

IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const

TargetOptions & getTargetOpts()

std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()

FrontendOptions & getFrontendOpts()

TargetInfo & getTarget() const

llvm::vfs::FileSystem & getVirtualFileSystem() const

LangOptions & getLangOpts()

CodeGenOptions & getCodeGenOpts()

SourceManager & getSourceManager() const

Return the current source manager.

std::unique_ptr< raw_pwrite_stream > createNullOutputFile()

Stores additional source code information like skipped ranges which is required by the coverage mappi...

Decl - This represents one declaration (or definition), e.g.

Represents a ValueDecl that came out of a declarator.

A little helper class used to produce diagnostics.

Concrete class used by the front-end to report problems and issues.

DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)

Issue the message to the client.

unsigned getCustomDiagID(Level L, const char(&FormatString)[N])

Return an ID for a diagnostic with the specified format string and level.

EmitAssemblyAction(llvm::LLVMContext *_VMContext=nullptr)

Definition CodeGenAction.cpp:1196

EmitBCAction(llvm::LLVMContext *_VMContext=nullptr)

Definition CodeGenAction.cpp:1200

EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext=nullptr)

Definition CodeGenAction.cpp:1212

EmitLLVMAction(llvm::LLVMContext *_VMContext=nullptr)

Definition CodeGenAction.cpp:1204

EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext=nullptr)

Definition CodeGenAction.cpp:1208

EmitObjAction(llvm::LLVMContext *_VMContext=nullptr)

Definition CodeGenAction.cpp:1216

An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...

Implements support for file system lookup, file system caching, and directory search management.

llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)

Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...

llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const

InputKind getCurrentFileKind() const

virtual void EndSourceFileAction()

Callback at the end of processing a single input.

CompilerInstance & getCompilerInstance() const

virtual bool BeginSourceFileAction(CompilerInstance &CI)

Callback at the start of processing a single input.

StringRef getCurrentFileOrBufferName() const

unsigned GenReducedBMI

Whether to generate reduced BMI for C++20 named modules.

std::string ModuleOutputPath

Output Path for module output file.

A SourceLocation and its associated SourceManager.

Represents a function declaration or definition.

@ CMK_ModuleInterface

Compiling a C++ modules interface unit.

void addPPCallbacks(std::unique_ptr< PPCallbacks > C)

PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...

Encodes a location in the source.

static SourceLocation getFromRawEncoding(UIntTy Encoding)

Turn a raw encoding of a SourceLocation object into a real SourceLocation.

bool isValid() const

Return true if this is a valid SourceLocation object.

SourceLocation getLocWithOffset(IntTy Offset) const

Return a source location with the specified offset from this SourceLocation.

This class handles loading and caching of source files into memory.

FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)

Create a new FileID that represents the specified file being #included from the specified IncludePosi...

SourceLocation getLocForStartOfFile(FileID FID) const

Return the source location corresponding to the first byte of the specified file.

A trivial tuple used to represent a source range.

Represents the declaration of a struct/union/class/enum.

const char * getDataLayoutString() const

Options for controlling the target.

std::string Triple

The name of the target triple to compile for.

std::vector< std::string > Features

The list of target specific features to enable or disable – this should be a list of strings starting...

std::string CPU

If given, the name of the target CPU to generate code for.

Represents a variable declaration or definition.

Defines the clang::TargetInfo interface.

void mergeDefaultFunctionDefinitionAttributes(llvm::Function &F, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, bool WillInternalize)

Adds attributes to F according to our CodeGenOpts and LangOpts, as though we had emitted it ourselves...

The JSON file list parser is used to communicate input to InstallAPI.

static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)

Definition CodeGenAction.cpp:92

CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)

CreateLLVMCodeGen - Create a CodeGenerator instance.

@ Result

The result type of a method or function.

void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)

void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)

void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)

@ Backend_EmitAssembly

Emit native assembly files.

@ Backend_EmitLL

Emit human-readable LLVM assembly.

@ Backend_EmitBC

Emit LLVM bitcode files.

@ Backend_EmitObj

Emit native object files.

@ Backend_EmitMCNull

Run CodeGen, but don't emit anything.

@ Backend_EmitNothing

Don't emit anything (benchmarking mode)

U cast(CodeGen::Address addr)

Diagnostic wrappers for TextAPI types for error reporting.

hash_code hash_value(const clang::dependencies::ModuleID &ID)