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 LineCoverageStats::LineCoverageStats( 87 ArrayRef<const coverage::CoverageSegment *> LineSegments, 88 const coverage::CoverageSegment *WrappedSegment) { 89 // Find the minimum number of regions which start in this line. 90 unsigned MinRegionCount = 0; 91 auto isStartOfRegion = [](const coverage::CoverageSegment *S) { 92 return S->HasCount && S->IsRegionEntry; 93 }; 94 for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I) 95 if (isStartOfRegion(LineSegments[I])) 96 ++MinRegionCount; 97 98 ExecutionCount = 0; 99 HasMultipleRegions = MinRegionCount > 1; 100 Mapped = (WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0); 101 102 if (!Mapped) 103 return; 104 105 // Pick the max count among regions which start and end on this line, to 106 // avoid erroneously using the wrapped count, and to avoid picking region 107 // counts which come from deferred regions. 108 if (LineSegments.size() > 1) { 109 for (unsigned I = 0; I < LineSegments.size() - 1; ++I) 110 ExecutionCount = std::max(ExecutionCount, LineSegments[I]->Count); 111 return; 112 } 113 114 // Just pick the maximum count. 115 if (WrappedSegment && WrappedSegment->HasCount) 116 ExecutionCount = WrappedSegment->Count; 117 if (!LineSegments.empty()) 118 ExecutionCount = std::max(ExecutionCount, LineSegments[0]->Count); 119 } 120 121 unsigned SourceCoverageView::getFirstUncoveredLineNo() { 122 auto CheckIfUncovered = [](const coverage::CoverageSegment &S) { 123 return S.HasCount && S.Count == 0; 124 }; 125 // L is less than R if (1) it's an uncovered segment (has a 0 count), and (2) 126 // either R is not an uncovered segment, or L has a lower line number than R. 127 const auto MinSegIt = 128 std::min_element(CoverageInfo.begin(), CoverageInfo.end(), 129 [CheckIfUncovered](const coverage::CoverageSegment &L, 130 const coverage::CoverageSegment &R) { 131 return (CheckIfUncovered(L) && 132 (!CheckIfUncovered(R) || (L.Line < R.Line))); 133 }); 134 if (CheckIfUncovered(*MinSegIt)) 135 return (*MinSegIt).Line; 136 // There is no uncovered line, return zero. 137 return 0; 138 } 139 140 std::string SourceCoverageView::formatCount(uint64_t N) { 141 std::string Number = utostr(N); 142 int Len = Number.size(); 143 if (Len <= 3) 144 return Number; 145 int IntLen = Len % 3 == 0 ? 3 : Len % 3; 146 std::string Result(Number.data(), IntLen); 147 if (IntLen != 3) { 148 Result.push_back('.'); 149 Result += Number.substr(IntLen, 3 - IntLen); 150 } 151 Result.push_back(" kMGTPEZY"[(Len - 1) / 3]); 152 return Result; 153 } 154 155 bool SourceCoverageView::shouldRenderRegionMarkers( 156 bool LineHasMultipleRegions) const { 157 return getOptions().ShowRegionMarkers && 158 (!getOptions().ShowLineStatsOrRegionMarkers || LineHasMultipleRegions); 159 } 160 161 bool SourceCoverageView::hasSubViews() const { 162 return !ExpansionSubViews.empty() || !InstantiationSubViews.empty(); 163 } 164 165 std::unique_ptr<SourceCoverageView> 166 SourceCoverageView::create(StringRef SourceName, const MemoryBuffer &File, 167 const CoverageViewOptions &Options, 168 coverage::CoverageData &&CoverageInfo) { 169 switch (Options.Format) { 170 case CoverageViewOptions::OutputFormat::Text: 171 return llvm::make_unique<SourceCoverageViewText>( 172 SourceName, File, Options, std::move(CoverageInfo)); 173 case CoverageViewOptions::OutputFormat::HTML: 174 return llvm::make_unique<SourceCoverageViewHTML>( 175 SourceName, File, Options, std::move(CoverageInfo)); 176 } 177 llvm_unreachable("Unknown coverage output format!"); 178 } 179 180 std::string SourceCoverageView::getSourceName() const { 181 SmallString<128> SourceText(SourceName); 182 sys::path::remove_dots(SourceText, /*remove_dot_dots=*/true); 183 sys::path::native(SourceText); 184 return SourceText.str(); 185 } 186 187 void SourceCoverageView::addExpansion( 188 const coverage::CounterMappingRegion &Region, 189 std::unique_ptr<SourceCoverageView> View) { 190 ExpansionSubViews.emplace_back(Region, std::move(View)); 191 } 192 193 void SourceCoverageView::addInstantiation( 194 StringRef FunctionName, unsigned Line, 195 std::unique_ptr<SourceCoverageView> View) { 196 InstantiationSubViews.emplace_back(FunctionName, Line, std::move(View)); 197 } 198 199 void SourceCoverageView::print(raw_ostream &OS, bool WholeFile, 200 bool ShowSourceName, unsigned ViewDepth) { 201 if (WholeFile && getOptions().hasOutputDirectory()) 202 renderTitle(OS, "Coverage Report"); 203 204 renderViewHeader(OS); 205 206 if (ShowSourceName) 207 renderSourceName(OS, WholeFile); 208 209 renderTableHeader(OS, (ViewDepth > 0) ? 0 : getFirstUncoveredLineNo(), 210 ViewDepth); 211 212 // We need the expansions and instantiations sorted so we can go through them 213 // while we iterate lines. 214 std::sort(ExpansionSubViews.begin(), ExpansionSubViews.end()); 215 std::sort(InstantiationSubViews.begin(), InstantiationSubViews.end()); 216 auto NextESV = ExpansionSubViews.begin(); 217 auto EndESV = ExpansionSubViews.end(); 218 auto NextISV = InstantiationSubViews.begin(); 219 auto EndISV = InstantiationSubViews.end(); 220 221 // Get the coverage information for the file. 222 auto NextSegment = CoverageInfo.begin(); 223 auto EndSegment = CoverageInfo.end(); 224 225 unsigned FirstLine = NextSegment != EndSegment ? NextSegment->Line : 0; 226 const coverage::CoverageSegment *WrappedSegment = nullptr; 227 SmallVector<const coverage::CoverageSegment *, 8> LineSegments; 228 for (line_iterator LI(File, /*SkipBlanks=*/false); !LI.is_at_eof(); ++LI) { 229 // If we aren't rendering the whole file, we need to filter out the prologue 230 // and epilogue. 231 if (!WholeFile) { 232 if (NextSegment == EndSegment) 233 break; 234 else if (LI.line_number() < FirstLine) 235 continue; 236 } 237 238 // Collect the coverage information relevant to this line. 239 if (LineSegments.size()) 240 WrappedSegment = LineSegments.back(); 241 LineSegments.clear(); 242 while (NextSegment != EndSegment && NextSegment->Line == LI.line_number()) 243 LineSegments.push_back(&*NextSegment++); 244 245 renderLinePrefix(OS, ViewDepth); 246 if (getOptions().ShowLineNumbers) 247 renderLineNumberColumn(OS, LI.line_number()); 248 249 LineCoverageStats LineCount{LineSegments, WrappedSegment}; 250 if (getOptions().ShowLineStats) 251 renderLineCoverageColumn(OS, LineCount); 252 253 // If there are expansion subviews, we want to highlight the first one. 254 unsigned ExpansionColumn = 0; 255 if (NextESV != EndESV && NextESV->getLine() == LI.line_number() && 256 getOptions().Colors) 257 ExpansionColumn = NextESV->getStartCol(); 258 259 // Display the source code for the current line. 260 renderLine(OS, {*LI, LI.line_number()}, WrappedSegment, LineSegments, 261 ExpansionColumn, ViewDepth); 262 263 // Show the region markers. 264 if (shouldRenderRegionMarkers(LineCount.hasMultipleRegions())) 265 renderRegionMarkers(OS, LineSegments, ViewDepth); 266 267 // Show the expansions and instantiations for this line. 268 bool RenderedSubView = false; 269 for (; NextESV != EndESV && NextESV->getLine() == LI.line_number(); 270 ++NextESV) { 271 renderViewDivider(OS, ViewDepth + 1); 272 273 // Re-render the current line and highlight the expansion range for 274 // this subview. 275 if (RenderedSubView) { 276 ExpansionColumn = NextESV->getStartCol(); 277 renderExpansionSite(OS, {*LI, LI.line_number()}, WrappedSegment, 278 LineSegments, ExpansionColumn, ViewDepth); 279 renderViewDivider(OS, ViewDepth + 1); 280 } 281 282 renderExpansionView(OS, *NextESV, ViewDepth + 1); 283 RenderedSubView = true; 284 } 285 for (; NextISV != EndISV && NextISV->Line == LI.line_number(); ++NextISV) { 286 renderViewDivider(OS, ViewDepth + 1); 287 renderInstantiationView(OS, *NextISV, ViewDepth + 1); 288 RenderedSubView = true; 289 } 290 if (RenderedSubView) 291 renderViewDivider(OS, ViewDepth + 1); 292 renderLineSuffix(OS, ViewDepth); 293 } 294 295 renderViewFooter(OS); 296 } 297