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