1 //===- SourceCoverageView.cpp - Code coverage view for source code --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// 10 /// \file This class implements rendering for code coverage of source code. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "SourceCoverageView.h" 15 #include "SourceCoverageViewHTML.h" 16 #include "SourceCoverageViewText.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/Support/FileSystem.h" 20 #include "llvm/Support/LineIterator.h" 21 #include "llvm/Support/Path.h" 22 23 using namespace llvm; 24 25 void CoveragePrinter::StreamDestructor::operator()(raw_ostream *OS) const { 26 if (OS == &outs()) 27 return; 28 delete OS; 29 } 30 31 std::string CoveragePrinter::getOutputPath(StringRef Path, StringRef Extension, 32 bool InToplevel, bool Relative) { 33 assert(Extension.size() && "The file extension may not be empty"); 34 35 SmallString<256> FullPath; 36 37 if (!Relative) 38 FullPath.append(Opts.ShowOutputDirectory); 39 40 if (!InToplevel) 41 sys::path::append(FullPath, getCoverageDir()); 42 43 SmallString<256> ParentPath = sys::path::parent_path(Path); 44 sys::path::remove_dots(ParentPath, /*remove_dot_dots=*/true); 45 sys::path::append(FullPath, sys::path::relative_path(ParentPath)); 46 47 auto PathFilename = (sys::path::filename(Path) + "." + Extension).str(); 48 sys::path::append(FullPath, PathFilename); 49 sys::path::native(FullPath); 50 51 return FullPath.str(); 52 } 53 54 Expected<CoveragePrinter::OwnedStream> 55 CoveragePrinter::createOutputStream(StringRef Path, StringRef Extension, 56 bool InToplevel) { 57 if (!Opts.hasOutputDirectory()) 58 return OwnedStream(&outs()); 59 60 std::string FullPath = getOutputPath(Path, Extension, InToplevel, false); 61 62 auto ParentDir = sys::path::parent_path(FullPath); 63 if (auto E = sys::fs::create_directories(ParentDir)) 64 return errorCodeToError(E); 65 66 std::error_code E; 67 raw_ostream *RawStream = new raw_fd_ostream(FullPath, E, sys::fs::F_RW); 68 auto OS = CoveragePrinter::OwnedStream(RawStream); 69 if (E) 70 return errorCodeToError(E); 71 return std::move(OS); 72 } 73 74 std::unique_ptr<CoveragePrinter> 75 CoveragePrinter::create(const CoverageViewOptions &Opts) { 76 switch (Opts.Format) { 77 case CoverageViewOptions::OutputFormat::Text: 78 return llvm::make_unique<CoveragePrinterText>(Opts); 79 case CoverageViewOptions::OutputFormat::HTML: 80 return llvm::make_unique<CoveragePrinterHTML>(Opts); 81 } 82 llvm_unreachable("Unknown coverage output format!"); 83 } 84 85 unsigned SourceCoverageView::getFirstUncoveredLineNo() { 86 auto CheckIfUncovered = [](const coverage::CoverageSegment &S) { 87 return S.HasCount && S.Count == 0; 88 }; 89 // L is less than R if (1) it's an uncovered segment (has a 0 count), and (2) 90 // either R is not an uncovered segment, or L has a lower line number than R. 91 const auto MinSegIt = 92 std::min_element(CoverageInfo.begin(), CoverageInfo.end(), 93 [CheckIfUncovered](const coverage::CoverageSegment &L, 94 const coverage::CoverageSegment &R) { 95 return (CheckIfUncovered(L) && 96 (!CheckIfUncovered(R) || (L.Line < R.Line))); 97 }); 98 if (CheckIfUncovered(*MinSegIt)) 99 return (*MinSegIt).Line; 100 // There is no uncovered line, return zero. 101 return 0; 102 } 103 104 std::string SourceCoverageView::formatCount(uint64_t N) { 105 std::string Number = utostr(N); 106 int Len = Number.size(); 107 if (Len <= 3) 108 return Number; 109 int IntLen = Len % 3 == 0 ? 3 : Len % 3; 110 std::string Result(Number.data(), IntLen); 111 if (IntLen != 3) { 112 Result.push_back('.'); 113 Result += Number.substr(IntLen, 3 - IntLen); 114 } 115 Result.push_back(" kMGTPEZY"[(Len - 1) / 3]); 116 return Result; 117 } 118 119 bool SourceCoverageView::shouldRenderRegionMarkers( 120 bool LineHasMultipleRegions) const { 121 return getOptions().ShowRegionMarkers && 122 (!getOptions().ShowLineStatsOrRegionMarkers || LineHasMultipleRegions); 123 } 124 125 bool SourceCoverageView::hasSubViews() const { 126 return !ExpansionSubViews.empty() || !InstantiationSubViews.empty(); 127 } 128 129 std::unique_ptr<SourceCoverageView> 130 SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File, 131 const CoverageViewOptions &Options, 132 coverage::CoverageData &&CoverageInfo) { 133 switch (Options.Format) { 134 case CoverageViewOptions::OutputFormat::Text: 135 return llvm::make_unique<SourceCoverageViewText>( 136 SourceName, File, Options, std::move(CoverageInfo)); 137 case CoverageViewOptions::OutputFormat::HTML: 138 return llvm::make_unique<SourceCoverageViewHTML>( 139 SourceName, File, Options, std::move(CoverageInfo)); 140 } 141 llvm_unreachable("Unknown coverage output format!"); 142 } 143 144 std::string SourceCoverageView::getSourceName() const { 145 SmallString<128> SourceText(SourceName); 146 sys::path::remove_dots(SourceText, /*remove_dot_dots=*/true); 147 sys::path::native(SourceText); 148 return SourceText.str(); 149 } 150 151 std::string SourceCoverageView::getVerboseSourceName() const { 152 return "Source: " + getSourceName() + " (Binary: " + 153 sys::path::filename(getOptions().ObjectFilename).str() + ")"; 154 } 155 156 void SourceCoverageView::addExpansion( 157 const coverage::CounterMappingRegion &Region, 158 std::unique_ptr<SourceCoverageView> View) { 159 ExpansionSubViews.emplace_back(Region, std::move(View)); 160 } 161 162 void SourceCoverageView::addInstantiation( 163 StringRef FunctionName, unsigned Line, 164 std::unique_ptr<SourceCoverageView> View) { 165 InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View)); 166 } 167 168 void SourceCoverageView::print(raw_ostream &OS, bool WholeFile, 169 bool ShowSourceName, unsigned ViewDepth) { 170 if (WholeFile) 171 renderCellInTitle(OS, "Code Coverage Report"); 172 173 renderViewHeader(OS); 174 175 unsigned FirstUncoveredLineNo = 0; 176 if (WholeFile) 177 FirstUncoveredLineNo = getFirstUncoveredLineNo(); 178 179 if (ShowSourceName) 180 renderSourceName(OS, WholeFile, FirstUncoveredLineNo); 181 182 renderTableHeader(OS, ViewDepth); 183 // We need the expansions and instantiations sorted so we can go through them 184 // while we iterate lines. 185 std::sort(ExpansionSubViews.begin(), ExpansionSubViews.end()); 186 std::sort(InstantiationSubViews.begin(), InstantiationSubViews.end()); 187 auto NextESV = ExpansionSubViews.begin(); 188 auto EndESV = ExpansionSubViews.end(); 189 auto NextISV = InstantiationSubViews.begin(); 190 auto EndISV = InstantiationSubViews.end(); 191 192 // Get the coverage information for the file. 193 auto NextSegment = CoverageInfo.begin(); 194 auto EndSegment = CoverageInfo.end(); 195 196 unsigned FirstLine = NextSegment != EndSegment ? NextSegment->Line : 0; 197 const coverage::CoverageSegment *WrappedSegment = nullptr; 198 SmallVector<const coverage::CoverageSegment *, 8> LineSegments; 199 for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof(); ++LI) { 200 // If we aren't rendering the whole file, we need to filter out the prologue 201 // and epilogue. 202 if (!WholeFile) { 203 if (NextSegment == EndSegment) 204 break; 205 else if (LI.line_number() < FirstLine) 206 continue; 207 } 208 209 // Collect the coverage information relevant to this line. 210 if (LineSegments.size()) 211 WrappedSegment = LineSegments.back(); 212 LineSegments.clear(); 213 while (NextSegment != EndSegment && NextSegment->Line == LI.line_number()) 214 LineSegments.push_back(&*NextSegment++); 215 216 // Calculate a count to be for the line as a whole. 217 LineCoverageStats LineCount; 218 if (WrappedSegment && WrappedSegment->HasCount) 219 LineCount.addRegionCount(WrappedSegment->Count); 220 for (const auto *S : LineSegments) 221 if (S->HasCount && S->IsRegionEntry) 222 LineCount.addRegionStartCount(S->Count); 223 224 renderLinePrefix(OS, ViewDepth); 225 if (getOptions().ShowLineNumbers) 226 renderLineNumberColumn(OS, LI.line_number()); 227 if (getOptions().ShowLineStats) 228 renderLineCoverageColumn(OS, LineCount); 229 230 // If there are expansion subviews, we want to highlight the first one. 231 unsigned ExpansionColumn = 0; 232 if (NextESV != EndESV && NextESV->getLine() == LI.line_number() && 233 getOptions().Colors) 234 ExpansionColumn = NextESV->getStartCol(); 235 236 // Display the source code for the current line. 237 renderLine(OS, {*LI, LI.line_number()}, WrappedSegment, LineSegments, 238 ExpansionColumn, ViewDepth); 239 240 // Show the region markers. 241 if (shouldRenderRegionMarkers(LineCount.hasMultipleRegions())) 242 renderRegionMarkers(OS, LineSegments, ViewDepth); 243 244 // Show the expansions and instantiations for this line. 245 bool RenderedSubView = false; 246 for (; NextESV != EndESV && NextESV->getLine() == LI.line_number(); 247 ++NextESV) { 248 renderViewDivider(OS, ViewDepth + 1); 249 250 // Re-render the current line and highlight the expansion range for 251 // this subview. 252 if (RenderedSubView) { 253 ExpansionColumn = NextESV->getStartCol(); 254 renderExpansionSite(OS, {*LI, LI.line_number()}, WrappedSegment, 255 LineSegments, ExpansionColumn, ViewDepth); 256 renderViewDivider(OS, ViewDepth + 1); 257 } 258 259 renderExpansionView(OS, *NextESV, ViewDepth + 1); 260 RenderedSubView = true; 261 } 262 for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) { 263 renderViewDivider(OS, ViewDepth + 1); 264 renderInstantiationView(OS, *NextISV, ViewDepth + 1); 265 RenderedSubView = true; 266 } 267 if (RenderedSubView) 268 renderViewDivider(OS, ViewDepth + 1); 269 renderLineSuffix(OS, ViewDepth); 270 } 271 272 renderViewFooter(OS); 273 } 274