1fce43576SEugene Zelenko //===- DataFlowSanitizer.cpp - dynamic data flow analysis -----------------===//
2e5d5b0c7SPeter Collingbourne //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5d5b0c7SPeter Collingbourne //
7e5d5b0c7SPeter Collingbourne //===----------------------------------------------------------------------===//
8fce43576SEugene Zelenko //
9e5d5b0c7SPeter Collingbourne /// \file
10e5d5b0c7SPeter Collingbourne /// This file is a part of DataFlowSanitizer, a generalised dynamic data flow
11e5d5b0c7SPeter Collingbourne /// analysis.
12e5d5b0c7SPeter Collingbourne ///
13e5d5b0c7SPeter Collingbourne /// Unlike other Sanitizer tools, this tool is not designed to detect a specific
14e5d5b0c7SPeter Collingbourne /// class of bugs on its own.  Instead, it provides a generic dynamic data flow
15e5d5b0c7SPeter Collingbourne /// analysis framework to be used by clients to help detect application-specific
16e5d5b0c7SPeter Collingbourne /// issues within their own code.
17e5d5b0c7SPeter Collingbourne ///
18e5d5b0c7SPeter Collingbourne /// The analysis is based on automatic propagation of data flow labels (also
19d10f173fSGeorge Balatsouras /// known as taint labels) through a program as it performs computation.
20d10f173fSGeorge Balatsouras ///
2161ec2148SAndrew Browne /// Argument and return value labels are passed through TLS variables
2261ec2148SAndrew Browne /// __dfsan_arg_tls and __dfsan_retval_tls.
2361ec2148SAndrew Browne ///
245b4dda55SGeorge Balatsouras /// Each byte of application memory is backed by a shadow memory byte. The
255b4dda55SGeorge Balatsouras /// shadow byte can represent up to 8 labels. On Linux/x86_64, memory is then
265b4dda55SGeorge Balatsouras /// laid out as follows:
27d10f173fSGeorge Balatsouras ///
28d10f173fSGeorge Balatsouras /// +--------------------+ 0x800000000000 (top of memory)
2945f6d552SAndrew Browne /// |    application 3   |
3045f6d552SAndrew Browne /// +--------------------+ 0x700000000000
3145f6d552SAndrew Browne /// |      invalid       |
3245f6d552SAndrew Browne /// +--------------------+ 0x610000000000
3345f6d552SAndrew Browne /// |      origin 1      |
3445f6d552SAndrew Browne /// +--------------------+ 0x600000000000
3545f6d552SAndrew Browne /// |    application 2   |
3645f6d552SAndrew Browne /// +--------------------+ 0x510000000000
3745f6d552SAndrew Browne /// |      shadow 1      |
3845f6d552SAndrew Browne /// +--------------------+ 0x500000000000
3945f6d552SAndrew Browne /// |      invalid       |
4045f6d552SAndrew Browne /// +--------------------+ 0x400000000000
4145f6d552SAndrew Browne /// |      origin 3      |
4245f6d552SAndrew Browne /// +--------------------+ 0x300000000000
4345f6d552SAndrew Browne /// |      shadow 3      |
445b4dda55SGeorge Balatsouras /// +--------------------+ 0x200000000000
4545f6d552SAndrew Browne /// |      origin 2      |
4645f6d552SAndrew Browne /// +--------------------+ 0x110000000000
4745f6d552SAndrew Browne /// |      invalid       |
4845f6d552SAndrew Browne /// +--------------------+ 0x100000000000
4945f6d552SAndrew Browne /// |      shadow 2      |
5045f6d552SAndrew Browne /// +--------------------+ 0x010000000000
5145f6d552SAndrew Browne /// |    application 1   |
52d10f173fSGeorge Balatsouras /// +--------------------+ 0x000000000000
53d10f173fSGeorge Balatsouras ///
5445f6d552SAndrew Browne /// MEM_TO_SHADOW(mem) = mem ^ 0x500000000000
5545f6d552SAndrew Browne /// SHADOW_TO_ORIGIN(shadow) = shadow + 0x100000000000
56e5d5b0c7SPeter Collingbourne ///
57e5d5b0c7SPeter Collingbourne /// For more information, please refer to the design document:
58e5d5b0c7SPeter Collingbourne /// http://clang.llvm.org/docs/DataFlowSanitizerDesign.html
59fce43576SEugene Zelenko //
60fce43576SEugene Zelenko //===----------------------------------------------------------------------===//
61e5d5b0c7SPeter Collingbourne 
6271d0a2b8SArthur Eubanks #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
63e5d5b0c7SPeter Collingbourne #include "llvm/ADT/DenseMap.h"
64e5d5b0c7SPeter Collingbourne #include "llvm/ADT/DenseSet.h"
65e5d5b0c7SPeter Collingbourne #include "llvm/ADT/DepthFirstIterator.h"
66fce43576SEugene Zelenko #include "llvm/ADT/None.h"
67fce43576SEugene Zelenko #include "llvm/ADT/SmallPtrSet.h"
68fce43576SEugene Zelenko #include "llvm/ADT/SmallVector.h"
69fce43576SEugene Zelenko #include "llvm/ADT/StringRef.h"
705748219fSAndrew Browne #include "llvm/ADT/StringSet.h"
710826e607SPeter Collingbourne #include "llvm/ADT/Triple.h"
726ff18b08SGeorge Balatsouras #include "llvm/ADT/iterator.h"
73e5d5b0c7SPeter Collingbourne #include "llvm/Analysis/ValueTracking.h"
74fce43576SEugene Zelenko #include "llvm/IR/Argument.h"
75fce43576SEugene Zelenko #include "llvm/IR/Attributes.h"
76fce43576SEugene Zelenko #include "llvm/IR/BasicBlock.h"
77fce43576SEugene Zelenko #include "llvm/IR/Constant.h"
78fce43576SEugene Zelenko #include "llvm/IR/Constants.h"
79fce43576SEugene Zelenko #include "llvm/IR/DataLayout.h"
80fce43576SEugene Zelenko #include "llvm/IR/DerivedTypes.h"
816bda14b3SChandler Carruth #include "llvm/IR/Dominators.h"
82fce43576SEugene Zelenko #include "llvm/IR/Function.h"
83fce43576SEugene Zelenko #include "llvm/IR/GlobalAlias.h"
84fce43576SEugene Zelenko #include "llvm/IR/GlobalValue.h"
85fce43576SEugene Zelenko #include "llvm/IR/GlobalVariable.h"
86e5d5b0c7SPeter Collingbourne #include "llvm/IR/IRBuilder.h"
877da14f1aSChandler Carruth #include "llvm/IR/InstVisitor.h"
88fce43576SEugene Zelenko #include "llvm/IR/InstrTypes.h"
89fce43576SEugene Zelenko #include "llvm/IR/Instruction.h"
90fce43576SEugene Zelenko #include "llvm/IR/Instructions.h"
91fce43576SEugene Zelenko #include "llvm/IR/IntrinsicInst.h"
92e5d5b0c7SPeter Collingbourne #include "llvm/IR/MDBuilder.h"
93fce43576SEugene Zelenko #include "llvm/IR/Module.h"
9471d0a2b8SArthur Eubanks #include "llvm/IR/PassManager.h"
95e5d5b0c7SPeter Collingbourne #include "llvm/IR/Type.h"
96fce43576SEugene Zelenko #include "llvm/IR/User.h"
97e5d5b0c7SPeter Collingbourne #include "llvm/IR/Value.h"
9805da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
99e5d5b0c7SPeter Collingbourne #include "llvm/Pass.h"
100d866b9c9SJianzhou Zhao #include "llvm/Support/Alignment.h"
101fce43576SEugene Zelenko #include "llvm/Support/Casting.h"
102e5d5b0c7SPeter Collingbourne #include "llvm/Support/CommandLine.h"
103fce43576SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
104b7dd329fSAlexey Samsonov #include "llvm/Support/SpecialCaseList.h"
105aa981c18SIlya Biryukov #include "llvm/Support/VirtualFileSystem.h"
1066bda14b3SChandler Carruth #include "llvm/Transforms/Instrumentation.h"
107e5d5b0c7SPeter Collingbourne #include "llvm/Transforms/Utils/BasicBlockUtils.h"
10805da2fe5SReid Kleckner #include "llvm/Transforms/Utils/Local.h"
1099947c498SPeter Collingbourne #include <algorithm>
110fce43576SEugene Zelenko #include <cassert>
111fce43576SEugene Zelenko #include <cstddef>
112fce43576SEugene Zelenko #include <cstdint>
113fce43576SEugene Zelenko #include <memory>
1149947c498SPeter Collingbourne #include <set>
115fce43576SEugene Zelenko #include <string>
1169947c498SPeter Collingbourne #include <utility>
117fce43576SEugene Zelenko #include <vector>
118e5d5b0c7SPeter Collingbourne 
119e5d5b0c7SPeter Collingbourne using namespace llvm;
120e5d5b0c7SPeter Collingbourne 
12180e326a8SJianzhou Zhao // This must be consistent with ShadowWidthBits.
1226ff18b08SGeorge Balatsouras static const Align ShadowTLSAlignment = Align(2);
12380e326a8SJianzhou Zhao 
1246ff18b08SGeorge Balatsouras static const Align MinOriginAlignment = Align(4);
125cb1f1aabSJianzhou Zhao 
12680e326a8SJianzhou Zhao // The size of TLS variables. These constants must be kept in sync with the ones
12780e326a8SJianzhou Zhao // in dfsan.cpp.
1286ff18b08SGeorge Balatsouras static const unsigned ArgTLSSize = 800;
1296ff18b08SGeorge Balatsouras static const unsigned RetvalTLSSize = 800;
13080e326a8SJianzhou Zhao 
131e5d5b0c7SPeter Collingbourne // The -dfsan-preserve-alignment flag controls whether this pass assumes that
132e5d5b0c7SPeter Collingbourne // alignment requirements provided by the input IR are correct.  For example,
133e5d5b0c7SPeter Collingbourne // if the input IR contains a load with alignment 8, this flag will cause
134e5d5b0c7SPeter Collingbourne // the shadow load to have alignment 16.  This flag is disabled by default as
135e5d5b0c7SPeter Collingbourne // we have unfortunately encountered too much code (including Clang itself;
136e5d5b0c7SPeter Collingbourne // see PR14291) which performs misaligned access.
137e5d5b0c7SPeter Collingbourne static cl::opt<bool> ClPreserveAlignment(
138e5d5b0c7SPeter Collingbourne     "dfsan-preserve-alignment",
139e5d5b0c7SPeter Collingbourne     cl::desc("respect alignment requirements provided by input IR"), cl::Hidden,
140e5d5b0c7SPeter Collingbourne     cl::init(false));
141e5d5b0c7SPeter Collingbourne 
142b9b8027cSAlexey Samsonov // The ABI list files control how shadow parameters are passed. The pass treats
14368162e75SPeter Collingbourne // every function labelled "uninstrumented" in the ABI list file as conforming
14468162e75SPeter Collingbourne // to the "native" (i.e. unsanitized) ABI.  Unless the ABI list contains
14568162e75SPeter Collingbourne // additional annotations for those functions, a call to one of those functions
14668162e75SPeter Collingbourne // will produce a warning message, as the labelling behaviour of the function is
147c533b88aSAndrew Browne // unknown. The other supported annotations for uninstrumented functions are
148c533b88aSAndrew Browne // "functional" and "discard", which are described below under
149c533b88aSAndrew Browne // DataFlowSanitizer::WrapperKind.
150c533b88aSAndrew Browne // Functions will often be labelled with both "uninstrumented" and one of
151c533b88aSAndrew Browne // "functional" or "discard". This will leave the function unchanged by this
152c533b88aSAndrew Browne // pass, and create a wrapper function that will call the original.
153c533b88aSAndrew Browne //
154c533b88aSAndrew Browne // Instrumented functions can also be annotated as "force_zero_labels", which
155c533b88aSAndrew Browne // will make all shadow and return values set zero labels.
156c533b88aSAndrew Browne // Functions should never be labelled with both "force_zero_labels" and
157c533b88aSAndrew Browne // "uninstrumented" or any of the unistrumented wrapper kinds.
158b9b8027cSAlexey Samsonov static cl::list<std::string> ClABIListFiles(
15968162e75SPeter Collingbourne     "dfsan-abilist",
16068162e75SPeter Collingbourne     cl::desc("File listing native ABI functions and how the pass treats them"),
161e5d5b0c7SPeter Collingbourne     cl::Hidden);
162e5d5b0c7SPeter Collingbourne 
1630be79e1aSPeter Collingbourne // Controls whether the pass includes or ignores the labels of pointers in load
1640be79e1aSPeter Collingbourne // instructions.
1650be79e1aSPeter Collingbourne static cl::opt<bool> ClCombinePointerLabelsOnLoad(
1660be79e1aSPeter Collingbourne     "dfsan-combine-pointer-labels-on-load",
1670be79e1aSPeter Collingbourne     cl::desc("Combine the label of the pointer with the label of the data when "
1680be79e1aSPeter Collingbourne              "loading from memory."),
1690be79e1aSPeter Collingbourne     cl::Hidden, cl::init(true));
1700be79e1aSPeter Collingbourne 
1710be79e1aSPeter Collingbourne // Controls whether the pass includes or ignores the labels of pointers in
1720be79e1aSPeter Collingbourne // stores instructions.
1730be79e1aSPeter Collingbourne static cl::opt<bool> ClCombinePointerLabelsOnStore(
1740be79e1aSPeter Collingbourne     "dfsan-combine-pointer-labels-on-store",
1750be79e1aSPeter Collingbourne     cl::desc("Combine the label of the pointer with the label of the data when "
1760be79e1aSPeter Collingbourne              "storing in memory."),
1770be79e1aSPeter Collingbourne     cl::Hidden, cl::init(false));
1780be79e1aSPeter Collingbourne 
179fc1d3984SJianzhou Zhao // Controls whether the pass propagates labels of offsets in GEP instructions.
180fc1d3984SJianzhou Zhao static cl::opt<bool> ClCombineOffsetLabelsOnGEP(
181fc1d3984SJianzhou Zhao     "dfsan-combine-offset-labels-on-gep",
182fc1d3984SJianzhou Zhao     cl::desc(
183fc1d3984SJianzhou Zhao         "Combine the label of the offset with the label of the pointer when "
184fc1d3984SJianzhou Zhao         "doing pointer arithmetic."),
185fc1d3984SJianzhou Zhao     cl::Hidden, cl::init(true));
186fc1d3984SJianzhou Zhao 
1875748219fSAndrew Browne static cl::list<std::string> ClCombineTaintLookupTables(
1885748219fSAndrew Browne     "dfsan-combine-taint-lookup-table",
1895748219fSAndrew Browne     cl::desc(
1905748219fSAndrew Browne         "When dfsan-combine-offset-labels-on-gep and/or "
1915748219fSAndrew Browne         "dfsan-combine-pointer-labels-on-load are false, this flag can "
1925748219fSAndrew Browne         "be used to re-enable combining offset and/or pointer taint when "
1935748219fSAndrew Browne         "loading specific constant global variables (i.e. lookup tables)."),
1945748219fSAndrew Browne     cl::Hidden);
1955748219fSAndrew Browne 
196444c59e2SPeter Collingbourne static cl::opt<bool> ClDebugNonzeroLabels(
197444c59e2SPeter Collingbourne     "dfsan-debug-nonzero-labels",
198444c59e2SPeter Collingbourne     cl::desc("Insert calls to __dfsan_nonzero_label on observing a parameter, "
199444c59e2SPeter Collingbourne              "load or return with a nonzero label"),
200444c59e2SPeter Collingbourne     cl::Hidden);
201444c59e2SPeter Collingbourne 
202470db54cSMatt Morehouse // Experimental feature that inserts callbacks for certain data events.
20330bb737aSMatt Morehouse // Currently callbacks are only inserted for loads, stores, memory transfers
20430bb737aSMatt Morehouse // (i.e. memcpy and memmove), and comparisons.
205470db54cSMatt Morehouse //
206470db54cSMatt Morehouse // If this flag is set to true, the user must provide definitions for the
207470db54cSMatt Morehouse // following callback functions:
20806c9b4aaSJianzhou Zhao //   void __dfsan_load_callback(dfsan_label Label, void* addr);
20906c9b4aaSJianzhou Zhao //   void __dfsan_store_callback(dfsan_label Label, void* addr);
210f668baa4SMatt Morehouse //   void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
21130bb737aSMatt Morehouse //   void __dfsan_cmp_callback(dfsan_label CombinedLabel);
212470db54cSMatt Morehouse static cl::opt<bool> ClEventCallbacks(
213470db54cSMatt Morehouse     "dfsan-event-callbacks",
214470db54cSMatt Morehouse     cl::desc("Insert calls to __dfsan_*_callback functions on data events."),
215470db54cSMatt Morehouse     cl::Hidden, cl::init(false));
216470db54cSMatt Morehouse 
2174e173585SAndrew Browne // Experimental feature that inserts callbacks for conditionals, including:
2184e173585SAndrew Browne // conditional branch, switch, select.
2194e173585SAndrew Browne // This must be true for dfsan_set_conditional_callback() to have effect.
2204e173585SAndrew Browne static cl::opt<bool> ClConditionalCallbacks(
2214e173585SAndrew Browne     "dfsan-conditional-callbacks",
2224e173585SAndrew Browne     cl::desc("Insert calls to callback functions on conditionals."), cl::Hidden,
2234e173585SAndrew Browne     cl::init(false));
2244e173585SAndrew Browne 
2250dd87825SJianzhou Zhao // Controls whether the pass tracks the control flow of select instructions.
2260dd87825SJianzhou Zhao static cl::opt<bool> ClTrackSelectControlFlow(
2270dd87825SJianzhou Zhao     "dfsan-track-select-control-flow",
2280dd87825SJianzhou Zhao     cl::desc("Propagate labels from condition values of select instructions "
2290dd87825SJianzhou Zhao              "to results."),
2300dd87825SJianzhou Zhao     cl::Hidden, cl::init(true));
2310dd87825SJianzhou Zhao 
232db7fe6cdSJianzhou Zhao // TODO: This default value follows MSan. DFSan may use a different value.
233db7fe6cdSJianzhou Zhao static cl::opt<int> ClInstrumentWithCallThreshold(
234db7fe6cdSJianzhou Zhao     "dfsan-instrument-with-call-threshold",
235db7fe6cdSJianzhou Zhao     cl::desc("If the function being instrumented requires more than "
236db7fe6cdSJianzhou Zhao              "this number of origin stores, use callbacks instead of "
237db7fe6cdSJianzhou Zhao              "inline checks (-1 means never use callbacks)."),
238db7fe6cdSJianzhou Zhao     cl::Hidden, cl::init(3500));
239db7fe6cdSJianzhou Zhao 
2407e658b2fSJianzhou Zhao // Controls how to track origins.
2417e658b2fSJianzhou Zhao // * 0: do not track origins.
2427e658b2fSJianzhou Zhao // * 1: track origins at memory store operations.
2437fdf2709SJianzhou Zhao // * 2: track origins at memory load and store operations.
2447fdf2709SJianzhou Zhao //      TODO: track callsites.
2457e658b2fSJianzhou Zhao static cl::opt<int> ClTrackOrigins("dfsan-track-origins",
2467e658b2fSJianzhou Zhao                                    cl::desc("Track origins of labels"),
2477e658b2fSJianzhou Zhao                                    cl::Hidden, cl::init(0));
2487e658b2fSJianzhou Zhao 
24904e79cf7STaewook Oh static cl::opt<bool> ClIgnorePersonalityRoutine(
25004e79cf7STaewook Oh     "dfsan-ignore-personality-routine",
25104e79cf7STaewook Oh     cl::desc("If a personality routine is marked uninstrumented from the ABI "
25204e79cf7STaewook Oh              "list, do not create a wrapper for it."),
25304e79cf7STaewook Oh     cl::Hidden, cl::init(false));
25404e79cf7STaewook Oh 
getGlobalTypeString(const GlobalValue & G)2556ff18b08SGeorge Balatsouras static StringRef getGlobalTypeString(const GlobalValue &G) {
256b7dd329fSAlexey Samsonov   // Types of GlobalVariables are always pointer types.
2575f6eaac6SManuel Jacob   Type *GType = G.getValueType();
258858d3855SEric Christopher   // For now we support excluding struct types only.
259b7dd329fSAlexey Samsonov   if (StructType *SGType = dyn_cast<StructType>(GType)) {
260b7dd329fSAlexey Samsonov     if (!SGType->isLiteral())
261b7dd329fSAlexey Samsonov       return SGType->getName();
262b7dd329fSAlexey Samsonov   }
263b7dd329fSAlexey Samsonov   return "<unknown type>";
264b7dd329fSAlexey Samsonov }
265b7dd329fSAlexey Samsonov 
266fce43576SEugene Zelenko namespace {
267fce43576SEugene Zelenko 
26845f6d552SAndrew Browne // Memory map parameters used in application-to-shadow address calculation.
26945f6d552SAndrew Browne // Offset = (Addr & ~AndMask) ^ XorMask
27045f6d552SAndrew Browne // Shadow = ShadowBase + Offset
27145f6d552SAndrew Browne // Origin = (OriginBase + Offset) & ~3ULL
27245f6d552SAndrew Browne struct MemoryMapParams {
27345f6d552SAndrew Browne   uint64_t AndMask;
27445f6d552SAndrew Browne   uint64_t XorMask;
27545f6d552SAndrew Browne   uint64_t ShadowBase;
27645f6d552SAndrew Browne   uint64_t OriginBase;
27745f6d552SAndrew Browne };
27845f6d552SAndrew Browne 
27945f6d552SAndrew Browne } // end anonymous namespace
28045f6d552SAndrew Browne 
28145f6d552SAndrew Browne // x86_64 Linux
28245f6d552SAndrew Browne // NOLINTNEXTLINE(readability-identifier-naming)
28345f6d552SAndrew Browne static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
28445f6d552SAndrew Browne     0,              // AndMask (not used)
28545f6d552SAndrew Browne     0x500000000000, // XorMask
28645f6d552SAndrew Browne     0,              // ShadowBase (not used)
28745f6d552SAndrew Browne     0x100000000000, // OriginBase
28845f6d552SAndrew Browne };
28945f6d552SAndrew Browne 
29045f6d552SAndrew Browne namespace {
29145f6d552SAndrew Browne 
292b7dd329fSAlexey Samsonov class DFSanABIList {
293b7dd329fSAlexey Samsonov   std::unique_ptr<SpecialCaseList> SCL;
294b7dd329fSAlexey Samsonov 
295b7dd329fSAlexey Samsonov public:
296fce43576SEugene Zelenko   DFSanABIList() = default;
297b9b8027cSAlexey Samsonov 
set(std::unique_ptr<SpecialCaseList> List)298b9b8027cSAlexey Samsonov   void set(std::unique_ptr<SpecialCaseList> List) { SCL = std::move(List); }
299b7dd329fSAlexey Samsonov 
300b7dd329fSAlexey Samsonov   /// Returns whether either this function or its source file are listed in the
301b7dd329fSAlexey Samsonov   /// given category.
isIn(const Function & F,StringRef Category) const3026dc4a8bcSCraig Topper   bool isIn(const Function &F, StringRef Category) const {
303b7dd329fSAlexey Samsonov     return isIn(*F.getParent(), Category) ||
304998b220eSVlad Tsyrklevich            SCL->inSection("dataflow", "fun", F.getName(), Category);
305b7dd329fSAlexey Samsonov   }
306b7dd329fSAlexey Samsonov 
307b7dd329fSAlexey Samsonov   /// Returns whether this global alias is listed in the given category.
308b7dd329fSAlexey Samsonov   ///
309b7dd329fSAlexey Samsonov   /// If GA aliases a function, the alias's name is matched as a function name
310b7dd329fSAlexey Samsonov   /// would be.  Similarly, aliases of globals are matched like globals.
isIn(const GlobalAlias & GA,StringRef Category) const3116dc4a8bcSCraig Topper   bool isIn(const GlobalAlias &GA, StringRef Category) const {
312b7dd329fSAlexey Samsonov     if (isIn(*GA.getParent(), Category))
313b7dd329fSAlexey Samsonov       return true;
314b7dd329fSAlexey Samsonov 
3155f6eaac6SManuel Jacob     if (isa<FunctionType>(GA.getValueType()))
316998b220eSVlad Tsyrklevich       return SCL->inSection("dataflow", "fun", GA.getName(), Category);
317b7dd329fSAlexey Samsonov 
318998b220eSVlad Tsyrklevich     return SCL->inSection("dataflow", "global", GA.getName(), Category) ||
3196ff18b08SGeorge Balatsouras            SCL->inSection("dataflow", "type", getGlobalTypeString(GA),
320998b220eSVlad Tsyrklevich                           Category);
321b7dd329fSAlexey Samsonov   }
322b7dd329fSAlexey Samsonov 
323b7dd329fSAlexey Samsonov   /// Returns whether this module is listed in the given category.
isIn(const Module & M,StringRef Category) const3246dc4a8bcSCraig Topper   bool isIn(const Module &M, StringRef Category) const {
325998b220eSVlad Tsyrklevich     return SCL->inSection("dataflow", "src", M.getModuleIdentifier(), Category);
326b7dd329fSAlexey Samsonov   }
327b7dd329fSAlexey Samsonov };
328b7dd329fSAlexey Samsonov 
32932f5405bSPeter Collingbourne /// TransformedFunction is used to express the result of transforming one
33032f5405bSPeter Collingbourne /// function type into another.  This struct is immutable.  It holds metadata
33132f5405bSPeter Collingbourne /// useful for updating calls of the old function to the new type.
33232f5405bSPeter Collingbourne struct TransformedFunction {
TransformedFunction__anonc1e0408c0211::TransformedFunction3336ff18b08SGeorge Balatsouras   TransformedFunction(FunctionType *OriginalType, FunctionType *TransformedType,
33432f5405bSPeter Collingbourne                       std::vector<unsigned> ArgumentIndexMapping)
3356ff18b08SGeorge Balatsouras       : OriginalType(OriginalType), TransformedType(TransformedType),
33632f5405bSPeter Collingbourne         ArgumentIndexMapping(ArgumentIndexMapping) {}
33732f5405bSPeter Collingbourne 
33832f5405bSPeter Collingbourne   // Disallow copies.
33932f5405bSPeter Collingbourne   TransformedFunction(const TransformedFunction &) = delete;
34032f5405bSPeter Collingbourne   TransformedFunction &operator=(const TransformedFunction &) = delete;
34132f5405bSPeter Collingbourne 
34232f5405bSPeter Collingbourne   // Allow moves.
34332f5405bSPeter Collingbourne   TransformedFunction(TransformedFunction &&) = default;
34432f5405bSPeter Collingbourne   TransformedFunction &operator=(TransformedFunction &&) = default;
34532f5405bSPeter Collingbourne 
34632f5405bSPeter Collingbourne   /// Type of the function before the transformation.
34705090708SVitaly Buka   FunctionType *OriginalType;
34832f5405bSPeter Collingbourne 
34932f5405bSPeter Collingbourne   /// Type of the function after the transformation.
35005090708SVitaly Buka   FunctionType *TransformedType;
35132f5405bSPeter Collingbourne 
35232f5405bSPeter Collingbourne   /// Transforming a function may change the position of arguments.  This
35332f5405bSPeter Collingbourne   /// member records the mapping from each argument's old position to its new
35432f5405bSPeter Collingbourne   /// position.  Argument positions are zero-indexed.  If the transformation
35532f5405bSPeter Collingbourne   /// from F to F' made the first argument of F into the third argument of F',
35632f5405bSPeter Collingbourne   /// then ArgumentIndexMapping[0] will equal 2.
35705090708SVitaly Buka   std::vector<unsigned> ArgumentIndexMapping;
35832f5405bSPeter Collingbourne };
35932f5405bSPeter Collingbourne 
36032f5405bSPeter Collingbourne /// Given function attributes from a call site for the original function,
36132f5405bSPeter Collingbourne /// return function attributes appropriate for a call to the transformed
36232f5405bSPeter Collingbourne /// function.
3636ff18b08SGeorge Balatsouras AttributeList
transformFunctionAttributes(const TransformedFunction & TransformedFunction,LLVMContext & Ctx,AttributeList CallSiteAttrs)3646ff18b08SGeorge Balatsouras transformFunctionAttributes(const TransformedFunction &TransformedFunction,
36532f5405bSPeter Collingbourne                             LLVMContext &Ctx, AttributeList CallSiteAttrs) {
36632f5405bSPeter Collingbourne 
36732f5405bSPeter Collingbourne   // Construct a vector of AttributeSet for each function argument.
36832f5405bSPeter Collingbourne   std::vector<llvm::AttributeSet> ArgumentAttributes(
36932f5405bSPeter Collingbourne       TransformedFunction.TransformedType->getNumParams());
37032f5405bSPeter Collingbourne 
37132f5405bSPeter Collingbourne   // Copy attributes from the parameter of the original function to the
37232f5405bSPeter Collingbourne   // transformed version.  'ArgumentIndexMapping' holds the mapping from
37332f5405bSPeter Collingbourne   // old argument position to new.
3746ff18b08SGeorge Balatsouras   for (unsigned I = 0, IE = TransformedFunction.ArgumentIndexMapping.size();
3756ff18b08SGeorge Balatsouras        I < IE; ++I) {
3766ff18b08SGeorge Balatsouras     unsigned TransformedIndex = TransformedFunction.ArgumentIndexMapping[I];
37780ea2bb5SArthur Eubanks     ArgumentAttributes[TransformedIndex] = CallSiteAttrs.getParamAttrs(I);
37832f5405bSPeter Collingbourne   }
37932f5405bSPeter Collingbourne 
38032f5405bSPeter Collingbourne   // Copy annotations on varargs arguments.
3816ff18b08SGeorge Balatsouras   for (unsigned I = TransformedFunction.OriginalType->getNumParams(),
3826ff18b08SGeorge Balatsouras                 IE = CallSiteAttrs.getNumAttrSets();
3836ff18b08SGeorge Balatsouras        I < IE; ++I) {
38480ea2bb5SArthur Eubanks     ArgumentAttributes.push_back(CallSiteAttrs.getParamAttrs(I));
38532f5405bSPeter Collingbourne   }
38632f5405bSPeter Collingbourne 
38780ea2bb5SArthur Eubanks   return AttributeList::get(Ctx, CallSiteAttrs.getFnAttrs(),
38880ea2bb5SArthur Eubanks                             CallSiteAttrs.getRetAttrs(),
38932f5405bSPeter Collingbourne                             llvm::makeArrayRef(ArgumentAttributes));
39032f5405bSPeter Collingbourne }
39132f5405bSPeter Collingbourne 
39271d0a2b8SArthur Eubanks class DataFlowSanitizer {
393e5d5b0c7SPeter Collingbourne   friend struct DFSanFunction;
394e5d5b0c7SPeter Collingbourne   friend class DFSanVisitor;
395e5d5b0c7SPeter Collingbourne 
3965b4dda55SGeorge Balatsouras   enum { ShadowWidthBits = 8, ShadowWidthBytes = ShadowWidthBits / 8 };
3975b4dda55SGeorge Balatsouras 
398e652d991SAndrew Browne   enum { OriginWidthBits = 32, OriginWidthBytes = OriginWidthBits / 8 };
399e5d5b0c7SPeter Collingbourne 
40068162e75SPeter Collingbourne   /// How should calls to uninstrumented functions be handled?
40168162e75SPeter Collingbourne   enum WrapperKind {
40268162e75SPeter Collingbourne     /// This function is present in an uninstrumented form but we don't know
40368162e75SPeter Collingbourne     /// how it should be handled.  Print a warning and call the function anyway.
40468162e75SPeter Collingbourne     /// Don't label the return value.
40568162e75SPeter Collingbourne     WK_Warning,
40668162e75SPeter Collingbourne 
40768162e75SPeter Collingbourne     /// This function does not write to (user-accessible) memory, and its return
40868162e75SPeter Collingbourne     /// value is unlabelled.
40968162e75SPeter Collingbourne     WK_Discard,
41068162e75SPeter Collingbourne 
41168162e75SPeter Collingbourne     /// This function does not write to (user-accessible) memory, and the label
41268162e75SPeter Collingbourne     /// of its return value is the union of the label of its arguments.
41368162e75SPeter Collingbourne     WK_Functional,
41468162e75SPeter Collingbourne 
41568162e75SPeter Collingbourne     /// Instead of calling the function, a custom wrapper __dfsw_F is called,
41668162e75SPeter Collingbourne     /// where F is the name of the function.  This function may wrap the
41761ec2148SAndrew Browne     /// original function or provide its own implementation. WK_Custom uses an
41868162e75SPeter Collingbourne     /// extra pointer argument to return the shadow.  This allows the wrapped
41968162e75SPeter Collingbourne     /// form of the function type to be expressed in C.
42068162e75SPeter Collingbourne     WK_Custom
42168162e75SPeter Collingbourne   };
42268162e75SPeter Collingbourne 
423e5d5b0c7SPeter Collingbourne   Module *Mod;
424e5d5b0c7SPeter Collingbourne   LLVMContext *Ctx;
42506c9b4aaSJianzhou Zhao   Type *Int8Ptr;
4267e658b2fSJianzhou Zhao   IntegerType *OriginTy;
4277e658b2fSJianzhou Zhao   PointerType *OriginPtrTy;
428dab953c8SJianzhou Zhao   ConstantInt *ZeroOrigin;
429ea981165SJianzhou Zhao   /// The shadow type for all primitive types and vector types.
430bd726d27SJianzhou Zhao   IntegerType *PrimitiveShadowTy;
431bd726d27SJianzhou Zhao   PointerType *PrimitiveShadowPtrTy;
432e5d5b0c7SPeter Collingbourne   IntegerType *IntptrTy;
433bd726d27SJianzhou Zhao   ConstantInt *ZeroPrimitiveShadow;
434e5d5b0c7SPeter Collingbourne   Constant *ArgTLS;
4357e658b2fSJianzhou Zhao   ArrayType *ArgOriginTLSTy;
4367e658b2fSJianzhou Zhao   Constant *ArgOriginTLS;
437e5d5b0c7SPeter Collingbourne   Constant *RetvalTLS;
4387e658b2fSJianzhou Zhao   Constant *RetvalOriginTLS;
439e5d5b0c7SPeter Collingbourne   FunctionType *DFSanUnionLoadFnTy;
4407e658b2fSJianzhou Zhao   FunctionType *DFSanLoadLabelAndOriginFnTy;
44168162e75SPeter Collingbourne   FunctionType *DFSanUnimplementedFnTy;
442204c12eeSAndrew Browne   FunctionType *DFSanWrapperExternWeakNullFnTy;
4439d31d6f3SPeter Collingbourne   FunctionType *DFSanSetLabelFnTy;
444444c59e2SPeter Collingbourne   FunctionType *DFSanNonzeroLabelFnTy;
445a1099840SPeter Collingbourne   FunctionType *DFSanVarargWrapperFnTy;
4464e173585SAndrew Browne   FunctionType *DFSanConditionalCallbackFnTy;
4474e173585SAndrew Browne   FunctionType *DFSanConditionalCallbackOriginFnTy;
44806c9b4aaSJianzhou Zhao   FunctionType *DFSanCmpCallbackFnTy;
44906c9b4aaSJianzhou Zhao   FunctionType *DFSanLoadStoreCallbackFnTy;
450f668baa4SMatt Morehouse   FunctionType *DFSanMemTransferCallbackFnTy;
4517e658b2fSJianzhou Zhao   FunctionType *DFSanChainOriginFnTy;
4527fdf2709SJianzhou Zhao   FunctionType *DFSanChainOriginIfTaintedFnTy;
4537e658b2fSJianzhou Zhao   FunctionType *DFSanMemOriginTransferFnTy;
4547e658b2fSJianzhou Zhao   FunctionType *DFSanMaybeStoreOriginFnTy;
45513680223SJames Y Knight   FunctionCallee DFSanUnionLoadFn;
4567e658b2fSJianzhou Zhao   FunctionCallee DFSanLoadLabelAndOriginFn;
45713680223SJames Y Knight   FunctionCallee DFSanUnimplementedFn;
458204c12eeSAndrew Browne   FunctionCallee DFSanWrapperExternWeakNullFn;
45913680223SJames Y Knight   FunctionCallee DFSanSetLabelFn;
46013680223SJames Y Knight   FunctionCallee DFSanNonzeroLabelFn;
46113680223SJames Y Knight   FunctionCallee DFSanVarargWrapperFn;
46252f889abSMatt Morehouse   FunctionCallee DFSanLoadCallbackFn;
463470db54cSMatt Morehouse   FunctionCallee DFSanStoreCallbackFn;
464f668baa4SMatt Morehouse   FunctionCallee DFSanMemTransferCallbackFn;
4654e173585SAndrew Browne   FunctionCallee DFSanConditionalCallbackFn;
4664e173585SAndrew Browne   FunctionCallee DFSanConditionalCallbackOriginFn;
46730bb737aSMatt Morehouse   FunctionCallee DFSanCmpCallbackFn;
4687e658b2fSJianzhou Zhao   FunctionCallee DFSanChainOriginFn;
4697fdf2709SJianzhou Zhao   FunctionCallee DFSanChainOriginIfTaintedFn;
4707e658b2fSJianzhou Zhao   FunctionCallee DFSanMemOriginTransferFn;
4717e658b2fSJianzhou Zhao   FunctionCallee DFSanMaybeStoreOriginFn;
4727e658b2fSJianzhou Zhao   SmallPtrSet<Value *, 16> DFSanRuntimeFunctions;
473e5d5b0c7SPeter Collingbourne   MDNode *ColdCallWeights;
474db7fe6cdSJianzhou Zhao   MDNode *OriginStoreWeights;
475b7dd329fSAlexey Samsonov   DFSanABIList ABIList;
476e5d5b0c7SPeter Collingbourne   DenseMap<Value *, Function *> UnwrappedFnMap;
4779290ccc3Sserge-sans-paille   AttributeMask ReadOnlyNoneAttrs;
4785748219fSAndrew Browne   StringSet<> CombineTaintLookupTableNames;
479e5d5b0c7SPeter Collingbourne 
48045f6d552SAndrew Browne   /// Memory map parameters used in calculation mapping application addresses
48145f6d552SAndrew Browne   /// to shadow addresses and origin addresses.
48245f6d552SAndrew Browne   const MemoryMapParams *MapParams;
48345f6d552SAndrew Browne 
484cb1f1aabSJianzhou Zhao   Value *getShadowOffset(Value *Addr, IRBuilder<> &IRB);
485e5d5b0c7SPeter Collingbourne   Value *getShadowAddress(Value *Addr, Instruction *Pos);
486d10f173fSGeorge Balatsouras   Value *getShadowAddress(Value *Addr, Instruction *Pos, Value *ShadowOffset);
487d866b9c9SJianzhou Zhao   std::pair<Value *, Value *>
488d866b9c9SJianzhou Zhao   getShadowOriginAddress(Value *Addr, Align InstAlignment, Instruction *Pos);
48959b1262dSPeter Collingbourne   bool isInstrumented(const Function *F);
49059b1262dSPeter Collingbourne   bool isInstrumented(const GlobalAlias *GA);
491c533b88aSAndrew Browne   bool isForceZeroLabels(const Function *F);
49232f5405bSPeter Collingbourne   TransformedFunction getCustomFunctionType(FunctionType *T);
49368162e75SPeter Collingbourne   WrapperKind getWrapperKind(Function *F);
494c6b5a25eSGeorge Balatsouras   void addGlobalNameSuffix(GlobalValue *GV);
495204c12eeSAndrew Browne   void buildExternWeakCheckIfNeeded(IRBuilder<> &IRB, Function *F);
496761a4fc4SPeter Collingbourne   Function *buildWrapperFunction(Function *F, StringRef NewFName,
497761a4fc4SPeter Collingbourne                                  GlobalValue::LinkageTypes NewFLink,
498761a4fc4SPeter Collingbourne                                  FunctionType *NewFT);
4998d8fda49SZola Bridges   void initializeCallbackFunctions(Module &M);
5008d8fda49SZola Bridges   void initializeRuntimeFunctions(Module &M);
501c9075a1cSGeorge Balatsouras   void injectMetadataGlobals(Module &M);
50245f6d552SAndrew Browne   bool initializeModule(Module &M);
50371d0a2b8SArthur Eubanks 
504a45fd436SGeorge Balatsouras   /// Advances \p OriginAddr to point to the next 32-bit origin and then loads
505a45fd436SGeorge Balatsouras   /// from it. Returns the origin's loaded value.
506a45fd436SGeorge Balatsouras   Value *loadNextOrigin(Instruction *Pos, Align OriginAlign,
507a45fd436SGeorge Balatsouras                         Value **OriginAddr);
508a45fd436SGeorge Balatsouras 
50979b5280aSGeorge Balatsouras   /// Returns whether the given load byte size is amenable to inlined
51079b5280aSGeorge Balatsouras   /// optimization patterns.
51179b5280aSGeorge Balatsouras   bool hasLoadSizeForFastPath(uint64_t Size);
51279b5280aSGeorge Balatsouras 
5135b4dda55SGeorge Balatsouras   /// Returns whether the pass tracks origins. Supports only TLS ABI mode.
5147e658b2fSJianzhou Zhao   bool shouldTrackOrigins();
5157e658b2fSJianzhou Zhao 
516ea981165SJianzhou Zhao   /// Returns a zero constant with the shadow type of OrigTy.
517ea981165SJianzhou Zhao   ///
518ea981165SJianzhou Zhao   /// getZeroShadow({T1,T2,...}) = {getZeroShadow(T1),getZeroShadow(T2,...}
519ea981165SJianzhou Zhao   /// getZeroShadow([n x T]) = [n x getZeroShadow(T)]
520ea981165SJianzhou Zhao   /// getZeroShadow(other type) = i16(0)
521ea981165SJianzhou Zhao   Constant *getZeroShadow(Type *OrigTy);
522ea981165SJianzhou Zhao   /// Returns a zero constant with the shadow type of V's type.
523a28db8b2SJianzhou Zhao   Constant *getZeroShadow(Value *V);
524ea981165SJianzhou Zhao 
525a28db8b2SJianzhou Zhao   /// Checks if V is a zero shadow.
526a28db8b2SJianzhou Zhao   bool isZeroShadow(Value *V);
527ea981165SJianzhou Zhao 
528a28db8b2SJianzhou Zhao   /// Returns the shadow type of OrigTy.
529ea981165SJianzhou Zhao   ///
530ea981165SJianzhou Zhao   /// getShadowTy({T1,T2,...}) = {getShadowTy(T1),getShadowTy(T2),...}
531ea981165SJianzhou Zhao   /// getShadowTy([n x T]) = [n x getShadowTy(T)]
532ea981165SJianzhou Zhao   /// getShadowTy(other type) = i16
533a28db8b2SJianzhou Zhao   Type *getShadowTy(Type *OrigTy);
534a28db8b2SJianzhou Zhao   /// Returns the shadow type of of V's type.
535a28db8b2SJianzhou Zhao   Type *getShadowTy(Value *V);
536a28db8b2SJianzhou Zhao 
5376ff18b08SGeorge Balatsouras   const uint64_t NumOfElementsInArgOrgTLS = ArgTLSSize / OriginWidthBytes;
5387e658b2fSJianzhou Zhao 
539e5d5b0c7SPeter Collingbourne public:
54071d0a2b8SArthur Eubanks   DataFlowSanitizer(const std::vector<std::string> &ABIListFiles);
541fce43576SEugene Zelenko 
54271d0a2b8SArthur Eubanks   bool runImpl(Module &M);
543e5d5b0c7SPeter Collingbourne };
544e5d5b0c7SPeter Collingbourne 
545e5d5b0c7SPeter Collingbourne struct DFSanFunction {
546e5d5b0c7SPeter Collingbourne   DataFlowSanitizer &DFS;
547e5d5b0c7SPeter Collingbourne   Function *F;
548705a1ae3SPeter Collingbourne   DominatorTree DT;
54968162e75SPeter Collingbourne   bool IsNativeABI;
550c533b88aSAndrew Browne   bool IsForceZeroLabels;
551fce43576SEugene Zelenko   AllocaInst *LabelReturnAlloca = nullptr;
552a47d435bSJianzhou Zhao   AllocaInst *OriginReturnAlloca = nullptr;
553e5d5b0c7SPeter Collingbourne   DenseMap<Value *, Value *> ValShadowMap;
554dab953c8SJianzhou Zhao   DenseMap<Value *, Value *> ValOriginMap;
555e5d5b0c7SPeter Collingbourne   DenseMap<AllocaInst *, AllocaInst *> AllocaShadowMap;
556d866b9c9SJianzhou Zhao   DenseMap<AllocaInst *, AllocaInst *> AllocaOriginMap;
557d866b9c9SJianzhou Zhao 
5586a9a686cSJianzhou Zhao   struct PHIFixupElement {
5596a9a686cSJianzhou Zhao     PHINode *Phi;
5606a9a686cSJianzhou Zhao     PHINode *ShadowPhi;
5616a9a686cSJianzhou Zhao     PHINode *OriginPhi;
5626a9a686cSJianzhou Zhao   };
5636a9a686cSJianzhou Zhao   std::vector<PHIFixupElement> PHIFixups;
5646a9a686cSJianzhou Zhao 
565e5d5b0c7SPeter Collingbourne   DenseSet<Instruction *> SkipInsts;
566fab565a5SPeter Collingbourne   std::vector<Value *> NonZeroChecks;
567e5d5b0c7SPeter Collingbourne 
568dad5d958SJianzhou Zhao   struct CachedShadow {
569dad5d958SJianzhou Zhao     BasicBlock *Block; // The block where Shadow is defined.
570705a1ae3SPeter Collingbourne     Value *Shadow;
571705a1ae3SPeter Collingbourne   };
572dad5d958SJianzhou Zhao   /// Maps a value to its latest shadow value in terms of domination tree.
573dad5d958SJianzhou Zhao   DenseMap<std::pair<Value *, Value *>, CachedShadow> CachedShadows;
574ea981165SJianzhou Zhao   /// Maps a value to its latest collapsed shadow value it was converted to in
575ea981165SJianzhou Zhao   /// terms of domination tree. When ClDebugNonzeroLabels is on, this cache is
576ea981165SJianzhou Zhao   /// used at a post process where CFG blocks are split. So it does not cache
577ea981165SJianzhou Zhao   /// BasicBlock like CachedShadows, but uses domination between values.
578ea981165SJianzhou Zhao   DenseMap<Value *, Value *> CachedCollapsedShadows;
5799947c498SPeter Collingbourne   DenseMap<Value *, std::set<Value *>> ShadowElements;
580705a1ae3SPeter Collingbourne 
DFSanFunction__anonc1e0408c0211::DFSanFunction581c533b88aSAndrew Browne   DFSanFunction(DataFlowSanitizer &DFS, Function *F, bool IsNativeABI,
582c533b88aSAndrew Browne                 bool IsForceZeroLabels)
58361ec2148SAndrew Browne       : DFS(DFS), F(F), IsNativeABI(IsNativeABI),
584c533b88aSAndrew Browne         IsForceZeroLabels(IsForceZeroLabels) {
585705a1ae3SPeter Collingbourne     DT.recalculate(*F);
586705a1ae3SPeter Collingbourne   }
587fce43576SEugene Zelenko 
58880e326a8SJianzhou Zhao   /// Computes the shadow address for a given function argument.
58980e326a8SJianzhou Zhao   ///
59080e326a8SJianzhou Zhao   /// Shadow = ArgTLS+ArgOffset.
591a28db8b2SJianzhou Zhao   Value *getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB);
59280e326a8SJianzhou Zhao 
593dab953c8SJianzhou Zhao   /// Computes the shadow address for a return value.
594a28db8b2SJianzhou Zhao   Value *getRetvalTLS(Type *T, IRBuilder<> &IRB);
59580e326a8SJianzhou Zhao 
596dab953c8SJianzhou Zhao   /// Computes the origin address for a given function argument.
597dab953c8SJianzhou Zhao   ///
598dab953c8SJianzhou Zhao   /// Origin = ArgOriginTLS[ArgNo].
5997424efd5SJianzhou Zhao   Value *getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB);
600dab953c8SJianzhou Zhao 
601dab953c8SJianzhou Zhao   /// Computes the origin address for a return value.
6027424efd5SJianzhou Zhao   Value *getRetvalOriginTLS();
603dab953c8SJianzhou Zhao 
6047424efd5SJianzhou Zhao   Value *getOrigin(Value *V);
6057424efd5SJianzhou Zhao   void setOrigin(Instruction *I, Value *Origin);
6067424efd5SJianzhou Zhao   /// Generates IR to compute the origin of the last operand with a taint label.
6077424efd5SJianzhou Zhao   Value *combineOperandOrigins(Instruction *Inst);
6087424efd5SJianzhou Zhao   /// Before the instruction Pos, generates IR to compute the last origin with a
6097424efd5SJianzhou Zhao   /// taint label. Labels and origins are from vectors Shadows and Origins
6107424efd5SJianzhou Zhao   /// correspondingly. The generated IR is like
6117424efd5SJianzhou Zhao   ///   Sn-1 != Zero ? On-1: ... S2 != Zero ? O2: S1 != Zero ? O1: O0
6127424efd5SJianzhou Zhao   /// When Zero is nullptr, it uses ZeroPrimitiveShadow. Otherwise it can be
6137424efd5SJianzhou Zhao   /// zeros with other bitwidths.
6147424efd5SJianzhou Zhao   Value *combineOrigins(const std::vector<Value *> &Shadows,
6157424efd5SJianzhou Zhao                         const std::vector<Value *> &Origins, Instruction *Pos,
6167424efd5SJianzhou Zhao                         ConstantInt *Zero = nullptr);
6177424efd5SJianzhou Zhao 
618e5d5b0c7SPeter Collingbourne   Value *getShadow(Value *V);
619e5d5b0c7SPeter Collingbourne   void setShadow(Instruction *I, Value *Shadow);
620ea981165SJianzhou Zhao   /// Generates IR to compute the union of the two given shadows, inserting it
621ea981165SJianzhou Zhao   /// before Pos. The combined value is with primitive type.
62283def1cbSPeter Collingbourne   Value *combineShadows(Value *V1, Value *V2, Instruction *Pos);
623ea981165SJianzhou Zhao   /// Combines the shadow values of V1 and V2, then converts the combined value
624ea981165SJianzhou Zhao   /// with primitive type into a shadow value with the original type T.
625ea981165SJianzhou Zhao   Value *combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
626ea981165SJianzhou Zhao                                    Instruction *Pos);
627e5d5b0c7SPeter Collingbourne   Value *combineOperandShadows(Instruction *Inst);
6287fdf2709SJianzhou Zhao 
6297fdf2709SJianzhou Zhao   /// Generates IR to load shadow and origin corresponding to bytes [\p
6307fdf2709SJianzhou Zhao   /// Addr, \p Addr + \p Size), where addr has alignment \p
6317fdf2709SJianzhou Zhao   /// InstAlignment, and take the union of each of those shadows. The returned
6327fdf2709SJianzhou Zhao   /// shadow always has primitive type.
6337fdf2709SJianzhou Zhao   ///
6347fdf2709SJianzhou Zhao   /// When tracking loads is enabled, the returned origin is a chain at the
6357fdf2709SJianzhou Zhao   /// current stack if the returned shadow is tainted.
6367fdf2709SJianzhou Zhao   std::pair<Value *, Value *> loadShadowOrigin(Value *Addr, uint64_t Size,
637d866b9c9SJianzhou Zhao                                                Align InstAlignment,
638e5d5b0c7SPeter Collingbourne                                                Instruction *Pos);
6397fdf2709SJianzhou Zhao 
640db7fe6cdSJianzhou Zhao   void storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
641db7fe6cdSJianzhou Zhao                                   Align InstAlignment, Value *PrimitiveShadow,
642db7fe6cdSJianzhou Zhao                                   Value *Origin, Instruction *Pos);
643ea981165SJianzhou Zhao   /// Applies PrimitiveShadow to all primitive subtypes of T, returning
644ea981165SJianzhou Zhao   /// the expanded shadow value.
645ea981165SJianzhou Zhao   ///
646ea981165SJianzhou Zhao   /// EFP({T1,T2, ...}, PS) = {EFP(T1,PS),EFP(T2,PS),...}
647ea981165SJianzhou Zhao   /// EFP([n x T], PS) = [n x EFP(T,PS)]
648ea981165SJianzhou Zhao   /// EFP(other types, PS) = PS
649ea981165SJianzhou Zhao   Value *expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
650e5d5b0c7SPeter Collingbourne                                    Instruction *Pos);
651ea981165SJianzhou Zhao   /// Collapses Shadow into a single primitive shadow value, unioning all
652ea981165SJianzhou Zhao   /// primitive shadow values in the process. Returns the final primitive
653ea981165SJianzhou Zhao   /// shadow value.
654ea981165SJianzhou Zhao   ///
655ea981165SJianzhou Zhao   /// CTP({V1,V2, ...}) = UNION(CFP(V1,PS),CFP(V2,PS),...)
656ea981165SJianzhou Zhao   /// CTP([V1,V2,...]) = UNION(CFP(V1,PS),CFP(V2,PS),...)
657ea981165SJianzhou Zhao   /// CTP(other types, PS) = PS
658ea981165SJianzhou Zhao   Value *collapseToPrimitiveShadow(Value *Shadow, Instruction *Pos);
65980e326a8SJianzhou Zhao 
660c88fedefSJianzhou Zhao   void storeZeroPrimitiveShadow(Value *Addr, uint64_t Size, Align ShadowAlign,
661c88fedefSJianzhou Zhao                                 Instruction *Pos);
662c88fedefSJianzhou Zhao 
663c88fedefSJianzhou Zhao   Align getShadowAlign(Align InstAlignment);
664c88fedefSJianzhou Zhao 
6654e173585SAndrew Browne   // If ClConditionalCallbacks is enabled, insert a callback after a given
6664e173585SAndrew Browne   // branch instruction using the given conditional expression.
6674e173585SAndrew Browne   void addConditionalCallbacksIfEnabled(Instruction &I, Value *Condition);
6684e173585SAndrew Browne 
6695748219fSAndrew Browne   bool isLookupTableConstant(Value *P);
6705748219fSAndrew Browne 
67180e326a8SJianzhou Zhao private:
672ea981165SJianzhou Zhao   /// Collapses the shadow with aggregate type into a single primitive shadow
673ea981165SJianzhou Zhao   /// value.
674ea981165SJianzhou Zhao   template <class AggregateType>
675ea981165SJianzhou Zhao   Value *collapseAggregateShadow(AggregateType *AT, Value *Shadow,
676ea981165SJianzhou Zhao                                  IRBuilder<> &IRB);
677ea981165SJianzhou Zhao 
678ea981165SJianzhou Zhao   Value *collapseToPrimitiveShadow(Value *Shadow, IRBuilder<> &IRB);
679ea981165SJianzhou Zhao 
68080e326a8SJianzhou Zhao   /// Returns the shadow value of an argument A.
68180e326a8SJianzhou Zhao   Value *getShadowForTLSArgument(Argument *A);
6829887fdebSJianzhou Zhao 
6835b4dda55SGeorge Balatsouras   /// The fast path of loading shadows.
684d866b9c9SJianzhou Zhao   std::pair<Value *, Value *>
6855b4dda55SGeorge Balatsouras   loadShadowFast(Value *ShadowAddr, Value *OriginAddr, uint64_t Size,
686d866b9c9SJianzhou Zhao                  Align ShadowAlign, Align OriginAlign, Value *FirstOrigin,
687d866b9c9SJianzhou Zhao                  Instruction *Pos);
688d866b9c9SJianzhou Zhao 
689d866b9c9SJianzhou Zhao   Align getOriginAlign(Align InstAlignment);
690d866b9c9SJianzhou Zhao 
691d866b9c9SJianzhou Zhao   /// Because 4 contiguous bytes share one 4-byte origin, the most accurate load
692d866b9c9SJianzhou Zhao   /// is __dfsan_load_label_and_origin. This function returns the union of all
693d866b9c9SJianzhou Zhao   /// labels and the origin of the first taint label. However this is an
694d866b9c9SJianzhou Zhao   /// additional call with many instructions. To ensure common cases are fast,
695d866b9c9SJianzhou Zhao   /// checks if it is possible to load labels and origins without using the
696d866b9c9SJianzhou Zhao   /// callback function.
6977fdf2709SJianzhou Zhao   ///
6987fdf2709SJianzhou Zhao   /// When enabling tracking load instructions, we always use
6997fdf2709SJianzhou Zhao   /// __dfsan_load_label_and_origin to reduce code size.
700d866b9c9SJianzhou Zhao   bool useCallbackLoadLabelAndOrigin(uint64_t Size, Align InstAlignment);
701db7fe6cdSJianzhou Zhao 
702db7fe6cdSJianzhou Zhao   /// Returns a chain at the current stack with previous origin V.
703db7fe6cdSJianzhou Zhao   Value *updateOrigin(Value *V, IRBuilder<> &IRB);
704db7fe6cdSJianzhou Zhao 
7057fdf2709SJianzhou Zhao   /// Returns a chain at the current stack with previous origin V if Shadow is
7067fdf2709SJianzhou Zhao   /// tainted.
7077fdf2709SJianzhou Zhao   Value *updateOriginIfTainted(Value *Shadow, Value *Origin, IRBuilder<> &IRB);
7087fdf2709SJianzhou Zhao 
709db7fe6cdSJianzhou Zhao   /// Creates an Intptr = Origin | Origin << 32 if Intptr's size is 64. Returns
710db7fe6cdSJianzhou Zhao   /// Origin otherwise.
711db7fe6cdSJianzhou Zhao   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin);
712db7fe6cdSJianzhou Zhao 
713db7fe6cdSJianzhou Zhao   /// Stores Origin into the address range [StoreOriginAddr, StoreOriginAddr +
714db7fe6cdSJianzhou Zhao   /// Size).
715db7fe6cdSJianzhou Zhao   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *StoreOriginAddr,
716db7fe6cdSJianzhou Zhao                    uint64_t StoreOriginSize, Align Alignment);
717db7fe6cdSJianzhou Zhao 
718db7fe6cdSJianzhou Zhao   /// Stores Origin in terms of its Shadow value.
719db7fe6cdSJianzhou Zhao   /// * Do not write origins for zero shadows because we do not trace origins
720db7fe6cdSJianzhou Zhao   ///   for untainted sinks.
721db7fe6cdSJianzhou Zhao   /// * Use __dfsan_maybe_store_origin if there are too many origin store
722db7fe6cdSJianzhou Zhao   ///   instrumentations.
723db7fe6cdSJianzhou Zhao   void storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size, Value *Shadow,
724db7fe6cdSJianzhou Zhao                    Value *Origin, Value *StoreOriginAddr, Align InstAlignment);
725db7fe6cdSJianzhou Zhao 
726db7fe6cdSJianzhou Zhao   /// Convert a scalar value to an i1 by comparing with 0.
727db7fe6cdSJianzhou Zhao   Value *convertToBool(Value *V, IRBuilder<> &IRB, const Twine &Name = "");
728db7fe6cdSJianzhou Zhao 
729db7fe6cdSJianzhou Zhao   bool shouldInstrumentWithCall();
730db7fe6cdSJianzhou Zhao 
7317fdf2709SJianzhou Zhao   /// Generates IR to load shadow and origin corresponding to bytes [\p
7327fdf2709SJianzhou Zhao   /// Addr, \p Addr + \p Size), where addr has alignment \p
7337fdf2709SJianzhou Zhao   /// InstAlignment, and take the union of each of those shadows. The returned
7347fdf2709SJianzhou Zhao   /// shadow always has primitive type.
7357fdf2709SJianzhou Zhao   std::pair<Value *, Value *>
7367fdf2709SJianzhou Zhao   loadShadowOriginSansLoadTracking(Value *Addr, uint64_t Size,
7377fdf2709SJianzhou Zhao                                    Align InstAlignment, Instruction *Pos);
738db7fe6cdSJianzhou Zhao   int NumOriginStores = 0;
739e5d5b0c7SPeter Collingbourne };
740e5d5b0c7SPeter Collingbourne 
741e5d5b0c7SPeter Collingbourne class DFSanVisitor : public InstVisitor<DFSanVisitor> {
742e5d5b0c7SPeter Collingbourne public:
743e5d5b0c7SPeter Collingbourne   DFSanFunction &DFSF;
744fce43576SEugene Zelenko 
DFSanVisitor(DFSanFunction & DFSF)745e5d5b0c7SPeter Collingbourne   DFSanVisitor(DFSanFunction &DFSF) : DFSF(DFSF) {}
746e5d5b0c7SPeter Collingbourne 
getDataLayout() const7473c1fc768SMatt Arsenault   const DataLayout &getDataLayout() const {
7483c1fc768SMatt Arsenault     return DFSF.F->getParent()->getDataLayout();
7493c1fc768SMatt Arsenault   }
7503c1fc768SMatt Arsenault 
7517424efd5SJianzhou Zhao   // Combines shadow values and origins for all of I's operands.
7527424efd5SJianzhou Zhao   void visitInstOperands(Instruction &I);
75330bb737aSMatt Morehouse 
7547aa898e6SCameron McInally   void visitUnaryOperator(UnaryOperator &UO);
755e5d5b0c7SPeter Collingbourne   void visitBinaryOperator(BinaryOperator &BO);
75670804f2aSAndrew Browne   void visitBitCastInst(BitCastInst &BCI);
757e5d5b0c7SPeter Collingbourne   void visitCastInst(CastInst &CI);
758e5d5b0c7SPeter Collingbourne   void visitCmpInst(CmpInst &CI);
759af931576SAndrew Browne   void visitLandingPadInst(LandingPadInst &LPI);
760e5d5b0c7SPeter Collingbourne   void visitGetElementPtrInst(GetElementPtrInst &GEPI);
761e5d5b0c7SPeter Collingbourne   void visitLoadInst(LoadInst &LI);
762e5d5b0c7SPeter Collingbourne   void visitStoreInst(StoreInst &SI);
763c88fedefSJianzhou Zhao   void visitAtomicRMWInst(AtomicRMWInst &I);
764c88fedefSJianzhou Zhao   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
765e5d5b0c7SPeter Collingbourne   void visitReturnInst(ReturnInst &RI);
7666235951eSCraig Topper   void visitCallBase(CallBase &CB);
767e5d5b0c7SPeter Collingbourne   void visitPHINode(PHINode &PN);
768e5d5b0c7SPeter Collingbourne   void visitExtractElementInst(ExtractElementInst &I);
769e5d5b0c7SPeter Collingbourne   void visitInsertElementInst(InsertElementInst &I);
770e5d5b0c7SPeter Collingbourne   void visitShuffleVectorInst(ShuffleVectorInst &I);
771e5d5b0c7SPeter Collingbourne   void visitExtractValueInst(ExtractValueInst &I);
772e5d5b0c7SPeter Collingbourne   void visitInsertValueInst(InsertValueInst &I);
773e5d5b0c7SPeter Collingbourne   void visitAllocaInst(AllocaInst &I);
774e5d5b0c7SPeter Collingbourne   void visitSelectInst(SelectInst &I);
7759d31d6f3SPeter Collingbourne   void visitMemSetInst(MemSetInst &I);
776e5d5b0c7SPeter Collingbourne   void visitMemTransferInst(MemTransferInst &I);
7774e173585SAndrew Browne   void visitBranchInst(BranchInst &BR);
7784e173585SAndrew Browne   void visitSwitchInst(SwitchInst &SW);
77964b448b9SJianzhou Zhao 
78064b448b9SJianzhou Zhao private:
781c88fedefSJianzhou Zhao   void visitCASOrRMW(Align InstAlignment, Instruction &I);
782c88fedefSJianzhou Zhao 
78364b448b9SJianzhou Zhao   // Returns false when this is an invoke of a custom function.
78464b448b9SJianzhou Zhao   bool visitWrappedCallBase(Function &F, CallBase &CB);
7857424efd5SJianzhou Zhao 
7867424efd5SJianzhou Zhao   // Combines origins for all of I's operands.
7877424efd5SJianzhou Zhao   void visitInstOperandOrigins(Instruction &I);
788a47d435bSJianzhou Zhao 
789a47d435bSJianzhou Zhao   void addShadowArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
790a47d435bSJianzhou Zhao                           IRBuilder<> &IRB);
791a47d435bSJianzhou Zhao 
792a47d435bSJianzhou Zhao   void addOriginArguments(Function &F, CallBase &CB, std::vector<Value *> &Args,
793a47d435bSJianzhou Zhao                           IRBuilder<> &IRB);
794e5d5b0c7SPeter Collingbourne };
795e5d5b0c7SPeter Collingbourne 
796fce43576SEugene Zelenko } // end anonymous namespace
797e5d5b0c7SPeter Collingbourne 
DataFlowSanitizer(const std::vector<std::string> & ABIListFiles)798b9b8027cSAlexey Samsonov DataFlowSanitizer::DataFlowSanitizer(
79971d0a2b8SArthur Eubanks     const std::vector<std::string> &ABIListFiles) {
800b9b8027cSAlexey Samsonov   std::vector<std::string> AllABIListFiles(std::move(ABIListFiles));
8018299fb8fSKazu Hirata   llvm::append_range(AllABIListFiles, ClABIListFiles);
802aa981c18SIlya Biryukov   // FIXME: should we propagate vfs::FileSystem to this constructor?
803aa981c18SIlya Biryukov   ABIList.set(
804aa981c18SIlya Biryukov       SpecialCaseList::createOrDie(AllABIListFiles, *vfs::getRealFileSystem()));
8055748219fSAndrew Browne 
8065748219fSAndrew Browne   for (StringRef v : ClCombineTaintLookupTables)
8075748219fSAndrew Browne     CombineTaintLookupTableNames.insert(v);
80868162e75SPeter Collingbourne }
809e5d5b0c7SPeter Collingbourne 
getCustomFunctionType(FunctionType * T)81032f5405bSPeter Collingbourne TransformedFunction DataFlowSanitizer::getCustomFunctionType(FunctionType *T) {
811fce43576SEugene Zelenko   SmallVector<Type *, 4> ArgTypes;
81232f5405bSPeter Collingbourne 
81332f5405bSPeter Collingbourne   // Some parameters of the custom function being constructed are
81432f5405bSPeter Collingbourne   // parameters of T.  Record the mapping from parameters of T to
81532f5405bSPeter Collingbourne   // parameters of the custom function, so that parameter attributes
81632f5405bSPeter Collingbourne   // at call sites can be updated.
81732f5405bSPeter Collingbourne   std::vector<unsigned> ArgumentIndexMapping;
818a47d435bSJianzhou Zhao   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I) {
8196ff18b08SGeorge Balatsouras     Type *ParamType = T->getParamType(I);
82032f5405bSPeter Collingbourne     ArgumentIndexMapping.push_back(ArgTypes.size());
8216ff18b08SGeorge Balatsouras     ArgTypes.push_back(ParamType);
82228a10affSPeter Collingbourne   }
823a47d435bSJianzhou Zhao   for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
824bd726d27SJianzhou Zhao     ArgTypes.push_back(PrimitiveShadowTy);
825dd3486ecSPeter Collingbourne   if (T->isVarArg())
826bd726d27SJianzhou Zhao     ArgTypes.push_back(PrimitiveShadowPtrTy);
82768162e75SPeter Collingbourne   Type *RetType = T->getReturnType();
82868162e75SPeter Collingbourne   if (!RetType->isVoidTy())
829bd726d27SJianzhou Zhao     ArgTypes.push_back(PrimitiveShadowPtrTy);
830a47d435bSJianzhou Zhao 
831a47d435bSJianzhou Zhao   if (shouldTrackOrigins()) {
832a47d435bSJianzhou Zhao     for (unsigned I = 0, E = T->getNumParams(); I != E; ++I)
833a47d435bSJianzhou Zhao       ArgTypes.push_back(OriginTy);
834a47d435bSJianzhou Zhao     if (T->isVarArg())
835a47d435bSJianzhou Zhao       ArgTypes.push_back(OriginPtrTy);
836a47d435bSJianzhou Zhao     if (!RetType->isVoidTy())
837a47d435bSJianzhou Zhao       ArgTypes.push_back(OriginPtrTy);
838a47d435bSJianzhou Zhao   }
839a47d435bSJianzhou Zhao 
84032f5405bSPeter Collingbourne   return TransformedFunction(
84132f5405bSPeter Collingbourne       T, FunctionType::get(T->getReturnType(), ArgTypes, T->isVarArg()),
84232f5405bSPeter Collingbourne       ArgumentIndexMapping);
84368162e75SPeter Collingbourne }
84468162e75SPeter Collingbourne 
isZeroShadow(Value * V)845a28db8b2SJianzhou Zhao bool DataFlowSanitizer::isZeroShadow(Value *V) {
846ea981165SJianzhou Zhao   Type *T = V->getType();
847ea981165SJianzhou Zhao   if (!isa<ArrayType>(T) && !isa<StructType>(T)) {
848ea981165SJianzhou Zhao     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
849ea981165SJianzhou Zhao       return CI->isZero();
850ea981165SJianzhou Zhao     return false;
851ea981165SJianzhou Zhao   }
852ea981165SJianzhou Zhao 
853ea981165SJianzhou Zhao   return isa<ConstantAggregateZero>(V);
854ea981165SJianzhou Zhao }
855ea981165SJianzhou Zhao 
hasLoadSizeForFastPath(uint64_t Size)85679b5280aSGeorge Balatsouras bool DataFlowSanitizer::hasLoadSizeForFastPath(uint64_t Size) {
85779b5280aSGeorge Balatsouras   uint64_t ShadowSize = Size * ShadowWidthBytes;
85879b5280aSGeorge Balatsouras   return ShadowSize % 8 == 0 || ShadowSize == 4;
85979b5280aSGeorge Balatsouras }
86079b5280aSGeorge Balatsouras 
shouldTrackOrigins()8617e658b2fSJianzhou Zhao bool DataFlowSanitizer::shouldTrackOrigins() {
86261ec2148SAndrew Browne   static const bool ShouldTrackOrigins = ClTrackOrigins;
8636ff18b08SGeorge Balatsouras   return ShouldTrackOrigins;
8647e658b2fSJianzhou Zhao }
8657e658b2fSJianzhou Zhao 
getZeroShadow(Type * OrigTy)866ea981165SJianzhou Zhao Constant *DataFlowSanitizer::getZeroShadow(Type *OrigTy) {
867ea981165SJianzhou Zhao   if (!isa<ArrayType>(OrigTy) && !isa<StructType>(OrigTy))
868ea981165SJianzhou Zhao     return ZeroPrimitiveShadow;
869ea981165SJianzhou Zhao   Type *ShadowTy = getShadowTy(OrigTy);
870ea981165SJianzhou Zhao   return ConstantAggregateZero::get(ShadowTy);
871a28db8b2SJianzhou Zhao }
872a28db8b2SJianzhou Zhao 
getZeroShadow(Value * V)873a28db8b2SJianzhou Zhao Constant *DataFlowSanitizer::getZeroShadow(Value *V) {
874ea981165SJianzhou Zhao   return getZeroShadow(V->getType());
875a28db8b2SJianzhou Zhao }
876a28db8b2SJianzhou Zhao 
expandFromPrimitiveShadowRecursive(Value * Shadow,SmallVector<unsigned,4> & Indices,Type * SubShadowTy,Value * PrimitiveShadow,IRBuilder<> & IRB)877ea981165SJianzhou Zhao static Value *expandFromPrimitiveShadowRecursive(
878ea981165SJianzhou Zhao     Value *Shadow, SmallVector<unsigned, 4> &Indices, Type *SubShadowTy,
879ea981165SJianzhou Zhao     Value *PrimitiveShadow, IRBuilder<> &IRB) {
880ea981165SJianzhou Zhao   if (!isa<ArrayType>(SubShadowTy) && !isa<StructType>(SubShadowTy))
881ea981165SJianzhou Zhao     return IRB.CreateInsertValue(Shadow, PrimitiveShadow, Indices);
882ea981165SJianzhou Zhao 
883ea981165SJianzhou Zhao   if (ArrayType *AT = dyn_cast<ArrayType>(SubShadowTy)) {
884ea981165SJianzhou Zhao     for (unsigned Idx = 0; Idx < AT->getNumElements(); Idx++) {
885ea981165SJianzhou Zhao       Indices.push_back(Idx);
886ea981165SJianzhou Zhao       Shadow = expandFromPrimitiveShadowRecursive(
887ea981165SJianzhou Zhao           Shadow, Indices, AT->getElementType(), PrimitiveShadow, IRB);
888ea981165SJianzhou Zhao       Indices.pop_back();
889ea981165SJianzhou Zhao     }
890ea981165SJianzhou Zhao     return Shadow;
891ea981165SJianzhou Zhao   }
892ea981165SJianzhou Zhao 
893ea981165SJianzhou Zhao   if (StructType *ST = dyn_cast<StructType>(SubShadowTy)) {
894ea981165SJianzhou Zhao     for (unsigned Idx = 0; Idx < ST->getNumElements(); Idx++) {
895ea981165SJianzhou Zhao       Indices.push_back(Idx);
896ea981165SJianzhou Zhao       Shadow = expandFromPrimitiveShadowRecursive(
897ea981165SJianzhou Zhao           Shadow, Indices, ST->getElementType(Idx), PrimitiveShadow, IRB);
898ea981165SJianzhou Zhao       Indices.pop_back();
899ea981165SJianzhou Zhao     }
900ea981165SJianzhou Zhao     return Shadow;
901ea981165SJianzhou Zhao   }
902ea981165SJianzhou Zhao   llvm_unreachable("Unexpected shadow type");
903ea981165SJianzhou Zhao }
904ea981165SJianzhou Zhao 
shouldInstrumentWithCall()905db7fe6cdSJianzhou Zhao bool DFSanFunction::shouldInstrumentWithCall() {
906db7fe6cdSJianzhou Zhao   return ClInstrumentWithCallThreshold >= 0 &&
907db7fe6cdSJianzhou Zhao          NumOriginStores >= ClInstrumentWithCallThreshold;
908db7fe6cdSJianzhou Zhao }
909db7fe6cdSJianzhou Zhao 
expandFromPrimitiveShadow(Type * T,Value * PrimitiveShadow,Instruction * Pos)910ea981165SJianzhou Zhao Value *DFSanFunction::expandFromPrimitiveShadow(Type *T, Value *PrimitiveShadow,
911ea981165SJianzhou Zhao                                                 Instruction *Pos) {
912ea981165SJianzhou Zhao   Type *ShadowTy = DFS.getShadowTy(T);
913ea981165SJianzhou Zhao 
914ea981165SJianzhou Zhao   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
915ea981165SJianzhou Zhao     return PrimitiveShadow;
916ea981165SJianzhou Zhao 
917ea981165SJianzhou Zhao   if (DFS.isZeroShadow(PrimitiveShadow))
918ea981165SJianzhou Zhao     return DFS.getZeroShadow(ShadowTy);
919ea981165SJianzhou Zhao 
920ea981165SJianzhou Zhao   IRBuilder<> IRB(Pos);
921ea981165SJianzhou Zhao   SmallVector<unsigned, 4> Indices;
922ea981165SJianzhou Zhao   Value *Shadow = UndefValue::get(ShadowTy);
923ea981165SJianzhou Zhao   Shadow = expandFromPrimitiveShadowRecursive(Shadow, Indices, ShadowTy,
924ea981165SJianzhou Zhao                                               PrimitiveShadow, IRB);
925ea981165SJianzhou Zhao 
926ea981165SJianzhou Zhao   // Caches the primitive shadow value that built the shadow value.
927ea981165SJianzhou Zhao   CachedCollapsedShadows[Shadow] = PrimitiveShadow;
928ea981165SJianzhou Zhao   return Shadow;
929ea981165SJianzhou Zhao }
930ea981165SJianzhou Zhao 
931ea981165SJianzhou Zhao template <class AggregateType>
collapseAggregateShadow(AggregateType * AT,Value * Shadow,IRBuilder<> & IRB)932ea981165SJianzhou Zhao Value *DFSanFunction::collapseAggregateShadow(AggregateType *AT, Value *Shadow,
933ea981165SJianzhou Zhao                                               IRBuilder<> &IRB) {
934ea981165SJianzhou Zhao   if (!AT->getNumElements())
935ea981165SJianzhou Zhao     return DFS.ZeroPrimitiveShadow;
936ea981165SJianzhou Zhao 
937ea981165SJianzhou Zhao   Value *FirstItem = IRB.CreateExtractValue(Shadow, 0);
938ea981165SJianzhou Zhao   Value *Aggregator = collapseToPrimitiveShadow(FirstItem, IRB);
939ea981165SJianzhou Zhao 
940ea981165SJianzhou Zhao   for (unsigned Idx = 1; Idx < AT->getNumElements(); Idx++) {
941ea981165SJianzhou Zhao     Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx);
942ea981165SJianzhou Zhao     Value *ShadowInner = collapseToPrimitiveShadow(ShadowItem, IRB);
943ea981165SJianzhou Zhao     Aggregator = IRB.CreateOr(Aggregator, ShadowInner);
944ea981165SJianzhou Zhao   }
945ea981165SJianzhou Zhao   return Aggregator;
946ea981165SJianzhou Zhao }
947ea981165SJianzhou Zhao 
collapseToPrimitiveShadow(Value * Shadow,IRBuilder<> & IRB)948ea981165SJianzhou Zhao Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
949ea981165SJianzhou Zhao                                                 IRBuilder<> &IRB) {
950ea981165SJianzhou Zhao   Type *ShadowTy = Shadow->getType();
951ea981165SJianzhou Zhao   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
952ea981165SJianzhou Zhao     return Shadow;
953ea981165SJianzhou Zhao   if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy))
954ea981165SJianzhou Zhao     return collapseAggregateShadow<>(AT, Shadow, IRB);
955ea981165SJianzhou Zhao   if (StructType *ST = dyn_cast<StructType>(ShadowTy))
956ea981165SJianzhou Zhao     return collapseAggregateShadow<>(ST, Shadow, IRB);
957ea981165SJianzhou Zhao   llvm_unreachable("Unexpected shadow type");
958ea981165SJianzhou Zhao }
959ea981165SJianzhou Zhao 
collapseToPrimitiveShadow(Value * Shadow,Instruction * Pos)960ea981165SJianzhou Zhao Value *DFSanFunction::collapseToPrimitiveShadow(Value *Shadow,
961ea981165SJianzhou Zhao                                                 Instruction *Pos) {
962ea981165SJianzhou Zhao   Type *ShadowTy = Shadow->getType();
963ea981165SJianzhou Zhao   if (!isa<ArrayType>(ShadowTy) && !isa<StructType>(ShadowTy))
964ea981165SJianzhou Zhao     return Shadow;
965ea981165SJianzhou Zhao 
966ea981165SJianzhou Zhao   // Checks if the cached collapsed shadow value dominates Pos.
967ea981165SJianzhou Zhao   Value *&CS = CachedCollapsedShadows[Shadow];
968ea981165SJianzhou Zhao   if (CS && DT.dominates(CS, Pos))
969ea981165SJianzhou Zhao     return CS;
970ea981165SJianzhou Zhao 
971ea981165SJianzhou Zhao   IRBuilder<> IRB(Pos);
972ea981165SJianzhou Zhao   Value *PrimitiveShadow = collapseToPrimitiveShadow(Shadow, IRB);
973ea981165SJianzhou Zhao   // Caches the converted primitive shadow value.
974ea981165SJianzhou Zhao   CS = PrimitiveShadow;
975ea981165SJianzhou Zhao   return PrimitiveShadow;
976ea981165SJianzhou Zhao }
977ea981165SJianzhou Zhao 
addConditionalCallbacksIfEnabled(Instruction & I,Value * Condition)9784e173585SAndrew Browne void DFSanFunction::addConditionalCallbacksIfEnabled(Instruction &I,
9794e173585SAndrew Browne                                                      Value *Condition) {
9804e173585SAndrew Browne   if (!ClConditionalCallbacks) {
9814e173585SAndrew Browne     return;
9824e173585SAndrew Browne   }
9834e173585SAndrew Browne   IRBuilder<> IRB(&I);
9844e173585SAndrew Browne   Value *CondShadow = getShadow(Condition);
9854e173585SAndrew Browne   if (DFS.shouldTrackOrigins()) {
9864e173585SAndrew Browne     Value *CondOrigin = getOrigin(Condition);
9874e173585SAndrew Browne     IRB.CreateCall(DFS.DFSanConditionalCallbackOriginFn,
9884e173585SAndrew Browne                    {CondShadow, CondOrigin});
9894e173585SAndrew Browne   } else {
9904e173585SAndrew Browne     IRB.CreateCall(DFS.DFSanConditionalCallbackFn, {CondShadow});
9914e173585SAndrew Browne   }
9924e173585SAndrew Browne }
9934e173585SAndrew Browne 
getShadowTy(Type * OrigTy)994ea981165SJianzhou Zhao Type *DataFlowSanitizer::getShadowTy(Type *OrigTy) {
995ea981165SJianzhou Zhao   if (!OrigTy->isSized())
996ea981165SJianzhou Zhao     return PrimitiveShadowTy;
997ea981165SJianzhou Zhao   if (isa<IntegerType>(OrigTy))
998ea981165SJianzhou Zhao     return PrimitiveShadowTy;
999ea981165SJianzhou Zhao   if (isa<VectorType>(OrigTy))
1000ea981165SJianzhou Zhao     return PrimitiveShadowTy;
1001ea981165SJianzhou Zhao   if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy))
1002ea981165SJianzhou Zhao     return ArrayType::get(getShadowTy(AT->getElementType()),
1003ea981165SJianzhou Zhao                           AT->getNumElements());
1004ea981165SJianzhou Zhao   if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
1005ea981165SJianzhou Zhao     SmallVector<Type *, 4> Elements;
1006ea981165SJianzhou Zhao     for (unsigned I = 0, N = ST->getNumElements(); I < N; ++I)
1007ea981165SJianzhou Zhao       Elements.push_back(getShadowTy(ST->getElementType(I)));
1008ea981165SJianzhou Zhao     return StructType::get(*Ctx, Elements);
1009ea981165SJianzhou Zhao   }
1010ea981165SJianzhou Zhao   return PrimitiveShadowTy;
1011ea981165SJianzhou Zhao }
1012a28db8b2SJianzhou Zhao 
getShadowTy(Value * V)1013a28db8b2SJianzhou Zhao Type *DataFlowSanitizer::getShadowTy(Value *V) {
1014a28db8b2SJianzhou Zhao   return getShadowTy(V->getType());
1015a28db8b2SJianzhou Zhao }
1016a28db8b2SJianzhou Zhao 
initializeModule(Module & M)101745f6d552SAndrew Browne bool DataFlowSanitizer::initializeModule(Module &M) {
1018fce43576SEugene Zelenko   Triple TargetTriple(M.getTargetTriple());
1019a28d91d8SMehdi Amini   const DataLayout &DL = M.getDataLayout();
1020e5d5b0c7SPeter Collingbourne 
102114407332SAndrew Browne   if (TargetTriple.getOS() != Triple::Linux)
102214407332SAndrew Browne     report_fatal_error("unsupported operating system");
102314407332SAndrew Browne   if (TargetTriple.getArch() != Triple::x86_64)
102414407332SAndrew Browne     report_fatal_error("unsupported architecture");
102545f6d552SAndrew Browne   MapParams = &Linux_X86_64_MemoryMapParams;
102614407332SAndrew Browne 
1027e5d5b0c7SPeter Collingbourne   Mod = &M;
1028e5d5b0c7SPeter Collingbourne   Ctx = &M.getContext();
102906c9b4aaSJianzhou Zhao   Int8Ptr = Type::getInt8PtrTy(*Ctx);
10307e658b2fSJianzhou Zhao   OriginTy = IntegerType::get(*Ctx, OriginWidthBits);
10317e658b2fSJianzhou Zhao   OriginPtrTy = PointerType::getUnqual(OriginTy);
1032bd726d27SJianzhou Zhao   PrimitiveShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
1033bd726d27SJianzhou Zhao   PrimitiveShadowPtrTy = PointerType::getUnqual(PrimitiveShadowTy);
1034a28d91d8SMehdi Amini   IntptrTy = DL.getIntPtrType(*Ctx);
1035bd726d27SJianzhou Zhao   ZeroPrimitiveShadow = ConstantInt::getSigned(PrimitiveShadowTy, 0);
1036dab953c8SJianzhou Zhao   ZeroOrigin = ConstantInt::getSigned(OriginTy, 0);
10376ff18b08SGeorge Balatsouras 
1038bd726d27SJianzhou Zhao   Type *DFSanUnionLoadArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1039bd726d27SJianzhou Zhao   DFSanUnionLoadFnTy = FunctionType::get(PrimitiveShadowTy, DFSanUnionLoadArgs,
1040bd726d27SJianzhou Zhao                                          /*isVarArg=*/false);
10417e658b2fSJianzhou Zhao   Type *DFSanLoadLabelAndOriginArgs[2] = {Int8Ptr, IntptrTy};
10427e658b2fSJianzhou Zhao   DFSanLoadLabelAndOriginFnTy =
10437e658b2fSJianzhou Zhao       FunctionType::get(IntegerType::get(*Ctx, 64), DFSanLoadLabelAndOriginArgs,
10447e658b2fSJianzhou Zhao                         /*isVarArg=*/false);
104568162e75SPeter Collingbourne   DFSanUnimplementedFnTy = FunctionType::get(
104668162e75SPeter Collingbourne       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
1047204c12eeSAndrew Browne   Type *DFSanWrapperExternWeakNullArgs[2] = {Int8Ptr, Int8Ptr};
1048204c12eeSAndrew Browne   DFSanWrapperExternWeakNullFnTy =
1049204c12eeSAndrew Browne       FunctionType::get(Type::getVoidTy(*Ctx), DFSanWrapperExternWeakNullArgs,
1050204c12eeSAndrew Browne                         /*isVarArg=*/false);
1051a05aa0ddSJianzhou Zhao   Type *DFSanSetLabelArgs[4] = {PrimitiveShadowTy, OriginTy,
1052a05aa0ddSJianzhou Zhao                                 Type::getInt8PtrTy(*Ctx), IntptrTy};
10539d31d6f3SPeter Collingbourne   DFSanSetLabelFnTy = FunctionType::get(Type::getVoidTy(*Ctx),
10549d31d6f3SPeter Collingbourne                                         DFSanSetLabelArgs, /*isVarArg=*/false);
1055bd726d27SJianzhou Zhao   DFSanNonzeroLabelFnTy =
1056bd726d27SJianzhou Zhao       FunctionType::get(Type::getVoidTy(*Ctx), None, /*isVarArg=*/false);
1057a1099840SPeter Collingbourne   DFSanVarargWrapperFnTy = FunctionType::get(
1058a1099840SPeter Collingbourne       Type::getVoidTy(*Ctx), Type::getInt8PtrTy(*Ctx), /*isVarArg=*/false);
10594e173585SAndrew Browne   DFSanConditionalCallbackFnTy =
10604e173585SAndrew Browne       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
10614e173585SAndrew Browne                         /*isVarArg=*/false);
10624e173585SAndrew Browne   Type *DFSanConditionalCallbackOriginArgs[2] = {PrimitiveShadowTy, OriginTy};
10634e173585SAndrew Browne   DFSanConditionalCallbackOriginFnTy = FunctionType::get(
10644e173585SAndrew Browne       Type::getVoidTy(*Ctx), DFSanConditionalCallbackOriginArgs,
10654e173585SAndrew Browne       /*isVarArg=*/false);
1066bd726d27SJianzhou Zhao   DFSanCmpCallbackFnTy =
1067bd726d27SJianzhou Zhao       FunctionType::get(Type::getVoidTy(*Ctx), PrimitiveShadowTy,
106806c9b4aaSJianzhou Zhao                         /*isVarArg=*/false);
10697e658b2fSJianzhou Zhao   DFSanChainOriginFnTy =
10707e658b2fSJianzhou Zhao       FunctionType::get(OriginTy, OriginTy, /*isVarArg=*/false);
10717fdf2709SJianzhou Zhao   Type *DFSanChainOriginIfTaintedArgs[2] = {PrimitiveShadowTy, OriginTy};
10727fdf2709SJianzhou Zhao   DFSanChainOriginIfTaintedFnTy = FunctionType::get(
10737fdf2709SJianzhou Zhao       OriginTy, DFSanChainOriginIfTaintedArgs, /*isVarArg=*/false);
10747e658b2fSJianzhou Zhao   Type *DFSanMaybeStoreOriginArgs[4] = {IntegerType::get(*Ctx, ShadowWidthBits),
10757e658b2fSJianzhou Zhao                                         Int8Ptr, IntptrTy, OriginTy};
10767e658b2fSJianzhou Zhao   DFSanMaybeStoreOriginFnTy = FunctionType::get(
10777e658b2fSJianzhou Zhao       Type::getVoidTy(*Ctx), DFSanMaybeStoreOriginArgs, /*isVarArg=*/false);
10787e658b2fSJianzhou Zhao   Type *DFSanMemOriginTransferArgs[3] = {Int8Ptr, Int8Ptr, IntptrTy};
10797e658b2fSJianzhou Zhao   DFSanMemOriginTransferFnTy = FunctionType::get(
10807e658b2fSJianzhou Zhao       Type::getVoidTy(*Ctx), DFSanMemOriginTransferArgs, /*isVarArg=*/false);
1081bd726d27SJianzhou Zhao   Type *DFSanLoadStoreCallbackArgs[2] = {PrimitiveShadowTy, Int8Ptr};
108206c9b4aaSJianzhou Zhao   DFSanLoadStoreCallbackFnTy =
108306c9b4aaSJianzhou Zhao       FunctionType::get(Type::getVoidTy(*Ctx), DFSanLoadStoreCallbackArgs,
108406c9b4aaSJianzhou Zhao                         /*isVarArg=*/false);
1085bd726d27SJianzhou Zhao   Type *DFSanMemTransferCallbackArgs[2] = {PrimitiveShadowPtrTy, IntptrTy};
1086f668baa4SMatt Morehouse   DFSanMemTransferCallbackFnTy =
1087f668baa4SMatt Morehouse       FunctionType::get(Type::getVoidTy(*Ctx), DFSanMemTransferCallbackArgs,
1088f668baa4SMatt Morehouse                         /*isVarArg=*/false);
1089e5d5b0c7SPeter Collingbourne 
1090e5d5b0c7SPeter Collingbourne   ColdCallWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1091db7fe6cdSJianzhou Zhao   OriginStoreWeights = MDBuilder(*Ctx).createBranchWeights(1, 1000);
1092e5d5b0c7SPeter Collingbourne   return true;
1093e5d5b0c7SPeter Collingbourne }
1094e5d5b0c7SPeter Collingbourne 
isInstrumented(const Function * F)109559b1262dSPeter Collingbourne bool DataFlowSanitizer::isInstrumented(const Function *F) {
1096b7dd329fSAlexey Samsonov   return !ABIList.isIn(*F, "uninstrumented");
1097e5d5b0c7SPeter Collingbourne }
1098e5d5b0c7SPeter Collingbourne 
isInstrumented(const GlobalAlias * GA)109959b1262dSPeter Collingbourne bool DataFlowSanitizer::isInstrumented(const GlobalAlias *GA) {
1100b7dd329fSAlexey Samsonov   return !ABIList.isIn(*GA, "uninstrumented");
110159b1262dSPeter Collingbourne }
110259b1262dSPeter Collingbourne 
isForceZeroLabels(const Function * F)1103c533b88aSAndrew Browne bool DataFlowSanitizer::isForceZeroLabels(const Function *F) {
1104c533b88aSAndrew Browne   return ABIList.isIn(*F, "force_zero_labels");
1105c533b88aSAndrew Browne }
1106c533b88aSAndrew Browne 
getWrapperKind(Function * F)110768162e75SPeter Collingbourne DataFlowSanitizer::WrapperKind DataFlowSanitizer::getWrapperKind(Function *F) {
1108b7dd329fSAlexey Samsonov   if (ABIList.isIn(*F, "functional"))
110968162e75SPeter Collingbourne     return WK_Functional;
1110b7dd329fSAlexey Samsonov   if (ABIList.isIn(*F, "discard"))
111168162e75SPeter Collingbourne     return WK_Discard;
111240d3deebSLorenzo Martignoni   if (ABIList.isIn(*F, "custom"))
111368162e75SPeter Collingbourne     return WK_Custom;
111468162e75SPeter Collingbourne 
111568162e75SPeter Collingbourne   return WK_Warning;
111668162e75SPeter Collingbourne }
111768162e75SPeter Collingbourne 
addGlobalNameSuffix(GlobalValue * GV)1118c6b5a25eSGeorge Balatsouras void DataFlowSanitizer::addGlobalNameSuffix(GlobalValue *GV) {
1119c6b5a25eSGeorge Balatsouras   std::string GVName = std::string(GV->getName()), Suffix = ".dfsan";
1120c6b5a25eSGeorge Balatsouras   GV->setName(GVName + Suffix);
112159b1262dSPeter Collingbourne 
112259b1262dSPeter Collingbourne   // Try to change the name of the function in module inline asm.  We only do
112359b1262dSPeter Collingbourne   // this for specific asm directives, currently only ".symver", to try to avoid
112459b1262dSPeter Collingbourne   // corrupting asm which happens to contain the symbol name as a substring.
112559b1262dSPeter Collingbourne   // Note that the substitution for .symver assumes that the versioned symbol
112659b1262dSPeter Collingbourne   // also has an instrumented name.
112759b1262dSPeter Collingbourne   std::string Asm = GV->getParent()->getModuleInlineAsm();
112859b1262dSPeter Collingbourne   std::string SearchStr = ".symver " + GVName + ",";
112959b1262dSPeter Collingbourne   size_t Pos = Asm.find(SearchStr);
113059b1262dSPeter Collingbourne   if (Pos != std::string::npos) {
1131c6b5a25eSGeorge Balatsouras     Asm.replace(Pos, SearchStr.size(), ".symver " + GVName + Suffix + ",");
1132c6b5a25eSGeorge Balatsouras     Pos = Asm.find("@");
1133c6b5a25eSGeorge Balatsouras 
1134c6b5a25eSGeorge Balatsouras     if (Pos == std::string::npos)
113521661607SSimon Pilgrim       report_fatal_error(Twine("unsupported .symver: ", Asm));
1136c6b5a25eSGeorge Balatsouras 
1137c6b5a25eSGeorge Balatsouras     Asm.replace(Pos, 1, Suffix + "@");
113859b1262dSPeter Collingbourne     GV->getParent()->setModuleInlineAsm(Asm);
113959b1262dSPeter Collingbourne   }
114059b1262dSPeter Collingbourne }
114159b1262dSPeter Collingbourne 
buildExternWeakCheckIfNeeded(IRBuilder<> & IRB,Function * F)1142204c12eeSAndrew Browne void DataFlowSanitizer::buildExternWeakCheckIfNeeded(IRBuilder<> &IRB,
1143204c12eeSAndrew Browne                                                      Function *F) {
1144204c12eeSAndrew Browne   // If the function we are wrapping was ExternWeak, it may be null.
1145204c12eeSAndrew Browne   // The original code before calling this wrapper may have checked for null,
1146204c12eeSAndrew Browne   // but replacing with a known-to-not-be-null wrapper can break this check.
1147204c12eeSAndrew Browne   // When replacing uses of the extern weak function with the wrapper we try
1148204c12eeSAndrew Browne   // to avoid replacing uses in conditionals, but this is not perfect.
1149204c12eeSAndrew Browne   // In the case where we fail, and accidentially optimize out a null check
1150204c12eeSAndrew Browne   // for a extern weak function, add a check here to help identify the issue.
1151204c12eeSAndrew Browne   if (GlobalValue::isExternalWeakLinkage(F->getLinkage())) {
1152204c12eeSAndrew Browne     std::vector<Value *> Args;
1153204c12eeSAndrew Browne     Args.push_back(IRB.CreatePointerCast(F, IRB.getInt8PtrTy()));
1154204c12eeSAndrew Browne     Args.push_back(IRB.CreateGlobalStringPtr(F->getName()));
1155204c12eeSAndrew Browne     IRB.CreateCall(DFSanWrapperExternWeakNullFn, Args);
1156204c12eeSAndrew Browne   }
1157204c12eeSAndrew Browne }
1158204c12eeSAndrew Browne 
1159761a4fc4SPeter Collingbourne Function *
buildWrapperFunction(Function * F,StringRef NewFName,GlobalValue::LinkageTypes NewFLink,FunctionType * NewFT)1160761a4fc4SPeter Collingbourne DataFlowSanitizer::buildWrapperFunction(Function *F, StringRef NewFName,
1161761a4fc4SPeter Collingbourne                                         GlobalValue::LinkageTypes NewFLink,
1162761a4fc4SPeter Collingbourne                                         FunctionType *NewFT) {
1163761a4fc4SPeter Collingbourne   FunctionType *FT = F->getFunctionType();
11646bcf2ba2SAlexander Richardson   Function *NewF = Function::Create(NewFT, NewFLink, F->getAddressSpace(),
11656bcf2ba2SAlexander Richardson                                     NewFName, F->getParent());
1166761a4fc4SPeter Collingbourne   NewF->copyAttributesFrom(F);
1167ad727ab7SArthur Eubanks   NewF->removeRetAttrs(
1168ee4930b6SReid Kleckner       AttributeFuncs::typeIncompatible(NewFT->getReturnType()));
1169761a4fc4SPeter Collingbourne 
1170761a4fc4SPeter Collingbourne   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", NewF);
1171a1099840SPeter Collingbourne   if (F->isVarArg()) {
1172e8e8bfeeSNikita Popov     NewF->removeFnAttr("split-stack");
1173a1099840SPeter Collingbourne     CallInst::Create(DFSanVarargWrapperFn,
1174a1099840SPeter Collingbourne                      IRBuilder<>(BB).CreateGlobalStringPtr(F->getName()), "",
1175a1099840SPeter Collingbourne                      BB);
1176a1099840SPeter Collingbourne     new UnreachableInst(*Ctx, BB);
1177a1099840SPeter Collingbourne   } else {
11786ff18b08SGeorge Balatsouras     auto ArgIt = pointer_iterator<Argument *>(NewF->arg_begin());
11796ff18b08SGeorge Balatsouras     std::vector<Value *> Args(ArgIt, ArgIt + FT->getNumParams());
11806ff18b08SGeorge Balatsouras 
1181761a4fc4SPeter Collingbourne     CallInst *CI = CallInst::Create(F, Args, "", BB);
1182761a4fc4SPeter Collingbourne     if (FT->getReturnType()->isVoidTy())
1183761a4fc4SPeter Collingbourne       ReturnInst::Create(*Ctx, BB);
1184761a4fc4SPeter Collingbourne     else
1185761a4fc4SPeter Collingbourne       ReturnInst::Create(*Ctx, CI, BB);
1186a1099840SPeter Collingbourne   }
1187761a4fc4SPeter Collingbourne 
1188761a4fc4SPeter Collingbourne   return NewF;
1189761a4fc4SPeter Collingbourne }
1190761a4fc4SPeter Collingbourne 
11918d8fda49SZola Bridges // Initialize DataFlowSanitizer runtime functions and declare them in the module
initializeRuntimeFunctions(Module & M)11928d8fda49SZola Bridges void DataFlowSanitizer::initializeRuntimeFunctions(Module &M) {
119313680223SJames Y Knight   {
119413680223SJames Y Knight     AttributeList AL;
1195de0ae9e8SArthur Eubanks     AL = AL.addFnAttribute(M.getContext(), Attribute::NoUnwind);
1196de0ae9e8SArthur Eubanks     AL = AL.addFnAttribute(M.getContext(), Attribute::ReadOnly);
1197de0ae9e8SArthur Eubanks     AL = AL.addRetAttribute(M.getContext(), Attribute::ZExt);
1198e5d5b0c7SPeter Collingbourne     DFSanUnionLoadFn =
119913680223SJames Y Knight         Mod->getOrInsertFunction("__dfsan_union_load", DFSanUnionLoadFnTy, AL);
1200e5d5b0c7SPeter Collingbourne   }
1201e2d0b44aSMatt Morehouse   {
1202e2d0b44aSMatt Morehouse     AttributeList AL;
1203de0ae9e8SArthur Eubanks     AL = AL.addFnAttribute(M.getContext(), Attribute::NoUnwind);
1204de0ae9e8SArthur Eubanks     AL = AL.addFnAttribute(M.getContext(), Attribute::ReadOnly);
1205de0ae9e8SArthur Eubanks     AL = AL.addRetAttribute(M.getContext(), Attribute::ZExt);
12067e658b2fSJianzhou Zhao     DFSanLoadLabelAndOriginFn = Mod->getOrInsertFunction(
12077e658b2fSJianzhou Zhao         "__dfsan_load_label_and_origin", DFSanLoadLabelAndOriginFnTy, AL);
12087e658b2fSJianzhou Zhao   }
120968162e75SPeter Collingbourne   DFSanUnimplementedFn =
121068162e75SPeter Collingbourne       Mod->getOrInsertFunction("__dfsan_unimplemented", DFSanUnimplementedFnTy);
1211204c12eeSAndrew Browne   DFSanWrapperExternWeakNullFn = Mod->getOrInsertFunction(
1212204c12eeSAndrew Browne       "__dfsan_wrapper_extern_weak_null", DFSanWrapperExternWeakNullFnTy);
121313680223SJames Y Knight   {
121413680223SJames Y Knight     AttributeList AL;
121513680223SJames Y Knight     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1216a05aa0ddSJianzhou Zhao     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
12179d31d6f3SPeter Collingbourne     DFSanSetLabelFn =
121813680223SJames Y Knight         Mod->getOrInsertFunction("__dfsan_set_label", DFSanSetLabelFnTy, AL);
12199d31d6f3SPeter Collingbourne   }
1220444c59e2SPeter Collingbourne   DFSanNonzeroLabelFn =
1221444c59e2SPeter Collingbourne       Mod->getOrInsertFunction("__dfsan_nonzero_label", DFSanNonzeroLabelFnTy);
1222a1099840SPeter Collingbourne   DFSanVarargWrapperFn = Mod->getOrInsertFunction("__dfsan_vararg_wrapper",
1223a1099840SPeter Collingbourne                                                   DFSanVarargWrapperFnTy);
12247e658b2fSJianzhou Zhao   {
12257e658b2fSJianzhou Zhao     AttributeList AL;
12267e658b2fSJianzhou Zhao     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
1227de0ae9e8SArthur Eubanks     AL = AL.addRetAttribute(M.getContext(), Attribute::ZExt);
12287e658b2fSJianzhou Zhao     DFSanChainOriginFn = Mod->getOrInsertFunction("__dfsan_chain_origin",
12297e658b2fSJianzhou Zhao                                                   DFSanChainOriginFnTy, AL);
12307e658b2fSJianzhou Zhao   }
12317fdf2709SJianzhou Zhao   {
12327fdf2709SJianzhou Zhao     AttributeList AL;
12337fdf2709SJianzhou Zhao     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
12347fdf2709SJianzhou Zhao     AL = AL.addParamAttribute(M.getContext(), 1, Attribute::ZExt);
1235de0ae9e8SArthur Eubanks     AL = AL.addRetAttribute(M.getContext(), Attribute::ZExt);
12367fdf2709SJianzhou Zhao     DFSanChainOriginIfTaintedFn = Mod->getOrInsertFunction(
12377fdf2709SJianzhou Zhao         "__dfsan_chain_origin_if_tainted", DFSanChainOriginIfTaintedFnTy, AL);
12387fdf2709SJianzhou Zhao   }
12397e658b2fSJianzhou Zhao   DFSanMemOriginTransferFn = Mod->getOrInsertFunction(
12407e658b2fSJianzhou Zhao       "__dfsan_mem_origin_transfer", DFSanMemOriginTransferFnTy);
12417e658b2fSJianzhou Zhao 
12427e658b2fSJianzhou Zhao   {
12437e658b2fSJianzhou Zhao     AttributeList AL;
12447e658b2fSJianzhou Zhao     AL = AL.addParamAttribute(M.getContext(), 0, Attribute::ZExt);
12457e658b2fSJianzhou Zhao     AL = AL.addParamAttribute(M.getContext(), 3, Attribute::ZExt);
12467e658b2fSJianzhou Zhao     DFSanMaybeStoreOriginFn = Mod->getOrInsertFunction(
12477e658b2fSJianzhou Zhao         "__dfsan_maybe_store_origin", DFSanMaybeStoreOriginFnTy, AL);
12487e658b2fSJianzhou Zhao   }
12492e6cd338SJianzhou Zhao 
12502e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12512e6cd338SJianzhou Zhao       DFSanUnionLoadFn.getCallee()->stripPointerCasts());
12522e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12537e658b2fSJianzhou Zhao       DFSanLoadLabelAndOriginFn.getCallee()->stripPointerCasts());
12547e658b2fSJianzhou Zhao   DFSanRuntimeFunctions.insert(
12552e6cd338SJianzhou Zhao       DFSanUnimplementedFn.getCallee()->stripPointerCasts());
12562e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
1257204c12eeSAndrew Browne       DFSanWrapperExternWeakNullFn.getCallee()->stripPointerCasts());
1258204c12eeSAndrew Browne   DFSanRuntimeFunctions.insert(
12592e6cd338SJianzhou Zhao       DFSanSetLabelFn.getCallee()->stripPointerCasts());
12602e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12612e6cd338SJianzhou Zhao       DFSanNonzeroLabelFn.getCallee()->stripPointerCasts());
12622e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12632e6cd338SJianzhou Zhao       DFSanVarargWrapperFn.getCallee()->stripPointerCasts());
12642e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12652e6cd338SJianzhou Zhao       DFSanLoadCallbackFn.getCallee()->stripPointerCasts());
12662e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12672e6cd338SJianzhou Zhao       DFSanStoreCallbackFn.getCallee()->stripPointerCasts());
12682e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12692e6cd338SJianzhou Zhao       DFSanMemTransferCallbackFn.getCallee()->stripPointerCasts());
12702e6cd338SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12714e173585SAndrew Browne       DFSanConditionalCallbackFn.getCallee()->stripPointerCasts());
12724e173585SAndrew Browne   DFSanRuntimeFunctions.insert(
12734e173585SAndrew Browne       DFSanConditionalCallbackOriginFn.getCallee()->stripPointerCasts());
12744e173585SAndrew Browne   DFSanRuntimeFunctions.insert(
12752e6cd338SJianzhou Zhao       DFSanCmpCallbackFn.getCallee()->stripPointerCasts());
12767e658b2fSJianzhou Zhao   DFSanRuntimeFunctions.insert(
12777e658b2fSJianzhou Zhao       DFSanChainOriginFn.getCallee()->stripPointerCasts());
12787e658b2fSJianzhou Zhao   DFSanRuntimeFunctions.insert(
12797fdf2709SJianzhou Zhao       DFSanChainOriginIfTaintedFn.getCallee()->stripPointerCasts());
12807fdf2709SJianzhou Zhao   DFSanRuntimeFunctions.insert(
12817e658b2fSJianzhou Zhao       DFSanMemOriginTransferFn.getCallee()->stripPointerCasts());
12827e658b2fSJianzhou Zhao   DFSanRuntimeFunctions.insert(
12837e658b2fSJianzhou Zhao       DFSanMaybeStoreOriginFn.getCallee()->stripPointerCasts());
12848d8fda49SZola Bridges }
1285e5d5b0c7SPeter Collingbourne 
12868d8fda49SZola Bridges // Initializes event callback functions and declare them in the module
initializeCallbackFunctions(Module & M)12878d8fda49SZola Bridges void DataFlowSanitizer::initializeCallbackFunctions(Module &M) {
128852f889abSMatt Morehouse   DFSanLoadCallbackFn = Mod->getOrInsertFunction("__dfsan_load_callback",
128906c9b4aaSJianzhou Zhao                                                  DFSanLoadStoreCallbackFnTy);
129006c9b4aaSJianzhou Zhao   DFSanStoreCallbackFn = Mod->getOrInsertFunction("__dfsan_store_callback",
129106c9b4aaSJianzhou Zhao                                                   DFSanLoadStoreCallbackFnTy);
1292f668baa4SMatt Morehouse   DFSanMemTransferCallbackFn = Mod->getOrInsertFunction(
1293f668baa4SMatt Morehouse       "__dfsan_mem_transfer_callback", DFSanMemTransferCallbackFnTy);
129406c9b4aaSJianzhou Zhao   DFSanCmpCallbackFn =
129506c9b4aaSJianzhou Zhao       Mod->getOrInsertFunction("__dfsan_cmp_callback", DFSanCmpCallbackFnTy);
12964e173585SAndrew Browne 
12974e173585SAndrew Browne   DFSanConditionalCallbackFn = Mod->getOrInsertFunction(
12984e173585SAndrew Browne       "__dfsan_conditional_callback", DFSanConditionalCallbackFnTy);
12994e173585SAndrew Browne   DFSanConditionalCallbackOriginFn =
13004e173585SAndrew Browne       Mod->getOrInsertFunction("__dfsan_conditional_callback_origin",
13014e173585SAndrew Browne                                DFSanConditionalCallbackOriginFnTy);
13028d8fda49SZola Bridges }
13038d8fda49SZola Bridges 
injectMetadataGlobals(Module & M)1304c9075a1cSGeorge Balatsouras void DataFlowSanitizer::injectMetadataGlobals(Module &M) {
1305c9075a1cSGeorge Balatsouras   // These variables can be used:
1306c9075a1cSGeorge Balatsouras   // - by the runtime (to discover what the shadow width was, during
1307c9075a1cSGeorge Balatsouras   //   compilation)
1308c9075a1cSGeorge Balatsouras   // - in testing (to avoid hardcoding the shadow width and type but instead
1309c9075a1cSGeorge Balatsouras   //   extract them by pattern matching)
1310c9075a1cSGeorge Balatsouras   Type *IntTy = Type::getInt32Ty(*Ctx);
1311c9075a1cSGeorge Balatsouras   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bits", IntTy, [&] {
1312c9075a1cSGeorge Balatsouras     return new GlobalVariable(
1313c9075a1cSGeorge Balatsouras         M, IntTy, /*isConstant=*/true, GlobalValue::WeakODRLinkage,
1314c9075a1cSGeorge Balatsouras         ConstantInt::get(IntTy, ShadowWidthBits), "__dfsan_shadow_width_bits");
1315c9075a1cSGeorge Balatsouras   });
1316c9075a1cSGeorge Balatsouras   (void)Mod->getOrInsertGlobal("__dfsan_shadow_width_bytes", IntTy, [&] {
1317c9075a1cSGeorge Balatsouras     return new GlobalVariable(M, IntTy, /*isConstant=*/true,
1318c9075a1cSGeorge Balatsouras                               GlobalValue::WeakODRLinkage,
1319c9075a1cSGeorge Balatsouras                               ConstantInt::get(IntTy, ShadowWidthBytes),
1320c9075a1cSGeorge Balatsouras                               "__dfsan_shadow_width_bytes");
1321c9075a1cSGeorge Balatsouras   });
1322c9075a1cSGeorge Balatsouras }
1323c9075a1cSGeorge Balatsouras 
runImpl(Module & M)132471d0a2b8SArthur Eubanks bool DataFlowSanitizer::runImpl(Module &M) {
132545f6d552SAndrew Browne   initializeModule(M);
132671d0a2b8SArthur Eubanks 
13278d8fda49SZola Bridges   if (ABIList.isIn(M, "skip"))
13288d8fda49SZola Bridges     return false;
13298d8fda49SZola Bridges 
1330bff09876Sserge-sans-paille   const unsigned InitialGlobalSize = M.global_size();
1331bff09876Sserge-sans-paille   const unsigned InitialModuleSize = M.size();
1332bff09876Sserge-sans-paille 
1333bff09876Sserge-sans-paille   bool Changed = false;
1334bff09876Sserge-sans-paille 
13356ff18b08SGeorge Balatsouras   auto GetOrInsertGlobal = [this, &Changed](StringRef Name,
1336406dc549SJianzhou Zhao                                             Type *Ty) -> Constant * {
1337406dc549SJianzhou Zhao     Constant *C = Mod->getOrInsertGlobal(Name, Ty);
1338406dc549SJianzhou Zhao     if (GlobalVariable *G = dyn_cast<GlobalVariable>(C)) {
1339bff09876Sserge-sans-paille       Changed |= G->getThreadLocalMode() != GlobalVariable::InitialExecTLSModel;
13408d8fda49SZola Bridges       G->setThreadLocalMode(GlobalVariable::InitialExecTLSModel);
13418d8fda49SZola Bridges     }
1342406dc549SJianzhou Zhao     return C;
1343406dc549SJianzhou Zhao   };
1344406dc549SJianzhou Zhao 
1345406dc549SJianzhou Zhao   // These globals must be kept in sync with the ones in dfsan.cpp.
13466ff18b08SGeorge Balatsouras   ArgTLS =
13476ff18b08SGeorge Balatsouras       GetOrInsertGlobal("__dfsan_arg_tls",
13486ff18b08SGeorge Balatsouras                         ArrayType::get(Type::getInt64Ty(*Ctx), ArgTLSSize / 8));
13496ff18b08SGeorge Balatsouras   RetvalTLS = GetOrInsertGlobal(
1350406dc549SJianzhou Zhao       "__dfsan_retval_tls",
13516ff18b08SGeorge Balatsouras       ArrayType::get(Type::getInt64Ty(*Ctx), RetvalTLSSize / 8));
13526ff18b08SGeorge Balatsouras   ArgOriginTLSTy = ArrayType::get(OriginTy, NumOfElementsInArgOrgTLS);
13536ff18b08SGeorge Balatsouras   ArgOriginTLS = GetOrInsertGlobal("__dfsan_arg_origin_tls", ArgOriginTLSTy);
13546ff18b08SGeorge Balatsouras   RetvalOriginTLS = GetOrInsertGlobal("__dfsan_retval_origin_tls", OriginTy);
13557e658b2fSJianzhou Zhao 
13567e658b2fSJianzhou Zhao   (void)Mod->getOrInsertGlobal("__dfsan_track_origins", OriginTy, [&] {
13577e658b2fSJianzhou Zhao     Changed = true;
13587e658b2fSJianzhou Zhao     return new GlobalVariable(
13597e658b2fSJianzhou Zhao         M, OriginTy, true, GlobalValue::WeakODRLinkage,
1360ae6648ceSJianzhou Zhao         ConstantInt::getSigned(OriginTy,
1361ae6648ceSJianzhou Zhao                                shouldTrackOrigins() ? ClTrackOrigins : 0),
13627e658b2fSJianzhou Zhao         "__dfsan_track_origins");
13637e658b2fSJianzhou Zhao   });
13648d8fda49SZola Bridges 
1365c9075a1cSGeorge Balatsouras   injectMetadataGlobals(M);
1366c9075a1cSGeorge Balatsouras 
13678d8fda49SZola Bridges   initializeCallbackFunctions(M);
13688d8fda49SZola Bridges   initializeRuntimeFunctions(M);
1369470db54cSMatt Morehouse 
1370e5d5b0c7SPeter Collingbourne   std::vector<Function *> FnsToInstrument;
1371fce43576SEugene Zelenko   SmallPtrSet<Function *, 2> FnsWithNativeABI;
1372c533b88aSAndrew Browne   SmallPtrSet<Function *, 2> FnsWithForceZeroLabel;
137304e79cf7STaewook Oh   SmallPtrSet<Constant *, 1> PersonalityFns;
13746ff18b08SGeorge Balatsouras   for (Function &F : M)
137504e79cf7STaewook Oh     if (!F.isIntrinsic() && !DFSanRuntimeFunctions.contains(&F)) {
13766ff18b08SGeorge Balatsouras       FnsToInstrument.push_back(&F);
137704e79cf7STaewook Oh       if (F.hasPersonalityFn())
137804e79cf7STaewook Oh         PersonalityFns.insert(F.getPersonalityFn()->stripPointerCasts());
137904e79cf7STaewook Oh     }
138004e79cf7STaewook Oh 
138104e79cf7STaewook Oh   if (ClIgnorePersonalityRoutine) {
138204e79cf7STaewook Oh     for (auto *C : PersonalityFns) {
138304e79cf7STaewook Oh       assert(isa<Function>(C) && "Personality routine is not a function!");
138404e79cf7STaewook Oh       Function *F = cast<Function>(C);
138504e79cf7STaewook Oh       if (!isInstrumented(F))
138604e79cf7STaewook Oh         FnsToInstrument.erase(
138704e79cf7STaewook Oh             std::remove(FnsToInstrument.begin(), FnsToInstrument.end(), F),
138804e79cf7STaewook Oh             FnsToInstrument.end());
138904e79cf7STaewook Oh     }
139004e79cf7STaewook Oh   }
1391e5d5b0c7SPeter Collingbourne 
139234f0c313SPeter Collingbourne   // Give function aliases prefixes when necessary, and build wrappers where the
139334f0c313SPeter Collingbourne   // instrumentedness is inconsistent.
13940d182d9dSKazu Hirata   for (GlobalAlias &GA : llvm::make_early_inc_range(M.aliases())) {
139559b1262dSPeter Collingbourne     // Don't stop on weak.  We assume people aren't playing games with the
139659b1262dSPeter Collingbourne     // instrumentedness of overridden weak aliases.
13970d182d9dSKazu Hirata     auto *F = dyn_cast<Function>(GA.getAliaseeObject());
13986ff18b08SGeorge Balatsouras     if (!F)
13996ff18b08SGeorge Balatsouras       continue;
14006ff18b08SGeorge Balatsouras 
14010d182d9dSKazu Hirata     bool GAInst = isInstrumented(&GA), FInst = isInstrumented(F);
140259b1262dSPeter Collingbourne     if (GAInst && FInst) {
14030d182d9dSKazu Hirata       addGlobalNameSuffix(&GA);
140434f0c313SPeter Collingbourne     } else if (GAInst != FInst) {
140534f0c313SPeter Collingbourne       // Non-instrumented alias of an instrumented function, or vice versa.
140634f0c313SPeter Collingbourne       // Replace the alias with a native-ABI wrapper of the aliasee.  The pass
140734f0c313SPeter Collingbourne       // below will take care of instrumenting it.
140834f0c313SPeter Collingbourne       Function *NewF =
14090d182d9dSKazu Hirata           buildWrapperFunction(F, "", GA.getLinkage(), F->getFunctionType());
14100d182d9dSKazu Hirata       GA.replaceAllUsesWith(ConstantExpr::getBitCast(NewF, GA.getType()));
14110d182d9dSKazu Hirata       NewF->takeName(&GA);
14120d182d9dSKazu Hirata       GA.eraseFromParent();
141334f0c313SPeter Collingbourne       FnsToInstrument.push_back(NewF);
141459b1262dSPeter Collingbourne     }
141559b1262dSPeter Collingbourne   }
141659b1262dSPeter Collingbourne 
1417ee4930b6SReid Kleckner   ReadOnlyNoneAttrs.addAttribute(Attribute::ReadOnly)
1418ee4930b6SReid Kleckner       .addAttribute(Attribute::ReadNone);
141968162e75SPeter Collingbourne 
142068162e75SPeter Collingbourne   // First, change the ABI of every function in the module.  ABI-listed
1421e5d5b0c7SPeter Collingbourne   // functions keep their original ABI and get a wrapper function.
14226ff18b08SGeorge Balatsouras   for (std::vector<Function *>::iterator FI = FnsToInstrument.begin(),
14236ff18b08SGeorge Balatsouras                                          FE = FnsToInstrument.end();
14246ff18b08SGeorge Balatsouras        FI != FE; ++FI) {
14256ff18b08SGeorge Balatsouras     Function &F = **FI;
1426e5d5b0c7SPeter Collingbourne     FunctionType *FT = F.getFunctionType();
142768162e75SPeter Collingbourne 
142859b1262dSPeter Collingbourne     bool IsZeroArgsVoidRet = (FT->getNumParams() == 0 && !FT->isVarArg() &&
142959b1262dSPeter Collingbourne                               FT->getReturnType()->isVoidTy());
143068162e75SPeter Collingbourne 
143168162e75SPeter Collingbourne     if (isInstrumented(&F)) {
1432c533b88aSAndrew Browne       if (isForceZeroLabels(&F))
1433c533b88aSAndrew Browne         FnsWithForceZeroLabel.insert(&F);
1434c533b88aSAndrew Browne 
1435c6b5a25eSGeorge Balatsouras       // Instrumented functions get a '.dfsan' suffix.  This allows us to more
1436c6b5a25eSGeorge Balatsouras       // easily identify cases of mismatching ABIs. This naming scheme is
1437c6b5a25eSGeorge Balatsouras       // mangling-compatible (see Itanium ABI), using a vendor-specific suffix.
1438c6b5a25eSGeorge Balatsouras       addGlobalNameSuffix(&F);
143959b1262dSPeter Collingbourne     } else if (!IsZeroArgsVoidRet || getWrapperKind(&F) == WK_Custom) {
144068162e75SPeter Collingbourne       // Build a wrapper function for F.  The wrapper simply calls F, and is
144168162e75SPeter Collingbourne       // added to FnsToInstrument so that any instrumentation according to its
144268162e75SPeter Collingbourne       // WrapperKind is done in the second pass below.
1443d03bf12cSPeter Collingbourne 
1444d03bf12cSPeter Collingbourne       // If the function being wrapped has local linkage, then preserve the
1445d03bf12cSPeter Collingbourne       // function's linkage in the wrapper function.
14466ff18b08SGeorge Balatsouras       GlobalValue::LinkageTypes WrapperLinkage =
14476ff18b08SGeorge Balatsouras           F.hasLocalLinkage() ? F.getLinkage()
1448d03bf12cSPeter Collingbourne                               : GlobalValue::LinkOnceODRLinkage;
1449d03bf12cSPeter Collingbourne 
14506dae24dfSAlexey Samsonov       Function *NewF = buildWrapperFunction(
1451a47d435bSJianzhou Zhao           &F,
1452a47d435bSJianzhou Zhao           (shouldTrackOrigins() ? std::string("dfso$") : std::string("dfsw$")) +
1453a47d435bSJianzhou Zhao               std::string(F.getName()),
145461ec2148SAndrew Browne           WrapperLinkage, FT);
1455ad727ab7SArthur Eubanks       NewF->removeFnAttrs(ReadOnlyNoneAttrs);
1456e5d5b0c7SPeter Collingbourne 
1457e5d5b0c7SPeter Collingbourne       Value *WrappedFnCst =
1458e5d5b0c7SPeter Collingbourne           ConstantExpr::getBitCast(NewF, PointerType::getUnqual(FT));
1459cddcf217SAndrew Browne 
1460cddcf217SAndrew Browne       // Extern weak functions can sometimes be null at execution time.
1461cddcf217SAndrew Browne       // Code will sometimes check if an extern weak function is null.
1462cddcf217SAndrew Browne       // This could look something like:
1463cddcf217SAndrew Browne       //   declare extern_weak i8 @my_func(i8)
1464cddcf217SAndrew Browne       //   br i1 icmp ne (i8 (i8)* @my_func, i8 (i8)* null), label %use_my_func,
1465cddcf217SAndrew Browne       //   label %avoid_my_func
1466cddcf217SAndrew Browne       // The @"dfsw$my_func" wrapper is never null, so if we replace this use
1467cddcf217SAndrew Browne       // in the comparision, the icmp will simplify to false and we have
1468cddcf217SAndrew Browne       // accidentially optimized away a null check that is necessary.
1469cddcf217SAndrew Browne       // This can lead to a crash when the null extern_weak my_func is called.
1470cddcf217SAndrew Browne       //
1471cddcf217SAndrew Browne       // To prevent (the most common pattern of) this problem,
1472cddcf217SAndrew Browne       // do not replace uses in comparisons with the wrapper.
1473cddcf217SAndrew Browne       // We definitely want to replace uses in call instructions.
1474cddcf217SAndrew Browne       // Other uses (e.g. store the function address somewhere) might be
1475cddcf217SAndrew Browne       // called or compared or both - this case may not be handled correctly.
1476cddcf217SAndrew Browne       // We will default to replacing with wrapper in cases we are unsure.
1477cddcf217SAndrew Browne       auto IsNotCmpUse = [](Use &U) -> bool {
1478cddcf217SAndrew Browne         User *Usr = U.getUser();
1479cddcf217SAndrew Browne         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Usr)) {
1480cddcf217SAndrew Browne           // This is the most common case for icmp ne null
1481cddcf217SAndrew Browne           if (CE->getOpcode() == Instruction::ICmp) {
1482cddcf217SAndrew Browne             return false;
1483cddcf217SAndrew Browne           }
1484cddcf217SAndrew Browne         }
1485cddcf217SAndrew Browne         if (Instruction *I = dyn_cast<Instruction>(Usr)) {
1486cddcf217SAndrew Browne           if (I->getOpcode() == Instruction::ICmp) {
1487cddcf217SAndrew Browne             return false;
1488cddcf217SAndrew Browne           }
1489cddcf217SAndrew Browne         }
1490cddcf217SAndrew Browne         return true;
1491cddcf217SAndrew Browne       };
1492cddcf217SAndrew Browne       F.replaceUsesWithIf(WrappedFnCst, IsNotCmpUse);
1493c6c6c7b1SDavid Blaikie 
1494e5d5b0c7SPeter Collingbourne       UnwrappedFnMap[WrappedFnCst] = &F;
14956ff18b08SGeorge Balatsouras       *FI = NewF;
149668162e75SPeter Collingbourne 
149768162e75SPeter Collingbourne       if (!F.isDeclaration()) {
149868162e75SPeter Collingbourne         // This function is probably defining an interposition of an
149968162e75SPeter Collingbourne         // uninstrumented function and hence needs to keep the original ABI.
150068162e75SPeter Collingbourne         // But any functions it may call need to use the instrumented ABI, so
150168162e75SPeter Collingbourne         // we instrument it in a mode which preserves the original ABI.
150268162e75SPeter Collingbourne         FnsWithNativeABI.insert(&F);
150368162e75SPeter Collingbourne 
150468162e75SPeter Collingbourne         // This code needs to rebuild the iterators, as they may be invalidated
150568162e75SPeter Collingbourne         // by the push_back, taking care that the new range does not include
150668162e75SPeter Collingbourne         // any functions added by this code.
15076ff18b08SGeorge Balatsouras         size_t N = FI - FnsToInstrument.begin(),
15086ff18b08SGeorge Balatsouras                Count = FE - FnsToInstrument.begin();
150968162e75SPeter Collingbourne         FnsToInstrument.push_back(&F);
15106ff18b08SGeorge Balatsouras         FI = FnsToInstrument.begin() + N;
15116ff18b08SGeorge Balatsouras         FE = FnsToInstrument.begin() + Count;
1512e5d5b0c7SPeter Collingbourne       }
151340d3deebSLorenzo Martignoni       // Hopefully, nobody will try to indirectly call a vararg
151440d3deebSLorenzo Martignoni       // function... yet.
151540d3deebSLorenzo Martignoni     } else if (FT->isVarArg()) {
151640d3deebSLorenzo Martignoni       UnwrappedFnMap[&F] = &F;
15176ff18b08SGeorge Balatsouras       *FI = nullptr;
1518e5d5b0c7SPeter Collingbourne     }
1519e5d5b0c7SPeter Collingbourne   }
1520e5d5b0c7SPeter Collingbourne 
15216ff18b08SGeorge Balatsouras   for (Function *F : FnsToInstrument) {
15226ff18b08SGeorge Balatsouras     if (!F || F->isDeclaration())
1523e5d5b0c7SPeter Collingbourne       continue;
1524e5d5b0c7SPeter Collingbourne 
15256ff18b08SGeorge Balatsouras     removeUnreachableBlocks(*F);
1526ae66d57bSPeter Collingbourne 
1527c533b88aSAndrew Browne     DFSanFunction DFSF(*this, F, FnsWithNativeABI.count(F),
1528c533b88aSAndrew Browne                        FnsWithForceZeroLabel.count(F));
1529e5d5b0c7SPeter Collingbourne 
1530e5d5b0c7SPeter Collingbourne     // DFSanVisitor may create new basic blocks, which confuses df_iterator.
1531e5d5b0c7SPeter Collingbourne     // Build a copy of the list before iterating over it.
15326ff18b08SGeorge Balatsouras     SmallVector<BasicBlock *, 4> BBList(depth_first(&F->getEntryBlock()));
1533e5d5b0c7SPeter Collingbourne 
15346ff18b08SGeorge Balatsouras     for (BasicBlock *BB : BBList) {
15356ff18b08SGeorge Balatsouras       Instruction *Inst = &BB->front();
1536fce43576SEugene Zelenko       while (true) {
1537e5d5b0c7SPeter Collingbourne         // DFSanVisitor may split the current basic block, changing the current
1538e5d5b0c7SPeter Collingbourne         // instruction's next pointer and moving the next instruction to the
1539e5d5b0c7SPeter Collingbourne         // tail block from which we should continue.
1540e5d5b0c7SPeter Collingbourne         Instruction *Next = Inst->getNextNode();
1541fb3a2b4fSPeter Collingbourne         // DFSanVisitor may delete Inst, so keep track of whether it was a
1542fb3a2b4fSPeter Collingbourne         // terminator.
15439ae926b9SChandler Carruth         bool IsTerminator = Inst->isTerminator();
1544e5d5b0c7SPeter Collingbourne         if (!DFSF.SkipInsts.count(Inst))
1545e5d5b0c7SPeter Collingbourne           DFSanVisitor(DFSF).visit(Inst);
1546fb3a2b4fSPeter Collingbourne         if (IsTerminator)
1547e5d5b0c7SPeter Collingbourne           break;
1548e5d5b0c7SPeter Collingbourne         Inst = Next;
1549e5d5b0c7SPeter Collingbourne       }
1550e5d5b0c7SPeter Collingbourne     }
1551e5d5b0c7SPeter Collingbourne 
155268162e75SPeter Collingbourne     // We will not necessarily be able to compute the shadow for every phi node
155368162e75SPeter Collingbourne     // until we have visited every block.  Therefore, the code that handles phi
155468162e75SPeter Collingbourne     // nodes adds them to the PHIFixups list so that they can be properly
155568162e75SPeter Collingbourne     // handled here.
15566a9a686cSJianzhou Zhao     for (DFSanFunction::PHIFixupElement &P : DFSF.PHIFixups) {
15576a9a686cSJianzhou Zhao       for (unsigned Val = 0, N = P.Phi->getNumIncomingValues(); Val != N;
15586a9a686cSJianzhou Zhao            ++Val) {
15596a9a686cSJianzhou Zhao         P.ShadowPhi->setIncomingValue(
15606a9a686cSJianzhou Zhao             Val, DFSF.getShadow(P.Phi->getIncomingValue(Val)));
15616a9a686cSJianzhou Zhao         if (P.OriginPhi)
15626a9a686cSJianzhou Zhao           P.OriginPhi->setIncomingValue(
15636a9a686cSJianzhou Zhao               Val, DFSF.getOrigin(P.Phi->getIncomingValue(Val)));
1564e5d5b0c7SPeter Collingbourne       }
1565e5d5b0c7SPeter Collingbourne     }
1566444c59e2SPeter Collingbourne 
1567444c59e2SPeter Collingbourne     // -dfsan-debug-nonzero-labels will split the CFG in all kinds of crazy
1568444c59e2SPeter Collingbourne     // places (i.e. instructions in basic blocks we haven't even begun visiting
1569444c59e2SPeter Collingbourne     // yet).  To make our life easier, do this work in a pass after the main
1570444c59e2SPeter Collingbourne     // instrumentation.
1571444c59e2SPeter Collingbourne     if (ClDebugNonzeroLabels) {
1572fab565a5SPeter Collingbourne       for (Value *V : DFSF.NonZeroChecks) {
1573444c59e2SPeter Collingbourne         Instruction *Pos;
1574fab565a5SPeter Collingbourne         if (Instruction *I = dyn_cast<Instruction>(V))
1575444c59e2SPeter Collingbourne           Pos = I->getNextNode();
1576444c59e2SPeter Collingbourne         else
1577e82c286fSDuncan P. N. Exon Smith           Pos = &DFSF.F->getEntryBlock().front();
1578444c59e2SPeter Collingbourne         while (isa<PHINode>(Pos) || isa<AllocaInst>(Pos))
1579444c59e2SPeter Collingbourne           Pos = Pos->getNextNode();
1580444c59e2SPeter Collingbourne         IRBuilder<> IRB(Pos);
1581ea981165SJianzhou Zhao         Value *PrimitiveShadow = DFSF.collapseToPrimitiveShadow(V, Pos);
1582ea981165SJianzhou Zhao         Value *Ne =
1583ea981165SJianzhou Zhao             IRB.CreateICmpNE(PrimitiveShadow, DFSF.DFS.ZeroPrimitiveShadow);
1584444c59e2SPeter Collingbourne         BranchInst *BI = cast<BranchInst>(SplitBlockAndInsertIfThen(
1585a9164e9eSEvgeniy Stepanov             Ne, Pos, /*Unreachable=*/false, ColdCallWeights));
1586444c59e2SPeter Collingbourne         IRBuilder<> ThenIRB(BI);
1587ff6409d0SDavid Blaikie         ThenIRB.CreateCall(DFSF.DFS.DFSanNonzeroLabelFn, {});
1588444c59e2SPeter Collingbourne       }
1589444c59e2SPeter Collingbourne     }
1590e5d5b0c7SPeter Collingbourne   }
1591e5d5b0c7SPeter Collingbourne 
1592bff09876Sserge-sans-paille   return Changed || !FnsToInstrument.empty() ||
1593bff09876Sserge-sans-paille          M.global_size() != InitialGlobalSize || M.size() != InitialModuleSize;
1594e5d5b0c7SPeter Collingbourne }
1595e5d5b0c7SPeter Collingbourne 
getArgTLS(Type * T,unsigned ArgOffset,IRBuilder<> & IRB)1596a28db8b2SJianzhou Zhao Value *DFSanFunction::getArgTLS(Type *T, unsigned ArgOffset, IRBuilder<> &IRB) {
159780e326a8SJianzhou Zhao   Value *Base = IRB.CreatePointerCast(DFS.ArgTLS, DFS.IntptrTy);
159880e326a8SJianzhou Zhao   if (ArgOffset)
159980e326a8SJianzhou Zhao     Base = IRB.CreateAdd(Base, ConstantInt::get(DFS.IntptrTy, ArgOffset));
1600a28db8b2SJianzhou Zhao   return IRB.CreateIntToPtr(Base, PointerType::get(DFS.getShadowTy(T), 0),
160180e326a8SJianzhou Zhao                             "_dfsarg");
160280e326a8SJianzhou Zhao }
160380e326a8SJianzhou Zhao 
getRetvalTLS(Type * T,IRBuilder<> & IRB)1604a28db8b2SJianzhou Zhao Value *DFSanFunction::getRetvalTLS(Type *T, IRBuilder<> &IRB) {
160580e326a8SJianzhou Zhao   return IRB.CreatePointerCast(
1606a28db8b2SJianzhou Zhao       DFS.RetvalTLS, PointerType::get(DFS.getShadowTy(T), 0), "_dfsret");
160780e326a8SJianzhou Zhao }
16087424efd5SJianzhou Zhao 
getRetvalOriginTLS()1609dab953c8SJianzhou Zhao Value *DFSanFunction::getRetvalOriginTLS() { return DFS.RetvalOriginTLS; }
1610dab953c8SJianzhou Zhao 
getArgOriginTLS(unsigned ArgNo,IRBuilder<> & IRB)1611dab953c8SJianzhou Zhao Value *DFSanFunction::getArgOriginTLS(unsigned ArgNo, IRBuilder<> &IRB) {
1612dab953c8SJianzhou Zhao   return IRB.CreateConstGEP2_64(DFS.ArgOriginTLSTy, DFS.ArgOriginTLS, 0, ArgNo,
1613dab953c8SJianzhou Zhao                                 "_dfsarg_o");
1614dab953c8SJianzhou Zhao }
1615dab953c8SJianzhou Zhao 
getOrigin(Value * V)1616dab953c8SJianzhou Zhao Value *DFSanFunction::getOrigin(Value *V) {
1617dab953c8SJianzhou Zhao   assert(DFS.shouldTrackOrigins());
1618dab953c8SJianzhou Zhao   if (!isa<Argument>(V) && !isa<Instruction>(V))
1619dab953c8SJianzhou Zhao     return DFS.ZeroOrigin;
1620dab953c8SJianzhou Zhao   Value *&Origin = ValOriginMap[V];
1621dab953c8SJianzhou Zhao   if (!Origin) {
1622dab953c8SJianzhou Zhao     if (Argument *A = dyn_cast<Argument>(V)) {
1623dab953c8SJianzhou Zhao       if (IsNativeABI)
1624dab953c8SJianzhou Zhao         return DFS.ZeroOrigin;
16256ff18b08SGeorge Balatsouras       if (A->getArgNo() < DFS.NumOfElementsInArgOrgTLS) {
1626dab953c8SJianzhou Zhao         Instruction *ArgOriginTLSPos = &*F->getEntryBlock().begin();
1627dab953c8SJianzhou Zhao         IRBuilder<> IRB(ArgOriginTLSPos);
1628dab953c8SJianzhou Zhao         Value *ArgOriginPtr = getArgOriginTLS(A->getArgNo(), IRB);
1629dab953c8SJianzhou Zhao         Origin = IRB.CreateLoad(DFS.OriginTy, ArgOriginPtr);
1630dab953c8SJianzhou Zhao       } else {
1631dab953c8SJianzhou Zhao         // Overflow
1632dab953c8SJianzhou Zhao         Origin = DFS.ZeroOrigin;
1633dab953c8SJianzhou Zhao       }
1634dab953c8SJianzhou Zhao     } else {
1635dab953c8SJianzhou Zhao       Origin = DFS.ZeroOrigin;
1636dab953c8SJianzhou Zhao     }
1637dab953c8SJianzhou Zhao   }
1638dab953c8SJianzhou Zhao   return Origin;
1639dab953c8SJianzhou Zhao }
1640dab953c8SJianzhou Zhao 
setOrigin(Instruction * I,Value * Origin)1641dab953c8SJianzhou Zhao void DFSanFunction::setOrigin(Instruction *I, Value *Origin) {
1642dab953c8SJianzhou Zhao   if (!DFS.shouldTrackOrigins())
1643dab953c8SJianzhou Zhao     return;
1644dab953c8SJianzhou Zhao   assert(!ValOriginMap.count(I));
1645dab953c8SJianzhou Zhao   assert(Origin->getType() == DFS.OriginTy);
1646dab953c8SJianzhou Zhao   ValOriginMap[I] = Origin;
1647dab953c8SJianzhou Zhao }
16487424efd5SJianzhou Zhao 
getShadowForTLSArgument(Argument * A)164980e326a8SJianzhou Zhao Value *DFSanFunction::getShadowForTLSArgument(Argument *A) {
165080e326a8SJianzhou Zhao   unsigned ArgOffset = 0;
165180e326a8SJianzhou Zhao   const DataLayout &DL = F->getParent()->getDataLayout();
165280e326a8SJianzhou Zhao   for (auto &FArg : F->args()) {
165380e326a8SJianzhou Zhao     if (!FArg.getType()->isSized()) {
165480e326a8SJianzhou Zhao       if (A == &FArg)
165580e326a8SJianzhou Zhao         break;
165680e326a8SJianzhou Zhao       continue;
165780e326a8SJianzhou Zhao     }
165880e326a8SJianzhou Zhao 
1659a28db8b2SJianzhou Zhao     unsigned Size = DL.getTypeAllocSize(DFS.getShadowTy(&FArg));
166080e326a8SJianzhou Zhao     if (A != &FArg) {
16616ff18b08SGeorge Balatsouras       ArgOffset += alignTo(Size, ShadowTLSAlignment);
16626ff18b08SGeorge Balatsouras       if (ArgOffset > ArgTLSSize)
166380e326a8SJianzhou Zhao         break; // ArgTLS overflows, uses a zero shadow.
166480e326a8SJianzhou Zhao       continue;
166580e326a8SJianzhou Zhao     }
166680e326a8SJianzhou Zhao 
16676ff18b08SGeorge Balatsouras     if (ArgOffset + Size > ArgTLSSize)
166880e326a8SJianzhou Zhao       break; // ArgTLS overflows, uses a zero shadow.
166980e326a8SJianzhou Zhao 
167080e326a8SJianzhou Zhao     Instruction *ArgTLSPos = &*F->getEntryBlock().begin();
167180e326a8SJianzhou Zhao     IRBuilder<> IRB(ArgTLSPos);
1672a28db8b2SJianzhou Zhao     Value *ArgShadowPtr = getArgTLS(FArg.getType(), ArgOffset, IRB);
1673a28db8b2SJianzhou Zhao     return IRB.CreateAlignedLoad(DFS.getShadowTy(&FArg), ArgShadowPtr,
16746ff18b08SGeorge Balatsouras                                  ShadowTLSAlignment);
167580e326a8SJianzhou Zhao   }
167680e326a8SJianzhou Zhao 
1677a28db8b2SJianzhou Zhao   return DFS.getZeroShadow(A);
1678e5d5b0c7SPeter Collingbourne }
1679e5d5b0c7SPeter Collingbourne 
getShadow(Value * V)1680e5d5b0c7SPeter Collingbourne Value *DFSanFunction::getShadow(Value *V) {
1681e5d5b0c7SPeter Collingbourne   if (!isa<Argument>(V) && !isa<Instruction>(V))
1682a28db8b2SJianzhou Zhao     return DFS.getZeroShadow(V);
1683c533b88aSAndrew Browne   if (IsForceZeroLabels)
1684c533b88aSAndrew Browne     return DFS.getZeroShadow(V);
1685e5d5b0c7SPeter Collingbourne   Value *&Shadow = ValShadowMap[V];
1686e5d5b0c7SPeter Collingbourne   if (!Shadow) {
1687e5d5b0c7SPeter Collingbourne     if (Argument *A = dyn_cast<Argument>(V)) {
168868162e75SPeter Collingbourne       if (IsNativeABI)
1689a28db8b2SJianzhou Zhao         return DFS.getZeroShadow(V);
169080e326a8SJianzhou Zhao       Shadow = getShadowForTLSArgument(A);
1691fab565a5SPeter Collingbourne       NonZeroChecks.push_back(Shadow);
1692e5d5b0c7SPeter Collingbourne     } else {
1693a28db8b2SJianzhou Zhao       Shadow = DFS.getZeroShadow(V);
1694e5d5b0c7SPeter Collingbourne     }
1695e5d5b0c7SPeter Collingbourne   }
1696e5d5b0c7SPeter Collingbourne   return Shadow;
1697e5d5b0c7SPeter Collingbourne }
1698e5d5b0c7SPeter Collingbourne 
setShadow(Instruction * I,Value * Shadow)1699e5d5b0c7SPeter Collingbourne void DFSanFunction::setShadow(Instruction *I, Value *Shadow) {
1700e5d5b0c7SPeter Collingbourne   assert(!ValShadowMap.count(I));
1701e5d5b0c7SPeter Collingbourne   ValShadowMap[I] = Shadow;
1702e5d5b0c7SPeter Collingbourne }
1703e5d5b0c7SPeter Collingbourne 
170445f6d552SAndrew Browne /// Compute the integer shadow offset that corresponds to a given
170545f6d552SAndrew Browne /// application address.
170645f6d552SAndrew Browne ///
170745f6d552SAndrew Browne /// Offset = (Addr & ~AndMask) ^ XorMask
getShadowOffset(Value * Addr,IRBuilder<> & IRB)1708cb1f1aabSJianzhou Zhao Value *DataFlowSanitizer::getShadowOffset(Value *Addr, IRBuilder<> &IRB) {
1709e5d5b0c7SPeter Collingbourne   assert(Addr != RetvalTLS && "Reinstrumenting?");
171045f6d552SAndrew Browne   Value *OffsetLong = IRB.CreatePointerCast(Addr, IntptrTy);
171145f6d552SAndrew Browne 
171245f6d552SAndrew Browne   uint64_t AndMask = MapParams->AndMask;
171345f6d552SAndrew Browne   if (AndMask)
171445f6d552SAndrew Browne     OffsetLong =
171545f6d552SAndrew Browne         IRB.CreateAnd(OffsetLong, ConstantInt::get(IntptrTy, ~AndMask));
171645f6d552SAndrew Browne 
171745f6d552SAndrew Browne   uint64_t XorMask = MapParams->XorMask;
171845f6d552SAndrew Browne   if (XorMask)
171945f6d552SAndrew Browne     OffsetLong = IRB.CreateXor(OffsetLong, ConstantInt::get(IntptrTy, XorMask));
172045f6d552SAndrew Browne   return OffsetLong;
1721cb1f1aabSJianzhou Zhao }
1722d866b9c9SJianzhou Zhao 
1723cb1f1aabSJianzhou Zhao std::pair<Value *, Value *>
getShadowOriginAddress(Value * Addr,Align InstAlignment,Instruction * Pos)1724cb1f1aabSJianzhou Zhao DataFlowSanitizer::getShadowOriginAddress(Value *Addr, Align InstAlignment,
1725cb1f1aabSJianzhou Zhao                                           Instruction *Pos) {
17265b4dda55SGeorge Balatsouras   // Returns ((Addr & shadow_mask) + origin_base - shadow_base) & ~4UL
1727cb1f1aabSJianzhou Zhao   IRBuilder<> IRB(Pos);
1728cb1f1aabSJianzhou Zhao   Value *ShadowOffset = getShadowOffset(Addr, IRB);
172945f6d552SAndrew Browne   Value *ShadowLong = ShadowOffset;
173045f6d552SAndrew Browne   uint64_t ShadowBase = MapParams->ShadowBase;
173145f6d552SAndrew Browne   if (ShadowBase != 0) {
173245f6d552SAndrew Browne     ShadowLong =
173345f6d552SAndrew Browne         IRB.CreateAdd(ShadowLong, ConstantInt::get(IntptrTy, ShadowBase));
173445f6d552SAndrew Browne   }
173545f6d552SAndrew Browne   IntegerType *ShadowTy = IntegerType::get(*Ctx, ShadowWidthBits);
173645f6d552SAndrew Browne   Value *ShadowPtr =
173745f6d552SAndrew Browne       IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
1738cb1f1aabSJianzhou Zhao   Value *OriginPtr = nullptr;
1739cb1f1aabSJianzhou Zhao   if (shouldTrackOrigins()) {
174045f6d552SAndrew Browne     Value *OriginLong = ShadowOffset;
174145f6d552SAndrew Browne     uint64_t OriginBase = MapParams->OriginBase;
174245f6d552SAndrew Browne     if (OriginBase != 0)
174345f6d552SAndrew Browne       OriginLong =
174445f6d552SAndrew Browne           IRB.CreateAdd(OriginLong, ConstantInt::get(IntptrTy, OriginBase));
1745cb1f1aabSJianzhou Zhao     const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1746cb1f1aabSJianzhou Zhao     // When alignment is >= 4, Addr must be aligned to 4, otherwise it is UB.
1747cb1f1aabSJianzhou Zhao     // So Mask is unnecessary.
17486ff18b08SGeorge Balatsouras     if (Alignment < MinOriginAlignment) {
17496ff18b08SGeorge Balatsouras       uint64_t Mask = MinOriginAlignment.value() - 1;
1750cb1f1aabSJianzhou Zhao       OriginLong = IRB.CreateAnd(OriginLong, ConstantInt::get(IntptrTy, ~Mask));
1751cb1f1aabSJianzhou Zhao     }
1752cb1f1aabSJianzhou Zhao     OriginPtr = IRB.CreateIntToPtr(OriginLong, OriginPtrTy);
1753cb1f1aabSJianzhou Zhao   }
175445f6d552SAndrew Browne   return std::make_pair(ShadowPtr, OriginPtr);
1755cb1f1aabSJianzhou Zhao }
1756d866b9c9SJianzhou Zhao 
getShadowAddress(Value * Addr,Instruction * Pos,Value * ShadowOffset)1757d10f173fSGeorge Balatsouras Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos,
1758d10f173fSGeorge Balatsouras                                            Value *ShadowOffset) {
1759d10f173fSGeorge Balatsouras   IRBuilder<> IRB(Pos);
1760d10f173fSGeorge Balatsouras   return IRB.CreateIntToPtr(ShadowOffset, PrimitiveShadowPtrTy);
1761d10f173fSGeorge Balatsouras }
1762d10f173fSGeorge Balatsouras 
getShadowAddress(Value * Addr,Instruction * Pos)1763cb1f1aabSJianzhou Zhao Value *DataFlowSanitizer::getShadowAddress(Value *Addr, Instruction *Pos) {
1764cb1f1aabSJianzhou Zhao   IRBuilder<> IRB(Pos);
1765cb1f1aabSJianzhou Zhao   Value *ShadowOffset = getShadowOffset(Addr, IRB);
1766d10f173fSGeorge Balatsouras   return getShadowAddress(Addr, Pos, ShadowOffset);
1767e5d5b0c7SPeter Collingbourne }
1768e5d5b0c7SPeter Collingbourne 
combineShadowsThenConvert(Type * T,Value * V1,Value * V2,Instruction * Pos)1769ea981165SJianzhou Zhao Value *DFSanFunction::combineShadowsThenConvert(Type *T, Value *V1, Value *V2,
1770ea981165SJianzhou Zhao                                                 Instruction *Pos) {
1771ea981165SJianzhou Zhao   Value *PrimitiveValue = combineShadows(V1, V2, Pos);
1772ea981165SJianzhou Zhao   return expandFromPrimitiveShadow(T, PrimitiveValue, Pos);
1773ea981165SJianzhou Zhao }
1774ea981165SJianzhou Zhao 
1775e5d5b0c7SPeter Collingbourne // Generates IR to compute the union of the two given shadows, inserting it
1776ea981165SJianzhou Zhao // before Pos. The combined value is with primitive type.
combineShadows(Value * V1,Value * V2,Instruction * Pos)177783def1cbSPeter Collingbourne Value *DFSanFunction::combineShadows(Value *V1, Value *V2, Instruction *Pos) {
1778a28db8b2SJianzhou Zhao   if (DFS.isZeroShadow(V1))
1779ea981165SJianzhou Zhao     return collapseToPrimitiveShadow(V2, Pos);
1780a28db8b2SJianzhou Zhao   if (DFS.isZeroShadow(V2))
1781ea981165SJianzhou Zhao     return collapseToPrimitiveShadow(V1, Pos);
1782e5d5b0c7SPeter Collingbourne   if (V1 == V2)
1783ea981165SJianzhou Zhao     return collapseToPrimitiveShadow(V1, Pos);
1784705a1ae3SPeter Collingbourne 
17859947c498SPeter Collingbourne   auto V1Elems = ShadowElements.find(V1);
17869947c498SPeter Collingbourne   auto V2Elems = ShadowElements.find(V2);
17879947c498SPeter Collingbourne   if (V1Elems != ShadowElements.end() && V2Elems != ShadowElements.end()) {
17889947c498SPeter Collingbourne     if (std::includes(V1Elems->second.begin(), V1Elems->second.end(),
17899947c498SPeter Collingbourne                       V2Elems->second.begin(), V2Elems->second.end())) {
1790ea981165SJianzhou Zhao       return collapseToPrimitiveShadow(V1, Pos);
17916ff18b08SGeorge Balatsouras     }
17926ff18b08SGeorge Balatsouras     if (std::includes(V2Elems->second.begin(), V2Elems->second.end(),
17939947c498SPeter Collingbourne                       V1Elems->second.begin(), V1Elems->second.end())) {
1794ea981165SJianzhou Zhao       return collapseToPrimitiveShadow(V2, Pos);
17959947c498SPeter Collingbourne     }
17969947c498SPeter Collingbourne   } else if (V1Elems != ShadowElements.end()) {
17979947c498SPeter Collingbourne     if (V1Elems->second.count(V2))
1798ea981165SJianzhou Zhao       return collapseToPrimitiveShadow(V1, Pos);
17999947c498SPeter Collingbourne   } else if (V2Elems != ShadowElements.end()) {
18009947c498SPeter Collingbourne     if (V2Elems->second.count(V1))
1801ea981165SJianzhou Zhao       return collapseToPrimitiveShadow(V2, Pos);
18029947c498SPeter Collingbourne   }
18039947c498SPeter Collingbourne 
1804705a1ae3SPeter Collingbourne   auto Key = std::make_pair(V1, V2);
1805705a1ae3SPeter Collingbourne   if (V1 > V2)
1806705a1ae3SPeter Collingbourne     std::swap(Key.first, Key.second);
1807dad5d958SJianzhou Zhao   CachedShadow &CCS = CachedShadows[Key];
1808705a1ae3SPeter Collingbourne   if (CCS.Block && DT.dominates(CCS.Block, Pos->getParent()))
1809705a1ae3SPeter Collingbourne     return CCS.Shadow;
1810705a1ae3SPeter Collingbourne 
1811ea981165SJianzhou Zhao   // Converts inputs shadows to shadows with primitive types.
1812ea981165SJianzhou Zhao   Value *PV1 = collapseToPrimitiveShadow(V1, Pos);
1813ea981165SJianzhou Zhao   Value *PV2 = collapseToPrimitiveShadow(V2, Pos);
1814ea981165SJianzhou Zhao 
1815e5d5b0c7SPeter Collingbourne   IRBuilder<> IRB(Pos);
1816e2d0b44aSMatt Morehouse   CCS.Block = Pos->getParent();
1817ea981165SJianzhou Zhao   CCS.Shadow = IRB.CreateOr(PV1, PV2);
18189947c498SPeter Collingbourne 
18199947c498SPeter Collingbourne   std::set<Value *> UnionElems;
18209947c498SPeter Collingbourne   if (V1Elems != ShadowElements.end()) {
18219947c498SPeter Collingbourne     UnionElems = V1Elems->second;
18229947c498SPeter Collingbourne   } else {
18239947c498SPeter Collingbourne     UnionElems.insert(V1);
18249947c498SPeter Collingbourne   }
18259947c498SPeter Collingbourne   if (V2Elems != ShadowElements.end()) {
18269947c498SPeter Collingbourne     UnionElems.insert(V2Elems->second.begin(), V2Elems->second.end());
18279947c498SPeter Collingbourne   } else {
18289947c498SPeter Collingbourne     UnionElems.insert(V2);
18299947c498SPeter Collingbourne   }
1830df240b25SPeter Collingbourne   ShadowElements[CCS.Shadow] = std::move(UnionElems);
18319947c498SPeter Collingbourne 
1832df240b25SPeter Collingbourne   return CCS.Shadow;
1833e5d5b0c7SPeter Collingbourne }
1834e5d5b0c7SPeter Collingbourne 
1835e5d5b0c7SPeter Collingbourne // A convenience function which folds the shadows of each of the operands
1836e5d5b0c7SPeter Collingbourne // of the provided instruction Inst, inserting the IR before Inst.  Returns
1837e5d5b0c7SPeter Collingbourne // the computed union Value.
combineOperandShadows(Instruction * Inst)1838e5d5b0c7SPeter Collingbourne Value *DFSanFunction::combineOperandShadows(Instruction *Inst) {
1839e5d5b0c7SPeter Collingbourne   if (Inst->getNumOperands() == 0)
1840a28db8b2SJianzhou Zhao     return DFS.getZeroShadow(Inst);
1841e5d5b0c7SPeter Collingbourne 
1842e5d5b0c7SPeter Collingbourne   Value *Shadow = getShadow(Inst->getOperand(0));
18436ff18b08SGeorge Balatsouras   for (unsigned I = 1, N = Inst->getNumOperands(); I < N; ++I)
18446ff18b08SGeorge Balatsouras     Shadow = combineShadows(Shadow, getShadow(Inst->getOperand(I)), Inst);
18456ff18b08SGeorge Balatsouras 
1846ea981165SJianzhou Zhao   return expandFromPrimitiveShadow(Inst->getType(), Shadow, Inst);
1847e5d5b0c7SPeter Collingbourne }
1848e5d5b0c7SPeter Collingbourne 
visitInstOperands(Instruction & I)18497424efd5SJianzhou Zhao void DFSanVisitor::visitInstOperands(Instruction &I) {
1850e5d5b0c7SPeter Collingbourne   Value *CombinedShadow = DFSF.combineOperandShadows(&I);
1851e5d5b0c7SPeter Collingbourne   DFSF.setShadow(&I, CombinedShadow);
18527424efd5SJianzhou Zhao   visitInstOperandOrigins(I);
18537424efd5SJianzhou Zhao }
18547424efd5SJianzhou Zhao 
combineOrigins(const std::vector<Value * > & Shadows,const std::vector<Value * > & Origins,Instruction * Pos,ConstantInt * Zero)18557424efd5SJianzhou Zhao Value *DFSanFunction::combineOrigins(const std::vector<Value *> &Shadows,
18567424efd5SJianzhou Zhao                                      const std::vector<Value *> &Origins,
18577424efd5SJianzhou Zhao                                      Instruction *Pos, ConstantInt *Zero) {
18587424efd5SJianzhou Zhao   assert(Shadows.size() == Origins.size());
18597424efd5SJianzhou Zhao   size_t Size = Origins.size();
18607424efd5SJianzhou Zhao   if (Size == 0)
18617424efd5SJianzhou Zhao     return DFS.ZeroOrigin;
18627424efd5SJianzhou Zhao   Value *Origin = nullptr;
18637424efd5SJianzhou Zhao   if (!Zero)
18647424efd5SJianzhou Zhao     Zero = DFS.ZeroPrimitiveShadow;
18657424efd5SJianzhou Zhao   for (size_t I = 0; I != Size; ++I) {
18667424efd5SJianzhou Zhao     Value *OpOrigin = Origins[I];
18677424efd5SJianzhou Zhao     Constant *ConstOpOrigin = dyn_cast<Constant>(OpOrigin);
18687424efd5SJianzhou Zhao     if (ConstOpOrigin && ConstOpOrigin->isNullValue())
18697424efd5SJianzhou Zhao       continue;
18707424efd5SJianzhou Zhao     if (!Origin) {
18717424efd5SJianzhou Zhao       Origin = OpOrigin;
18727424efd5SJianzhou Zhao       continue;
18737424efd5SJianzhou Zhao     }
18747424efd5SJianzhou Zhao     Value *OpShadow = Shadows[I];
18757424efd5SJianzhou Zhao     Value *PrimitiveShadow = collapseToPrimitiveShadow(OpShadow, Pos);
18767424efd5SJianzhou Zhao     IRBuilder<> IRB(Pos);
18777424efd5SJianzhou Zhao     Value *Cond = IRB.CreateICmpNE(PrimitiveShadow, Zero);
18787424efd5SJianzhou Zhao     Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
18797424efd5SJianzhou Zhao   }
18807424efd5SJianzhou Zhao   return Origin ? Origin : DFS.ZeroOrigin;
18817424efd5SJianzhou Zhao }
18827424efd5SJianzhou Zhao 
combineOperandOrigins(Instruction * Inst)18837424efd5SJianzhou Zhao Value *DFSanFunction::combineOperandOrigins(Instruction *Inst) {
18847424efd5SJianzhou Zhao   size_t Size = Inst->getNumOperands();
18857424efd5SJianzhou Zhao   std::vector<Value *> Shadows(Size);
18867424efd5SJianzhou Zhao   std::vector<Value *> Origins(Size);
18877424efd5SJianzhou Zhao   for (unsigned I = 0; I != Size; ++I) {
18887424efd5SJianzhou Zhao     Shadows[I] = getShadow(Inst->getOperand(I));
18897424efd5SJianzhou Zhao     Origins[I] = getOrigin(Inst->getOperand(I));
18907424efd5SJianzhou Zhao   }
18917424efd5SJianzhou Zhao   return combineOrigins(Shadows, Origins, Inst);
18927424efd5SJianzhou Zhao }
18937424efd5SJianzhou Zhao 
visitInstOperandOrigins(Instruction & I)18947424efd5SJianzhou Zhao void DFSanVisitor::visitInstOperandOrigins(Instruction &I) {
18957424efd5SJianzhou Zhao   if (!DFSF.DFS.shouldTrackOrigins())
18967424efd5SJianzhou Zhao     return;
18977424efd5SJianzhou Zhao   Value *CombinedOrigin = DFSF.combineOperandOrigins(&I);
18987424efd5SJianzhou Zhao   DFSF.setOrigin(&I, CombinedOrigin);
1899e5d5b0c7SPeter Collingbourne }
1900e5d5b0c7SPeter Collingbourne 
getShadowAlign(Align InstAlignment)1901c88fedefSJianzhou Zhao Align DFSanFunction::getShadowAlign(Align InstAlignment) {
1902c88fedefSJianzhou Zhao   const Align Alignment = ClPreserveAlignment ? InstAlignment : Align(1);
1903c88fedefSJianzhou Zhao   return Align(Alignment.value() * DFS.ShadowWidthBytes);
1904c88fedefSJianzhou Zhao }
1905c88fedefSJianzhou Zhao 
getOriginAlign(Align InstAlignment)1906d866b9c9SJianzhou Zhao Align DFSanFunction::getOriginAlign(Align InstAlignment) {
1907d866b9c9SJianzhou Zhao   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
1908ac4c1760SJianzhou Zhao   return Align(std::max(MinOriginAlignment, Alignment));
1909d866b9c9SJianzhou Zhao }
1910d866b9c9SJianzhou Zhao 
isLookupTableConstant(Value * P)19115748219fSAndrew Browne bool DFSanFunction::isLookupTableConstant(Value *P) {
19125748219fSAndrew Browne   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P->stripPointerCasts()))
19135748219fSAndrew Browne     if (GV->isConstant() && GV->hasName())
19145748219fSAndrew Browne       return DFS.CombineTaintLookupTableNames.count(GV->getName());
19155748219fSAndrew Browne 
19165748219fSAndrew Browne   return false;
19175748219fSAndrew Browne }
19185748219fSAndrew Browne 
useCallbackLoadLabelAndOrigin(uint64_t Size,Align InstAlignment)1919d866b9c9SJianzhou Zhao bool DFSanFunction::useCallbackLoadLabelAndOrigin(uint64_t Size,
1920d866b9c9SJianzhou Zhao                                                   Align InstAlignment) {
19217fdf2709SJianzhou Zhao   // When enabling tracking load instructions, we always use
19227fdf2709SJianzhou Zhao   // __dfsan_load_label_and_origin to reduce code size.
19237fdf2709SJianzhou Zhao   if (ClTrackOrigins == 2)
19247fdf2709SJianzhou Zhao     return true;
19257fdf2709SJianzhou Zhao 
1926d866b9c9SJianzhou Zhao   assert(Size != 0);
1927d866b9c9SJianzhou Zhao   // * if Size == 1, it is sufficient to load its origin aligned at 4.
1928d866b9c9SJianzhou Zhao   // * if Size == 2, we assume most cases Addr % 2 == 0, so it is sufficient to
1929d866b9c9SJianzhou Zhao   //   load its origin aligned at 4. If not, although origins may be lost, it
1930d866b9c9SJianzhou Zhao   //   should not happen very often.
1931d866b9c9SJianzhou Zhao   // * if align >= 4, Addr must be aligned to 4, otherwise it is UB. When
1932d866b9c9SJianzhou Zhao   //   Size % 4 == 0, it is more efficient to load origins without callbacks.
1933d866b9c9SJianzhou Zhao   // * Otherwise we use __dfsan_load_label_and_origin.
1934d866b9c9SJianzhou Zhao   // This should ensure that common cases run efficiently.
1935d866b9c9SJianzhou Zhao   if (Size <= 2)
1936d866b9c9SJianzhou Zhao     return false;
1937d866b9c9SJianzhou Zhao 
1938d866b9c9SJianzhou Zhao   const Align Alignment = llvm::assumeAligned(InstAlignment.value());
193979b5280aSGeorge Balatsouras   return Alignment < MinOriginAlignment || !DFS.hasLoadSizeForFastPath(Size);
1940d866b9c9SJianzhou Zhao }
1941d866b9c9SJianzhou Zhao 
loadNextOrigin(Instruction * Pos,Align OriginAlign,Value ** OriginAddr)1942a45fd436SGeorge Balatsouras Value *DataFlowSanitizer::loadNextOrigin(Instruction *Pos, Align OriginAlign,
1943a45fd436SGeorge Balatsouras                                          Value **OriginAddr) {
1944a45fd436SGeorge Balatsouras   IRBuilder<> IRB(Pos);
1945a45fd436SGeorge Balatsouras   *OriginAddr =
1946a45fd436SGeorge Balatsouras       IRB.CreateGEP(OriginTy, *OriginAddr, ConstantInt::get(IntptrTy, 1));
1947a45fd436SGeorge Balatsouras   return IRB.CreateAlignedLoad(OriginTy, *OriginAddr, OriginAlign);
1948a45fd436SGeorge Balatsouras }
1949a45fd436SGeorge Balatsouras 
loadShadowFast(Value * ShadowAddr,Value * OriginAddr,uint64_t Size,Align ShadowAlign,Align OriginAlign,Value * FirstOrigin,Instruction * Pos)19505b4dda55SGeorge Balatsouras std::pair<Value *, Value *> DFSanFunction::loadShadowFast(
1951d866b9c9SJianzhou Zhao     Value *ShadowAddr, Value *OriginAddr, uint64_t Size, Align ShadowAlign,
1952d866b9c9SJianzhou Zhao     Align OriginAlign, Value *FirstOrigin, Instruction *Pos) {
1953d866b9c9SJianzhou Zhao   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
1954d10f173fSGeorge Balatsouras   const uint64_t ShadowSize = Size * DFS.ShadowWidthBytes;
1955d10f173fSGeorge Balatsouras 
1956d10f173fSGeorge Balatsouras   assert(Size >= 4 && "Not large enough load size for fast path!");
1957d10f173fSGeorge Balatsouras 
1958d10f173fSGeorge Balatsouras   // Used for origin tracking.
1959d866b9c9SJianzhou Zhao   std::vector<Value *> Shadows;
1960d866b9c9SJianzhou Zhao   std::vector<Value *> Origins;
1961d10f173fSGeorge Balatsouras 
1962d10f173fSGeorge Balatsouras   // Load instructions in LLVM can have arbitrary byte sizes (e.g., 3, 12, 20)
1963d10f173fSGeorge Balatsouras   // but this function is only used in a subset of cases that make it possible
1964d10f173fSGeorge Balatsouras   // to optimize the instrumentation.
1965d10f173fSGeorge Balatsouras   //
1966d10f173fSGeorge Balatsouras   // Specifically, when the shadow size in bytes (i.e., loaded bytes x shadow
1967d10f173fSGeorge Balatsouras   // per byte) is either:
1968d10f173fSGeorge Balatsouras   // - a multiple of 8  (common)
19695b4dda55SGeorge Balatsouras   // - equal to 4       (only for load32)
1970d10f173fSGeorge Balatsouras   //
1971d10f173fSGeorge Balatsouras   // For the second case, we can fit the wide shadow in a 32-bit integer. In all
1972d10f173fSGeorge Balatsouras   // other cases, we use a 64-bit integer to hold the wide shadow.
1973d10f173fSGeorge Balatsouras   Type *WideShadowTy =
1974d10f173fSGeorge Balatsouras       ShadowSize == 4 ? Type::getInt32Ty(*DFS.Ctx) : Type::getInt64Ty(*DFS.Ctx);
1975d10f173fSGeorge Balatsouras 
19769887fdebSJianzhou Zhao   IRBuilder<> IRB(Pos);
1977d10f173fSGeorge Balatsouras   Value *WideAddr = IRB.CreateBitCast(ShadowAddr, WideShadowTy->getPointerTo());
19789887fdebSJianzhou Zhao   Value *CombinedWideShadow =
1979d10f173fSGeorge Balatsouras       IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
1980d10f173fSGeorge Balatsouras 
1981a45fd436SGeorge Balatsouras   unsigned WideShadowBitWidth = WideShadowTy->getIntegerBitWidth();
1982a45fd436SGeorge Balatsouras   const uint64_t BytesPerWideShadow = WideShadowBitWidth / DFS.ShadowWidthBits;
1983a45fd436SGeorge Balatsouras 
1984a45fd436SGeorge Balatsouras   auto AppendWideShadowAndOrigin = [&](Value *WideShadow, Value *Origin) {
1985a45fd436SGeorge Balatsouras     if (BytesPerWideShadow > 4) {
1986a45fd436SGeorge Balatsouras       assert(BytesPerWideShadow == 8);
1987a45fd436SGeorge Balatsouras       // The wide shadow relates to two origin pointers: one for the first four
1988a45fd436SGeorge Balatsouras       // application bytes, and one for the latest four. We use a left shift to
1989a45fd436SGeorge Balatsouras       // get just the shadow bytes that correspond to the first origin pointer,
1990a45fd436SGeorge Balatsouras       // and then the entire shadow for the second origin pointer (which will be
1991a45fd436SGeorge Balatsouras       // chosen by combineOrigins() iff the least-significant half of the wide
1992a45fd436SGeorge Balatsouras       // shadow was empty but the other half was not).
1993a45fd436SGeorge Balatsouras       Value *WideShadowLo = IRB.CreateShl(
1994a45fd436SGeorge Balatsouras           WideShadow, ConstantInt::get(WideShadowTy, WideShadowBitWidth / 2));
1995a45fd436SGeorge Balatsouras       Shadows.push_back(WideShadow);
1996a45fd436SGeorge Balatsouras       Origins.push_back(DFS.loadNextOrigin(Pos, OriginAlign, &OriginAddr));
1997a45fd436SGeorge Balatsouras 
1998a45fd436SGeorge Balatsouras       Shadows.push_back(WideShadowLo);
1999a45fd436SGeorge Balatsouras       Origins.push_back(Origin);
2000a45fd436SGeorge Balatsouras     } else {
2001a45fd436SGeorge Balatsouras       Shadows.push_back(WideShadow);
2002a45fd436SGeorge Balatsouras       Origins.push_back(Origin);
2003d866b9c9SJianzhou Zhao     }
2004a45fd436SGeorge Balatsouras   };
2005a45fd436SGeorge Balatsouras 
2006a45fd436SGeorge Balatsouras   if (ShouldTrackOrigins)
2007a45fd436SGeorge Balatsouras     AppendWideShadowAndOrigin(CombinedWideShadow, FirstOrigin);
2008d10f173fSGeorge Balatsouras 
2009d10f173fSGeorge Balatsouras   // First OR all the WideShadows (i.e., 64bit or 32bit shadow chunks) linearly;
2010d10f173fSGeorge Balatsouras   // then OR individual shadows within the combined WideShadow by binary ORing.
2011d10f173fSGeorge Balatsouras   // This is fewer instructions than ORing shadows individually, since it
2012d10f173fSGeorge Balatsouras   // needs logN shift/or instructions (N being the bytes of the combined wide
2013d10f173fSGeorge Balatsouras   // shadow).
2014d10f173fSGeorge Balatsouras   for (uint64_t ByteOfs = BytesPerWideShadow; ByteOfs < Size;
2015d10f173fSGeorge Balatsouras        ByteOfs += BytesPerWideShadow) {
2016d10f173fSGeorge Balatsouras     WideAddr = IRB.CreateGEP(WideShadowTy, WideAddr,
20179887fdebSJianzhou Zhao                              ConstantInt::get(DFS.IntptrTy, 1));
20189887fdebSJianzhou Zhao     Value *NextWideShadow =
2019d10f173fSGeorge Balatsouras         IRB.CreateAlignedLoad(WideShadowTy, WideAddr, ShadowAlign);
20209887fdebSJianzhou Zhao     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, NextWideShadow);
2021d866b9c9SJianzhou Zhao     if (ShouldTrackOrigins) {
2022a45fd436SGeorge Balatsouras       Value *NextOrigin = DFS.loadNextOrigin(Pos, OriginAlign, &OriginAddr);
2023a45fd436SGeorge Balatsouras       AppendWideShadowAndOrigin(NextWideShadow, NextOrigin);
2024d866b9c9SJianzhou Zhao     }
20259887fdebSJianzhou Zhao   }
2026d10f173fSGeorge Balatsouras   for (unsigned Width = WideShadowBitWidth / 2; Width >= DFS.ShadowWidthBits;
2027d10f173fSGeorge Balatsouras        Width >>= 1) {
20289887fdebSJianzhou Zhao     Value *ShrShadow = IRB.CreateLShr(CombinedWideShadow, Width);
20299887fdebSJianzhou Zhao     CombinedWideShadow = IRB.CreateOr(CombinedWideShadow, ShrShadow);
20309887fdebSJianzhou Zhao   }
2031d866b9c9SJianzhou Zhao   return {IRB.CreateTrunc(CombinedWideShadow, DFS.PrimitiveShadowTy),
2032d866b9c9SJianzhou Zhao           ShouldTrackOrigins
2033d866b9c9SJianzhou Zhao               ? combineOrigins(Shadows, Origins, Pos,
2034d866b9c9SJianzhou Zhao                                ConstantInt::getSigned(IRB.getInt64Ty(), 0))
2035d866b9c9SJianzhou Zhao               : DFS.ZeroOrigin};
20369887fdebSJianzhou Zhao }
20379887fdebSJianzhou Zhao 
loadShadowOriginSansLoadTracking(Value * Addr,uint64_t Size,Align InstAlignment,Instruction * Pos)20387fdf2709SJianzhou Zhao std::pair<Value *, Value *> DFSanFunction::loadShadowOriginSansLoadTracking(
20397fdf2709SJianzhou Zhao     Value *Addr, uint64_t Size, Align InstAlignment, Instruction *Pos) {
2040d866b9c9SJianzhou Zhao   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins();
2041d866b9c9SJianzhou Zhao 
2042d866b9c9SJianzhou Zhao   // Non-escaped loads.
2043e5d5b0c7SPeter Collingbourne   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2044d866b9c9SJianzhou Zhao     const auto SI = AllocaShadowMap.find(AI);
2045d866b9c9SJianzhou Zhao     if (SI != AllocaShadowMap.end()) {
2046e5d5b0c7SPeter Collingbourne       IRBuilder<> IRB(Pos);
2047d866b9c9SJianzhou Zhao       Value *ShadowLI = IRB.CreateLoad(DFS.PrimitiveShadowTy, SI->second);
2048d866b9c9SJianzhou Zhao       const auto OI = AllocaOriginMap.find(AI);
2049d866b9c9SJianzhou Zhao       assert(!ShouldTrackOrigins || OI != AllocaOriginMap.end());
2050d866b9c9SJianzhou Zhao       return {ShadowLI, ShouldTrackOrigins
2051d866b9c9SJianzhou Zhao                             ? IRB.CreateLoad(DFS.OriginTy, OI->second)
2052d866b9c9SJianzhou Zhao                             : nullptr};
2053e5d5b0c7SPeter Collingbourne     }
2054e5d5b0c7SPeter Collingbourne   }
2055e5d5b0c7SPeter Collingbourne 
2056d866b9c9SJianzhou Zhao   // Load from constant addresses.
205771e8c6f2SBjorn Pettersson   SmallVector<const Value *, 2> Objs;
2058b0eb40caSVitaly Buka   getUnderlyingObjects(Addr, Objs);
2059e5d5b0c7SPeter Collingbourne   bool AllConstants = true;
206071e8c6f2SBjorn Pettersson   for (const Value *Obj : Objs) {
2061135f735aSBenjamin Kramer     if (isa<Function>(Obj) || isa<BlockAddress>(Obj))
2062e5d5b0c7SPeter Collingbourne       continue;
2063135f735aSBenjamin Kramer     if (isa<GlobalVariable>(Obj) && cast<GlobalVariable>(Obj)->isConstant())
2064e5d5b0c7SPeter Collingbourne       continue;
2065e5d5b0c7SPeter Collingbourne 
2066e5d5b0c7SPeter Collingbourne     AllConstants = false;
2067e5d5b0c7SPeter Collingbourne     break;
2068e5d5b0c7SPeter Collingbourne   }
2069e5d5b0c7SPeter Collingbourne   if (AllConstants)
2070d866b9c9SJianzhou Zhao     return {DFS.ZeroPrimitiveShadow,
2071d866b9c9SJianzhou Zhao             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2072e5d5b0c7SPeter Collingbourne 
2073d866b9c9SJianzhou Zhao   if (Size == 0)
2074d866b9c9SJianzhou Zhao     return {DFS.ZeroPrimitiveShadow,
2075d866b9c9SJianzhou Zhao             ShouldTrackOrigins ? DFS.ZeroOrigin : nullptr};
2076d866b9c9SJianzhou Zhao 
2077d866b9c9SJianzhou Zhao   // Use callback to load if this is not an optimizable case for origin
2078d866b9c9SJianzhou Zhao   // tracking.
2079d866b9c9SJianzhou Zhao   if (ShouldTrackOrigins &&
2080d866b9c9SJianzhou Zhao       useCallbackLoadLabelAndOrigin(Size, InstAlignment)) {
2081d866b9c9SJianzhou Zhao     IRBuilder<> IRB(Pos);
2082d866b9c9SJianzhou Zhao     CallInst *Call =
2083d866b9c9SJianzhou Zhao         IRB.CreateCall(DFS.DFSanLoadLabelAndOriginFn,
2084d866b9c9SJianzhou Zhao                        {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2085d866b9c9SJianzhou Zhao                         ConstantInt::get(DFS.IntptrTy, Size)});
20863f4d00bcSArthur Eubanks     Call->addRetAttr(Attribute::ZExt);
2087d866b9c9SJianzhou Zhao     return {IRB.CreateTrunc(IRB.CreateLShr(Call, DFS.OriginWidthBits),
2088d866b9c9SJianzhou Zhao                             DFS.PrimitiveShadowTy),
2089d866b9c9SJianzhou Zhao             IRB.CreateTrunc(Call, DFS.OriginTy)};
2090d866b9c9SJianzhou Zhao   }
2091d866b9c9SJianzhou Zhao 
2092d866b9c9SJianzhou Zhao   // Other cases that support loading shadows or origins in a fast way.
2093d866b9c9SJianzhou Zhao   Value *ShadowAddr, *OriginAddr;
2094d866b9c9SJianzhou Zhao   std::tie(ShadowAddr, OriginAddr) =
2095d866b9c9SJianzhou Zhao       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2096d866b9c9SJianzhou Zhao 
2097d866b9c9SJianzhou Zhao   const Align ShadowAlign = getShadowAlign(InstAlignment);
2098d866b9c9SJianzhou Zhao   const Align OriginAlign = getOriginAlign(InstAlignment);
2099d866b9c9SJianzhou Zhao   Value *Origin = nullptr;
2100d866b9c9SJianzhou Zhao   if (ShouldTrackOrigins) {
2101d866b9c9SJianzhou Zhao     IRBuilder<> IRB(Pos);
2102d866b9c9SJianzhou Zhao     Origin = IRB.CreateAlignedLoad(DFS.OriginTy, OriginAddr, OriginAlign);
2103d866b9c9SJianzhou Zhao   }
2104d866b9c9SJianzhou Zhao 
2105d10f173fSGeorge Balatsouras   // When the byte size is small enough, we can load the shadow directly with
2106d10f173fSGeorge Balatsouras   // just a few instructions.
2107e5d5b0c7SPeter Collingbourne   switch (Size) {
2108e5d5b0c7SPeter Collingbourne   case 1: {
2109bd726d27SJianzhou Zhao     LoadInst *LI = new LoadInst(DFS.PrimitiveShadowTy, ShadowAddr, "", Pos);
2110279fa8e0SGuillaume Chatelet     LI->setAlignment(ShadowAlign);
2111d866b9c9SJianzhou Zhao     return {LI, Origin};
2112e5d5b0c7SPeter Collingbourne   }
2113e5d5b0c7SPeter Collingbourne   case 2: {
2114e5d5b0c7SPeter Collingbourne     IRBuilder<> IRB(Pos);
2115bd726d27SJianzhou Zhao     Value *ShadowAddr1 = IRB.CreateGEP(DFS.PrimitiveShadowTy, ShadowAddr,
211693c5444fSDavid Blaikie                                        ConstantInt::get(DFS.IntptrTy, 1));
2117d866b9c9SJianzhou Zhao     Value *Load =
2118d866b9c9SJianzhou Zhao         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr, ShadowAlign);
2119d866b9c9SJianzhou Zhao     Value *Load1 =
2120d866b9c9SJianzhou Zhao         IRB.CreateAlignedLoad(DFS.PrimitiveShadowTy, ShadowAddr1, ShadowAlign);
2121d866b9c9SJianzhou Zhao     return {combineShadows(Load, Load1, Pos), Origin};
2122e5d5b0c7SPeter Collingbourne   }
2123e5d5b0c7SPeter Collingbourne   }
212479b5280aSGeorge Balatsouras   bool HasSizeForFastPath = DFS.hasLoadSizeForFastPath(Size);
2125e2d0b44aSMatt Morehouse 
21265b4dda55SGeorge Balatsouras   if (HasSizeForFastPath)
21275b4dda55SGeorge Balatsouras     return loadShadowFast(ShadowAddr, OriginAddr, Size, ShadowAlign,
2128d866b9c9SJianzhou Zhao                           OriginAlign, Origin, Pos);
2129e5d5b0c7SPeter Collingbourne 
2130e5d5b0c7SPeter Collingbourne   IRBuilder<> IRB(Pos);
2131ff6409d0SDavid Blaikie   CallInst *FallbackCall = IRB.CreateCall(
21325b4dda55SGeorge Balatsouras       DFS.DFSanUnionLoadFn, {ShadowAddr, ConstantInt::get(DFS.IntptrTy, Size)});
21333f4d00bcSArthur Eubanks   FallbackCall->addRetAttr(Attribute::ZExt);
2134d866b9c9SJianzhou Zhao   return {FallbackCall, Origin};
2135e5d5b0c7SPeter Collingbourne }
2136e5d5b0c7SPeter Collingbourne 
loadShadowOrigin(Value * Addr,uint64_t Size,Align InstAlignment,Instruction * Pos)21377fdf2709SJianzhou Zhao std::pair<Value *, Value *> DFSanFunction::loadShadowOrigin(Value *Addr,
21387fdf2709SJianzhou Zhao                                                             uint64_t Size,
21397fdf2709SJianzhou Zhao                                                             Align InstAlignment,
21407fdf2709SJianzhou Zhao                                                             Instruction *Pos) {
21417fdf2709SJianzhou Zhao   Value *PrimitiveShadow, *Origin;
21427fdf2709SJianzhou Zhao   std::tie(PrimitiveShadow, Origin) =
21437fdf2709SJianzhou Zhao       loadShadowOriginSansLoadTracking(Addr, Size, InstAlignment, Pos);
21447fdf2709SJianzhou Zhao   if (DFS.shouldTrackOrigins()) {
21457fdf2709SJianzhou Zhao     if (ClTrackOrigins == 2) {
21467fdf2709SJianzhou Zhao       IRBuilder<> IRB(Pos);
21477fdf2709SJianzhou Zhao       auto *ConstantShadow = dyn_cast<Constant>(PrimitiveShadow);
21487fdf2709SJianzhou Zhao       if (!ConstantShadow || !ConstantShadow->isZeroValue())
21497fdf2709SJianzhou Zhao         Origin = updateOriginIfTainted(PrimitiveShadow, Origin, IRB);
21507fdf2709SJianzhou Zhao     }
21517fdf2709SJianzhou Zhao   }
21527fdf2709SJianzhou Zhao   return {PrimitiveShadow, Origin};
21537fdf2709SJianzhou Zhao }
21547fdf2709SJianzhou Zhao 
addAcquireOrdering(AtomicOrdering AO)2155c88fedefSJianzhou Zhao static AtomicOrdering addAcquireOrdering(AtomicOrdering AO) {
2156c88fedefSJianzhou Zhao   switch (AO) {
2157c88fedefSJianzhou Zhao   case AtomicOrdering::NotAtomic:
2158c88fedefSJianzhou Zhao     return AtomicOrdering::NotAtomic;
2159c88fedefSJianzhou Zhao   case AtomicOrdering::Unordered:
2160c88fedefSJianzhou Zhao   case AtomicOrdering::Monotonic:
2161c88fedefSJianzhou Zhao   case AtomicOrdering::Acquire:
2162c88fedefSJianzhou Zhao     return AtomicOrdering::Acquire;
2163c88fedefSJianzhou Zhao   case AtomicOrdering::Release:
2164c88fedefSJianzhou Zhao   case AtomicOrdering::AcquireRelease:
2165c88fedefSJianzhou Zhao     return AtomicOrdering::AcquireRelease;
2166c88fedefSJianzhou Zhao   case AtomicOrdering::SequentiallyConsistent:
2167c88fedefSJianzhou Zhao     return AtomicOrdering::SequentiallyConsistent;
2168c88fedefSJianzhou Zhao   }
2169c88fedefSJianzhou Zhao   llvm_unreachable("Unknown ordering");
2170c88fedefSJianzhou Zhao }
2171c88fedefSJianzhou Zhao 
StripPointerGEPsAndCasts(Value * V)21725748219fSAndrew Browne Value *StripPointerGEPsAndCasts(Value *V) {
21735748219fSAndrew Browne   if (!V->getType()->isPointerTy())
21745748219fSAndrew Browne     return V;
21755748219fSAndrew Browne 
21765748219fSAndrew Browne   // DFSan pass should be running on valid IR, but we'll
21775748219fSAndrew Browne   // keep a seen set to ensure there are no issues.
21785748219fSAndrew Browne   SmallPtrSet<const Value *, 4> Visited;
21795748219fSAndrew Browne   Visited.insert(V);
21805748219fSAndrew Browne   do {
21815748219fSAndrew Browne     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
21825748219fSAndrew Browne       V = GEP->getPointerOperand();
21835748219fSAndrew Browne     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
21845748219fSAndrew Browne       V = cast<Operator>(V)->getOperand(0);
21855748219fSAndrew Browne       if (!V->getType()->isPointerTy())
21865748219fSAndrew Browne         return V;
21875748219fSAndrew Browne     } else if (isa<GlobalAlias>(V)) {
21885748219fSAndrew Browne       V = cast<GlobalAlias>(V)->getAliasee();
21895748219fSAndrew Browne     }
21905748219fSAndrew Browne   } while (Visited.insert(V).second);
21915748219fSAndrew Browne 
21925748219fSAndrew Browne   return V;
21935748219fSAndrew Browne }
21945748219fSAndrew Browne 
visitLoadInst(LoadInst & LI)2195e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitLoadInst(LoadInst &LI) {
2196a28d91d8SMehdi Amini   auto &DL = LI.getModule()->getDataLayout();
2197a28d91d8SMehdi Amini   uint64_t Size = DL.getTypeStoreSize(LI.getType());
2198142fdff0SPeter Collingbourne   if (Size == 0) {
2199a28db8b2SJianzhou Zhao     DFSF.setShadow(&LI, DFSF.DFS.getZeroShadow(&LI));
2200d866b9c9SJianzhou Zhao     DFSF.setOrigin(&LI, DFSF.DFS.ZeroOrigin);
2201142fdff0SPeter Collingbourne     return;
2202142fdff0SPeter Collingbourne   }
2203142fdff0SPeter Collingbourne 
2204c88fedefSJianzhou Zhao   // When an application load is atomic, increase atomic ordering between
2205c88fedefSJianzhou Zhao   // atomic application loads and stores to ensure happen-before order; load
2206c88fedefSJianzhou Zhao   // shadow data after application data; store zero shadow data before
2207c88fedefSJianzhou Zhao   // application data. This ensure shadow loads return either labels of the
2208c88fedefSJianzhou Zhao   // initial application data or zeros.
2209c88fedefSJianzhou Zhao   if (LI.isAtomic())
2210c88fedefSJianzhou Zhao     LI.setOrdering(addAcquireOrdering(LI.getOrdering()));
2211c88fedefSJianzhou Zhao 
2212c88fedefSJianzhou Zhao   Instruction *Pos = LI.isAtomic() ? LI.getNextNode() : &LI;
2213d866b9c9SJianzhou Zhao   std::vector<Value *> Shadows;
2214d866b9c9SJianzhou Zhao   std::vector<Value *> Origins;
2215d866b9c9SJianzhou Zhao   Value *PrimitiveShadow, *Origin;
2216d866b9c9SJianzhou Zhao   std::tie(PrimitiveShadow, Origin) =
2217d866b9c9SJianzhou Zhao       DFSF.loadShadowOrigin(LI.getPointerOperand(), Size, LI.getAlign(), Pos);
2218d866b9c9SJianzhou Zhao   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
2219d866b9c9SJianzhou Zhao   if (ShouldTrackOrigins) {
2220d866b9c9SJianzhou Zhao     Shadows.push_back(PrimitiveShadow);
2221d866b9c9SJianzhou Zhao     Origins.push_back(Origin);
2222d866b9c9SJianzhou Zhao   }
22235748219fSAndrew Browne   if (ClCombinePointerLabelsOnLoad ||
22245748219fSAndrew Browne       DFSF.isLookupTableConstant(
22255748219fSAndrew Browne           StripPointerGEPsAndCasts(LI.getPointerOperand()))) {
2226e5d5b0c7SPeter Collingbourne     Value *PtrShadow = DFSF.getShadow(LI.getPointerOperand());
2227c88fedefSJianzhou Zhao     PrimitiveShadow = DFSF.combineShadows(PrimitiveShadow, PtrShadow, Pos);
2228d866b9c9SJianzhou Zhao     if (ShouldTrackOrigins) {
2229d866b9c9SJianzhou Zhao       Shadows.push_back(PtrShadow);
2230d866b9c9SJianzhou Zhao       Origins.push_back(DFSF.getOrigin(LI.getPointerOperand()));
2231d866b9c9SJianzhou Zhao     }
22320be79e1aSPeter Collingbourne   }
2233ea981165SJianzhou Zhao   if (!DFSF.DFS.isZeroShadow(PrimitiveShadow))
2234ea981165SJianzhou Zhao     DFSF.NonZeroChecks.push_back(PrimitiveShadow);
2235444c59e2SPeter Collingbourne 
2236ea981165SJianzhou Zhao   Value *Shadow =
2237c88fedefSJianzhou Zhao       DFSF.expandFromPrimitiveShadow(LI.getType(), PrimitiveShadow, Pos);
22380be79e1aSPeter Collingbourne   DFSF.setShadow(&LI, Shadow);
2239d866b9c9SJianzhou Zhao 
2240d866b9c9SJianzhou Zhao   if (ShouldTrackOrigins) {
2241d866b9c9SJianzhou Zhao     DFSF.setOrigin(&LI, DFSF.combineOrigins(Shadows, Origins, Pos));
2242d866b9c9SJianzhou Zhao   }
2243d866b9c9SJianzhou Zhao 
224452f889abSMatt Morehouse   if (ClEventCallbacks) {
2245c88fedefSJianzhou Zhao     IRBuilder<> IRB(Pos);
224606c9b4aaSJianzhou Zhao     Value *Addr8 = IRB.CreateBitCast(LI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2247ea981165SJianzhou Zhao     IRB.CreateCall(DFSF.DFS.DFSanLoadCallbackFn, {PrimitiveShadow, Addr8});
224852f889abSMatt Morehouse   }
2249e5d5b0c7SPeter Collingbourne }
2250e5d5b0c7SPeter Collingbourne 
updateOriginIfTainted(Value * Shadow,Value * Origin,IRBuilder<> & IRB)22517fdf2709SJianzhou Zhao Value *DFSanFunction::updateOriginIfTainted(Value *Shadow, Value *Origin,
22527fdf2709SJianzhou Zhao                                             IRBuilder<> &IRB) {
22537fdf2709SJianzhou Zhao   assert(DFS.shouldTrackOrigins());
225447211fa8SArthur Eubanks   return IRB.CreateCall(DFS.DFSanChainOriginIfTaintedFn, {Shadow, Origin});
22557fdf2709SJianzhou Zhao }
22567fdf2709SJianzhou Zhao 
updateOrigin(Value * V,IRBuilder<> & IRB)2257db7fe6cdSJianzhou Zhao Value *DFSanFunction::updateOrigin(Value *V, IRBuilder<> &IRB) {
2258db7fe6cdSJianzhou Zhao   if (!DFS.shouldTrackOrigins())
2259db7fe6cdSJianzhou Zhao     return V;
226047211fa8SArthur Eubanks   return IRB.CreateCall(DFS.DFSanChainOriginFn, V);
2261db7fe6cdSJianzhou Zhao }
2262db7fe6cdSJianzhou Zhao 
originToIntptr(IRBuilder<> & IRB,Value * Origin)2263db7fe6cdSJianzhou Zhao Value *DFSanFunction::originToIntptr(IRBuilder<> &IRB, Value *Origin) {
2264db7fe6cdSJianzhou Zhao   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2265db7fe6cdSJianzhou Zhao   const DataLayout &DL = F->getParent()->getDataLayout();
2266db7fe6cdSJianzhou Zhao   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2267db7fe6cdSJianzhou Zhao   if (IntptrSize == OriginSize)
2268db7fe6cdSJianzhou Zhao     return Origin;
2269db7fe6cdSJianzhou Zhao   assert(IntptrSize == OriginSize * 2);
2270db7fe6cdSJianzhou Zhao   Origin = IRB.CreateIntCast(Origin, DFS.IntptrTy, /* isSigned */ false);
2271db7fe6cdSJianzhou Zhao   return IRB.CreateOr(Origin, IRB.CreateShl(Origin, OriginSize * 8));
2272db7fe6cdSJianzhou Zhao }
2273db7fe6cdSJianzhou Zhao 
paintOrigin(IRBuilder<> & IRB,Value * Origin,Value * StoreOriginAddr,uint64_t StoreOriginSize,Align Alignment)2274db7fe6cdSJianzhou Zhao void DFSanFunction::paintOrigin(IRBuilder<> &IRB, Value *Origin,
2275db7fe6cdSJianzhou Zhao                                 Value *StoreOriginAddr,
2276db7fe6cdSJianzhou Zhao                                 uint64_t StoreOriginSize, Align Alignment) {
2277db7fe6cdSJianzhou Zhao   const unsigned OriginSize = DataFlowSanitizer::OriginWidthBytes;
2278db7fe6cdSJianzhou Zhao   const DataLayout &DL = F->getParent()->getDataLayout();
2279db7fe6cdSJianzhou Zhao   const Align IntptrAlignment = DL.getABITypeAlign(DFS.IntptrTy);
2280db7fe6cdSJianzhou Zhao   unsigned IntptrSize = DL.getTypeStoreSize(DFS.IntptrTy);
2281db7fe6cdSJianzhou Zhao   assert(IntptrAlignment >= MinOriginAlignment);
2282db7fe6cdSJianzhou Zhao   assert(IntptrSize >= OriginSize);
2283db7fe6cdSJianzhou Zhao 
2284db7fe6cdSJianzhou Zhao   unsigned Ofs = 0;
2285db7fe6cdSJianzhou Zhao   Align CurrentAlignment = Alignment;
2286db7fe6cdSJianzhou Zhao   if (Alignment >= IntptrAlignment && IntptrSize > OriginSize) {
2287db7fe6cdSJianzhou Zhao     Value *IntptrOrigin = originToIntptr(IRB, Origin);
2288db7fe6cdSJianzhou Zhao     Value *IntptrStoreOriginPtr = IRB.CreatePointerCast(
2289db7fe6cdSJianzhou Zhao         StoreOriginAddr, PointerType::get(DFS.IntptrTy, 0));
2290db7fe6cdSJianzhou Zhao     for (unsigned I = 0; I < StoreOriginSize / IntptrSize; ++I) {
2291db7fe6cdSJianzhou Zhao       Value *Ptr =
2292db7fe6cdSJianzhou Zhao           I ? IRB.CreateConstGEP1_32(DFS.IntptrTy, IntptrStoreOriginPtr, I)
2293db7fe6cdSJianzhou Zhao             : IntptrStoreOriginPtr;
2294db7fe6cdSJianzhou Zhao       IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
2295db7fe6cdSJianzhou Zhao       Ofs += IntptrSize / OriginSize;
2296db7fe6cdSJianzhou Zhao       CurrentAlignment = IntptrAlignment;
2297db7fe6cdSJianzhou Zhao     }
2298db7fe6cdSJianzhou Zhao   }
2299db7fe6cdSJianzhou Zhao 
2300db7fe6cdSJianzhou Zhao   for (unsigned I = Ofs; I < (StoreOriginSize + OriginSize - 1) / OriginSize;
2301db7fe6cdSJianzhou Zhao        ++I) {
2302db7fe6cdSJianzhou Zhao     Value *GEP = I ? IRB.CreateConstGEP1_32(DFS.OriginTy, StoreOriginAddr, I)
2303db7fe6cdSJianzhou Zhao                    : StoreOriginAddr;
2304db7fe6cdSJianzhou Zhao     IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
2305db7fe6cdSJianzhou Zhao     CurrentAlignment = MinOriginAlignment;
2306db7fe6cdSJianzhou Zhao   }
2307db7fe6cdSJianzhou Zhao }
2308db7fe6cdSJianzhou Zhao 
convertToBool(Value * V,IRBuilder<> & IRB,const Twine & Name)2309db7fe6cdSJianzhou Zhao Value *DFSanFunction::convertToBool(Value *V, IRBuilder<> &IRB,
2310db7fe6cdSJianzhou Zhao                                     const Twine &Name) {
2311db7fe6cdSJianzhou Zhao   Type *VTy = V->getType();
2312db7fe6cdSJianzhou Zhao   assert(VTy->isIntegerTy());
2313db7fe6cdSJianzhou Zhao   if (VTy->getIntegerBitWidth() == 1)
2314db7fe6cdSJianzhou Zhao     // Just converting a bool to a bool, so do nothing.
2315db7fe6cdSJianzhou Zhao     return V;
2316db7fe6cdSJianzhou Zhao   return IRB.CreateICmpNE(V, ConstantInt::get(VTy, 0), Name);
2317db7fe6cdSJianzhou Zhao }
2318db7fe6cdSJianzhou Zhao 
storeOrigin(Instruction * Pos,Value * Addr,uint64_t Size,Value * Shadow,Value * Origin,Value * StoreOriginAddr,Align InstAlignment)2319db7fe6cdSJianzhou Zhao void DFSanFunction::storeOrigin(Instruction *Pos, Value *Addr, uint64_t Size,
2320db7fe6cdSJianzhou Zhao                                 Value *Shadow, Value *Origin,
2321db7fe6cdSJianzhou Zhao                                 Value *StoreOriginAddr, Align InstAlignment) {
2322db7fe6cdSJianzhou Zhao   // Do not write origins for zero shadows because we do not trace origins for
2323db7fe6cdSJianzhou Zhao   // untainted sinks.
2324db7fe6cdSJianzhou Zhao   const Align OriginAlignment = getOriginAlign(InstAlignment);
2325db7fe6cdSJianzhou Zhao   Value *CollapsedShadow = collapseToPrimitiveShadow(Shadow, Pos);
2326db7fe6cdSJianzhou Zhao   IRBuilder<> IRB(Pos);
2327db7fe6cdSJianzhou Zhao   if (auto *ConstantShadow = dyn_cast<Constant>(CollapsedShadow)) {
2328db7fe6cdSJianzhou Zhao     if (!ConstantShadow->isZeroValue())
2329db7fe6cdSJianzhou Zhao       paintOrigin(IRB, updateOrigin(Origin, IRB), StoreOriginAddr, Size,
2330db7fe6cdSJianzhou Zhao                   OriginAlignment);
2331db7fe6cdSJianzhou Zhao     return;
2332db7fe6cdSJianzhou Zhao   }
2333db7fe6cdSJianzhou Zhao 
2334db7fe6cdSJianzhou Zhao   if (shouldInstrumentWithCall()) {
233547211fa8SArthur Eubanks     IRB.CreateCall(DFS.DFSanMaybeStoreOriginFn,
2336db7fe6cdSJianzhou Zhao                    {CollapsedShadow,
2337db7fe6cdSJianzhou Zhao                     IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
2338db7fe6cdSJianzhou Zhao                     ConstantInt::get(DFS.IntptrTy, Size), Origin});
2339db7fe6cdSJianzhou Zhao   } else {
2340db7fe6cdSJianzhou Zhao     Value *Cmp = convertToBool(CollapsedShadow, IRB, "_dfscmp");
2341db7fe6cdSJianzhou Zhao     Instruction *CheckTerm = SplitBlockAndInsertIfThen(
2342db7fe6cdSJianzhou Zhao         Cmp, &*IRB.GetInsertPoint(), false, DFS.OriginStoreWeights, &DT);
2343db7fe6cdSJianzhou Zhao     IRBuilder<> IRBNew(CheckTerm);
2344db7fe6cdSJianzhou Zhao     paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), StoreOriginAddr, Size,
2345db7fe6cdSJianzhou Zhao                 OriginAlignment);
2346db7fe6cdSJianzhou Zhao     ++NumOriginStores;
2347db7fe6cdSJianzhou Zhao   }
2348db7fe6cdSJianzhou Zhao }
2349db7fe6cdSJianzhou Zhao 
storeZeroPrimitiveShadow(Value * Addr,uint64_t Size,Align ShadowAlign,Instruction * Pos)2350c88fedefSJianzhou Zhao void DFSanFunction::storeZeroPrimitiveShadow(Value *Addr, uint64_t Size,
2351c88fedefSJianzhou Zhao                                              Align ShadowAlign,
2352c88fedefSJianzhou Zhao                                              Instruction *Pos) {
2353c88fedefSJianzhou Zhao   IRBuilder<> IRB(Pos);
2354c88fedefSJianzhou Zhao   IntegerType *ShadowTy =
2355c88fedefSJianzhou Zhao       IntegerType::get(*DFS.Ctx, Size * DFS.ShadowWidthBits);
2356c88fedefSJianzhou Zhao   Value *ExtZeroShadow = ConstantInt::get(ShadowTy, 0);
2357c88fedefSJianzhou Zhao   Value *ShadowAddr = DFS.getShadowAddress(Addr, Pos);
2358c88fedefSJianzhou Zhao   Value *ExtShadowAddr =
2359c88fedefSJianzhou Zhao       IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowTy));
2360c88fedefSJianzhou Zhao   IRB.CreateAlignedStore(ExtZeroShadow, ExtShadowAddr, ShadowAlign);
2361c88fedefSJianzhou Zhao   // Do not write origins for 0 shadows because we do not trace origins for
2362c88fedefSJianzhou Zhao   // untainted sinks.
2363c88fedefSJianzhou Zhao }
2364db7fe6cdSJianzhou Zhao 
storePrimitiveShadowOrigin(Value * Addr,uint64_t Size,Align InstAlignment,Value * PrimitiveShadow,Value * Origin,Instruction * Pos)2365db7fe6cdSJianzhou Zhao void DFSanFunction::storePrimitiveShadowOrigin(Value *Addr, uint64_t Size,
2366db7fe6cdSJianzhou Zhao                                                Align InstAlignment,
2367ea981165SJianzhou Zhao                                                Value *PrimitiveShadow,
2368db7fe6cdSJianzhou Zhao                                                Value *Origin,
2369ea981165SJianzhou Zhao                                                Instruction *Pos) {
2370db7fe6cdSJianzhou Zhao   const bool ShouldTrackOrigins = DFS.shouldTrackOrigins() && Origin;
2371db7fe6cdSJianzhou Zhao 
2372e5d5b0c7SPeter Collingbourne   if (AllocaInst *AI = dyn_cast<AllocaInst>(Addr)) {
2373db7fe6cdSJianzhou Zhao     const auto SI = AllocaShadowMap.find(AI);
2374db7fe6cdSJianzhou Zhao     if (SI != AllocaShadowMap.end()) {
2375e5d5b0c7SPeter Collingbourne       IRBuilder<> IRB(Pos);
2376db7fe6cdSJianzhou Zhao       IRB.CreateStore(PrimitiveShadow, SI->second);
2377db7fe6cdSJianzhou Zhao 
2378db7fe6cdSJianzhou Zhao       // Do not write origins for 0 shadows because we do not trace origins for
2379db7fe6cdSJianzhou Zhao       // untainted sinks.
2380db7fe6cdSJianzhou Zhao       if (ShouldTrackOrigins && !DFS.isZeroShadow(PrimitiveShadow)) {
2381db7fe6cdSJianzhou Zhao         const auto OI = AllocaOriginMap.find(AI);
2382db7fe6cdSJianzhou Zhao         assert(OI != AllocaOriginMap.end() && Origin);
2383db7fe6cdSJianzhou Zhao         IRB.CreateStore(Origin, OI->second);
2384db7fe6cdSJianzhou Zhao       }
2385e5d5b0c7SPeter Collingbourne       return;
2386e5d5b0c7SPeter Collingbourne     }
2387e5d5b0c7SPeter Collingbourne   }
2388e5d5b0c7SPeter Collingbourne 
2389db7fe6cdSJianzhou Zhao   const Align ShadowAlign = getShadowAlign(InstAlignment);
2390ea981165SJianzhou Zhao   if (DFS.isZeroShadow(PrimitiveShadow)) {
2391c88fedefSJianzhou Zhao     storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, Pos);
2392e5d5b0c7SPeter Collingbourne     return;
2393e5d5b0c7SPeter Collingbourne   }
2394e5d5b0c7SPeter Collingbourne 
2395c88fedefSJianzhou Zhao   IRBuilder<> IRB(Pos);
2396db7fe6cdSJianzhou Zhao   Value *ShadowAddr, *OriginAddr;
2397db7fe6cdSJianzhou Zhao   std::tie(ShadowAddr, OriginAddr) =
2398db7fe6cdSJianzhou Zhao       DFS.getShadowOriginAddress(Addr, InstAlignment, Pos);
2399db7fe6cdSJianzhou Zhao 
2400d10f173fSGeorge Balatsouras   const unsigned ShadowVecSize = 8;
2401d10f173fSGeorge Balatsouras   assert(ShadowVecSize * DFS.ShadowWidthBits <= 128 &&
2402d10f173fSGeorge Balatsouras          "Shadow vector is too large!");
2403d10f173fSGeorge Balatsouras 
2404e5d5b0c7SPeter Collingbourne   uint64_t Offset = 0;
2405db7fe6cdSJianzhou Zhao   uint64_t LeftSize = Size;
2406db7fe6cdSJianzhou Zhao   if (LeftSize >= ShadowVecSize) {
2407bd726d27SJianzhou Zhao     auto *ShadowVecTy =
2408bd726d27SJianzhou Zhao         FixedVectorType::get(DFS.PrimitiveShadowTy, ShadowVecSize);
2409e5d5b0c7SPeter Collingbourne     Value *ShadowVec = UndefValue::get(ShadowVecTy);
24106ff18b08SGeorge Balatsouras     for (unsigned I = 0; I != ShadowVecSize; ++I) {
2411e5d5b0c7SPeter Collingbourne       ShadowVec = IRB.CreateInsertElement(
2412ea981165SJianzhou Zhao           ShadowVec, PrimitiveShadow,
24136ff18b08SGeorge Balatsouras           ConstantInt::get(Type::getInt32Ty(*DFS.Ctx), I));
2414e5d5b0c7SPeter Collingbourne     }
2415e5d5b0c7SPeter Collingbourne     Value *ShadowVecAddr =
2416e5d5b0c7SPeter Collingbourne         IRB.CreateBitCast(ShadowAddr, PointerType::getUnqual(ShadowVecTy));
2417e5d5b0c7SPeter Collingbourne     do {
241895d3e537SDavid Blaikie       Value *CurShadowVecAddr =
241995d3e537SDavid Blaikie           IRB.CreateConstGEP1_32(ShadowVecTy, ShadowVecAddr, Offset);
2420e5d5b0c7SPeter Collingbourne       IRB.CreateAlignedStore(ShadowVec, CurShadowVecAddr, ShadowAlign);
2421db7fe6cdSJianzhou Zhao       LeftSize -= ShadowVecSize;
2422e5d5b0c7SPeter Collingbourne       ++Offset;
2423db7fe6cdSJianzhou Zhao     } while (LeftSize >= ShadowVecSize);
2424e5d5b0c7SPeter Collingbourne     Offset *= ShadowVecSize;
2425e5d5b0c7SPeter Collingbourne   }
2426db7fe6cdSJianzhou Zhao   while (LeftSize > 0) {
242795d3e537SDavid Blaikie     Value *CurShadowAddr =
2428bd726d27SJianzhou Zhao         IRB.CreateConstGEP1_32(DFS.PrimitiveShadowTy, ShadowAddr, Offset);
2429ea981165SJianzhou Zhao     IRB.CreateAlignedStore(PrimitiveShadow, CurShadowAddr, ShadowAlign);
2430db7fe6cdSJianzhou Zhao     --LeftSize;
2431e5d5b0c7SPeter Collingbourne     ++Offset;
2432e5d5b0c7SPeter Collingbourne   }
2433db7fe6cdSJianzhou Zhao 
2434db7fe6cdSJianzhou Zhao   if (ShouldTrackOrigins) {
2435db7fe6cdSJianzhou Zhao     storeOrigin(Pos, Addr, Size, PrimitiveShadow, Origin, OriginAddr,
2436db7fe6cdSJianzhou Zhao                 InstAlignment);
2437db7fe6cdSJianzhou Zhao   }
2438e5d5b0c7SPeter Collingbourne }
2439e5d5b0c7SPeter Collingbourne 
addReleaseOrdering(AtomicOrdering AO)2440c88fedefSJianzhou Zhao static AtomicOrdering addReleaseOrdering(AtomicOrdering AO) {
2441c88fedefSJianzhou Zhao   switch (AO) {
2442c88fedefSJianzhou Zhao   case AtomicOrdering::NotAtomic:
2443c88fedefSJianzhou Zhao     return AtomicOrdering::NotAtomic;
2444c88fedefSJianzhou Zhao   case AtomicOrdering::Unordered:
2445c88fedefSJianzhou Zhao   case AtomicOrdering::Monotonic:
2446c88fedefSJianzhou Zhao   case AtomicOrdering::Release:
2447c88fedefSJianzhou Zhao     return AtomicOrdering::Release;
2448c88fedefSJianzhou Zhao   case AtomicOrdering::Acquire:
2449c88fedefSJianzhou Zhao   case AtomicOrdering::AcquireRelease:
2450c88fedefSJianzhou Zhao     return AtomicOrdering::AcquireRelease;
2451c88fedefSJianzhou Zhao   case AtomicOrdering::SequentiallyConsistent:
2452c88fedefSJianzhou Zhao     return AtomicOrdering::SequentiallyConsistent;
2453c88fedefSJianzhou Zhao   }
2454c88fedefSJianzhou Zhao   llvm_unreachable("Unknown ordering");
2455c88fedefSJianzhou Zhao }
2456c88fedefSJianzhou Zhao 
visitStoreInst(StoreInst & SI)2457e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitStoreInst(StoreInst &SI) {
2458a28d91d8SMehdi Amini   auto &DL = SI.getModule()->getDataLayout();
2459c88fedefSJianzhou Zhao   Value *Val = SI.getValueOperand();
2460c88fedefSJianzhou Zhao   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2461142fdff0SPeter Collingbourne   if (Size == 0)
2462142fdff0SPeter Collingbourne     return;
2463142fdff0SPeter Collingbourne 
2464c88fedefSJianzhou Zhao   // When an application store is atomic, increase atomic ordering between
2465c88fedefSJianzhou Zhao   // atomic application loads and stores to ensure happen-before order; load
2466c88fedefSJianzhou Zhao   // shadow data after application data; store zero shadow data before
2467c88fedefSJianzhou Zhao   // application data. This ensure shadow loads return either labels of the
2468c88fedefSJianzhou Zhao   // initial application data or zeros.
2469c88fedefSJianzhou Zhao   if (SI.isAtomic())
2470c88fedefSJianzhou Zhao     SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
2471c88fedefSJianzhou Zhao 
2472db7fe6cdSJianzhou Zhao   const bool ShouldTrackOrigins =
2473db7fe6cdSJianzhou Zhao       DFSF.DFS.shouldTrackOrigins() && !SI.isAtomic();
2474db7fe6cdSJianzhou Zhao   std::vector<Value *> Shadows;
2475db7fe6cdSJianzhou Zhao   std::vector<Value *> Origins;
24760be79e1aSPeter Collingbourne 
2477c88fedefSJianzhou Zhao   Value *Shadow =
2478c88fedefSJianzhou Zhao       SI.isAtomic() ? DFSF.DFS.getZeroShadow(Val) : DFSF.getShadow(Val);
2479db7fe6cdSJianzhou Zhao 
2480db7fe6cdSJianzhou Zhao   if (ShouldTrackOrigins) {
2481db7fe6cdSJianzhou Zhao     Shadows.push_back(Shadow);
2482db7fe6cdSJianzhou Zhao     Origins.push_back(DFSF.getOrigin(Val));
2483db7fe6cdSJianzhou Zhao   }
2484db7fe6cdSJianzhou Zhao 
2485ea981165SJianzhou Zhao   Value *PrimitiveShadow;
24860be79e1aSPeter Collingbourne   if (ClCombinePointerLabelsOnStore) {
24870be79e1aSPeter Collingbourne     Value *PtrShadow = DFSF.getShadow(SI.getPointerOperand());
2488db7fe6cdSJianzhou Zhao     if (ShouldTrackOrigins) {
2489db7fe6cdSJianzhou Zhao       Shadows.push_back(PtrShadow);
2490db7fe6cdSJianzhou Zhao       Origins.push_back(DFSF.getOrigin(SI.getPointerOperand()));
2491db7fe6cdSJianzhou Zhao     }
2492ea981165SJianzhou Zhao     PrimitiveShadow = DFSF.combineShadows(Shadow, PtrShadow, &SI);
2493ea981165SJianzhou Zhao   } else {
2494ea981165SJianzhou Zhao     PrimitiveShadow = DFSF.collapseToPrimitiveShadow(Shadow, &SI);
24950be79e1aSPeter Collingbourne   }
2496db7fe6cdSJianzhou Zhao   Value *Origin = nullptr;
24978506fe5bSJianzhou Zhao   if (ShouldTrackOrigins)
2498db7fe6cdSJianzhou Zhao     Origin = DFSF.combineOrigins(Shadows, Origins, &SI);
2499db7fe6cdSJianzhou Zhao   DFSF.storePrimitiveShadowOrigin(SI.getPointerOperand(), Size, SI.getAlign(),
2500db7fe6cdSJianzhou Zhao                                   PrimitiveShadow, Origin, &SI);
2501470db54cSMatt Morehouse   if (ClEventCallbacks) {
2502470db54cSMatt Morehouse     IRBuilder<> IRB(&SI);
250306c9b4aaSJianzhou Zhao     Value *Addr8 = IRB.CreateBitCast(SI.getPointerOperand(), DFSF.DFS.Int8Ptr);
2504ea981165SJianzhou Zhao     IRB.CreateCall(DFSF.DFS.DFSanStoreCallbackFn, {PrimitiveShadow, Addr8});
2505470db54cSMatt Morehouse   }
2506e5d5b0c7SPeter Collingbourne }
2507e5d5b0c7SPeter Collingbourne 
visitCASOrRMW(Align InstAlignment,Instruction & I)2508c88fedefSJianzhou Zhao void DFSanVisitor::visitCASOrRMW(Align InstAlignment, Instruction &I) {
2509c88fedefSJianzhou Zhao   assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
2510c88fedefSJianzhou Zhao 
2511c88fedefSJianzhou Zhao   Value *Val = I.getOperand(1);
2512c88fedefSJianzhou Zhao   const auto &DL = I.getModule()->getDataLayout();
2513c88fedefSJianzhou Zhao   uint64_t Size = DL.getTypeStoreSize(Val->getType());
2514c88fedefSJianzhou Zhao   if (Size == 0)
2515c88fedefSJianzhou Zhao     return;
2516c88fedefSJianzhou Zhao 
2517c88fedefSJianzhou Zhao   // Conservatively set data at stored addresses and return with zero shadow to
2518c88fedefSJianzhou Zhao   // prevent shadow data races.
2519c88fedefSJianzhou Zhao   IRBuilder<> IRB(&I);
2520c88fedefSJianzhou Zhao   Value *Addr = I.getOperand(0);
2521c88fedefSJianzhou Zhao   const Align ShadowAlign = DFSF.getShadowAlign(InstAlignment);
2522c88fedefSJianzhou Zhao   DFSF.storeZeroPrimitiveShadow(Addr, Size, ShadowAlign, &I);
2523c88fedefSJianzhou Zhao   DFSF.setShadow(&I, DFSF.DFS.getZeroShadow(&I));
252472abc9bfSJianzhou Zhao   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2525c88fedefSJianzhou Zhao }
2526c88fedefSJianzhou Zhao 
visitAtomicRMWInst(AtomicRMWInst & I)2527c88fedefSJianzhou Zhao void DFSanVisitor::visitAtomicRMWInst(AtomicRMWInst &I) {
2528c88fedefSJianzhou Zhao   visitCASOrRMW(I.getAlign(), I);
2529c88fedefSJianzhou Zhao   // TODO: The ordering change follows MSan. It is possible not to change
2530c88fedefSJianzhou Zhao   // ordering because we always set and use 0 shadows.
2531c88fedefSJianzhou Zhao   I.setOrdering(addReleaseOrdering(I.getOrdering()));
2532c88fedefSJianzhou Zhao }
2533c88fedefSJianzhou Zhao 
visitAtomicCmpXchgInst(AtomicCmpXchgInst & I)2534c88fedefSJianzhou Zhao void DFSanVisitor::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
2535c88fedefSJianzhou Zhao   visitCASOrRMW(I.getAlign(), I);
2536c88fedefSJianzhou Zhao   // TODO: The ordering change follows MSan. It is possible not to change
2537c88fedefSJianzhou Zhao   // ordering because we always set and use 0 shadows.
2538c88fedefSJianzhou Zhao   I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
2539c88fedefSJianzhou Zhao }
2540c88fedefSJianzhou Zhao 
visitUnaryOperator(UnaryOperator & UO)25417aa898e6SCameron McInally void DFSanVisitor::visitUnaryOperator(UnaryOperator &UO) {
25427424efd5SJianzhou Zhao   visitInstOperands(UO);
25437aa898e6SCameron McInally }
25447aa898e6SCameron McInally 
visitBinaryOperator(BinaryOperator & BO)2545e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitBinaryOperator(BinaryOperator &BO) {
25467424efd5SJianzhou Zhao   visitInstOperands(BO);
2547e5d5b0c7SPeter Collingbourne }
2548e5d5b0c7SPeter Collingbourne 
visitBitCastInst(BitCastInst & BCI)254970804f2aSAndrew Browne void DFSanVisitor::visitBitCastInst(BitCastInst &BCI) {
255070804f2aSAndrew Browne   // Special case: if this is the bitcast (there is exactly 1 allowed) between
255170804f2aSAndrew Browne   // a musttail call and a ret, don't instrument. New instructions are not
255270804f2aSAndrew Browne   // allowed after a musttail call.
255370804f2aSAndrew Browne   if (auto *CI = dyn_cast<CallInst>(BCI.getOperand(0)))
255470804f2aSAndrew Browne     if (CI->isMustTailCall())
255570804f2aSAndrew Browne       return;
255670804f2aSAndrew Browne   visitInstOperands(BCI);
255770804f2aSAndrew Browne }
255870804f2aSAndrew Browne 
visitCastInst(CastInst & CI)25597424efd5SJianzhou Zhao void DFSanVisitor::visitCastInst(CastInst &CI) { visitInstOperands(CI); }
2560e5d5b0c7SPeter Collingbourne 
visitCmpInst(CmpInst & CI)256130bb737aSMatt Morehouse void DFSanVisitor::visitCmpInst(CmpInst &CI) {
25627424efd5SJianzhou Zhao   visitInstOperands(CI);
256330bb737aSMatt Morehouse   if (ClEventCallbacks) {
256430bb737aSMatt Morehouse     IRBuilder<> IRB(&CI);
25657424efd5SJianzhou Zhao     Value *CombinedShadow = DFSF.getShadow(&CI);
256630bb737aSMatt Morehouse     IRB.CreateCall(DFSF.DFS.DFSanCmpCallbackFn, CombinedShadow);
256730bb737aSMatt Morehouse   }
256830bb737aSMatt Morehouse }
2569e5d5b0c7SPeter Collingbourne 
visitLandingPadInst(LandingPadInst & LPI)2570af931576SAndrew Browne void DFSanVisitor::visitLandingPadInst(LandingPadInst &LPI) {
2571af931576SAndrew Browne   // We do not need to track data through LandingPadInst.
2572af931576SAndrew Browne   //
2573af931576SAndrew Browne   // For the C++ exceptions, if a value is thrown, this value will be stored
2574af931576SAndrew Browne   // in a memory location provided by __cxa_allocate_exception(...) (on the
2575af931576SAndrew Browne   // throw side) or  __cxa_begin_catch(...) (on the catch side).
2576af931576SAndrew Browne   // This memory will have a shadow, so with the loads and stores we will be
2577af931576SAndrew Browne   // able to propagate labels on data thrown through exceptions, without any
2578af931576SAndrew Browne   // special handling of the LandingPadInst.
2579af931576SAndrew Browne   //
2580af931576SAndrew Browne   // The second element in the pair result of the LandingPadInst is a
2581af931576SAndrew Browne   // register value, but it is for a type ID and should never be tainted.
2582af931576SAndrew Browne   DFSF.setShadow(&LPI, DFSF.DFS.getZeroShadow(&LPI));
2583af931576SAndrew Browne   DFSF.setOrigin(&LPI, DFSF.DFS.ZeroOrigin);
2584af931576SAndrew Browne }
2585af931576SAndrew Browne 
visitGetElementPtrInst(GetElementPtrInst & GEPI)2586e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitGetElementPtrInst(GetElementPtrInst &GEPI) {
25875748219fSAndrew Browne   if (ClCombineOffsetLabelsOnGEP ||
25885748219fSAndrew Browne       DFSF.isLookupTableConstant(
25895748219fSAndrew Browne           StripPointerGEPsAndCasts(GEPI.getPointerOperand()))) {
25907424efd5SJianzhou Zhao     visitInstOperands(GEPI);
2591fc1d3984SJianzhou Zhao     return;
2592fc1d3984SJianzhou Zhao   }
2593fc1d3984SJianzhou Zhao 
2594fc1d3984SJianzhou Zhao   // Only propagate shadow/origin of base pointer value but ignore those of
2595fc1d3984SJianzhou Zhao   // offset operands.
2596fc1d3984SJianzhou Zhao   Value *BasePointer = GEPI.getPointerOperand();
2597fc1d3984SJianzhou Zhao   DFSF.setShadow(&GEPI, DFSF.getShadow(BasePointer));
2598fc1d3984SJianzhou Zhao   if (DFSF.DFS.shouldTrackOrigins())
2599fc1d3984SJianzhou Zhao     DFSF.setOrigin(&GEPI, DFSF.getOrigin(BasePointer));
2600e5d5b0c7SPeter Collingbourne }
2601e5d5b0c7SPeter Collingbourne 
visitExtractElementInst(ExtractElementInst & I)2602e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitExtractElementInst(ExtractElementInst &I) {
26037424efd5SJianzhou Zhao   visitInstOperands(I);
2604e5d5b0c7SPeter Collingbourne }
2605e5d5b0c7SPeter Collingbourne 
visitInsertElementInst(InsertElementInst & I)2606e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitInsertElementInst(InsertElementInst &I) {
26077424efd5SJianzhou Zhao   visitInstOperands(I);
2608e5d5b0c7SPeter Collingbourne }
2609e5d5b0c7SPeter Collingbourne 
visitShuffleVectorInst(ShuffleVectorInst & I)2610e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitShuffleVectorInst(ShuffleVectorInst &I) {
26117424efd5SJianzhou Zhao   visitInstOperands(I);
2612e5d5b0c7SPeter Collingbourne }
2613e5d5b0c7SPeter Collingbourne 
visitExtractValueInst(ExtractValueInst & I)2614e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitExtractValueInst(ExtractValueInst &I) {
2615ea981165SJianzhou Zhao   IRBuilder<> IRB(&I);
2616ea981165SJianzhou Zhao   Value *Agg = I.getAggregateOperand();
2617ea981165SJianzhou Zhao   Value *AggShadow = DFSF.getShadow(Agg);
2618ea981165SJianzhou Zhao   Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2619ea981165SJianzhou Zhao   DFSF.setShadow(&I, ResShadow);
26207424efd5SJianzhou Zhao   visitInstOperandOrigins(I);
2621e5d5b0c7SPeter Collingbourne }
2622e5d5b0c7SPeter Collingbourne 
visitInsertValueInst(InsertValueInst & I)2623e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitInsertValueInst(InsertValueInst &I) {
2624ea981165SJianzhou Zhao   IRBuilder<> IRB(&I);
2625ea981165SJianzhou Zhao   Value *AggShadow = DFSF.getShadow(I.getAggregateOperand());
2626ea981165SJianzhou Zhao   Value *InsShadow = DFSF.getShadow(I.getInsertedValueOperand());
2627ea981165SJianzhou Zhao   Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2628ea981165SJianzhou Zhao   DFSF.setShadow(&I, Res);
26297424efd5SJianzhou Zhao   visitInstOperandOrigins(I);
2630e5d5b0c7SPeter Collingbourne }
2631e5d5b0c7SPeter Collingbourne 
visitAllocaInst(AllocaInst & I)2632e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitAllocaInst(AllocaInst &I) {
2633e5d5b0c7SPeter Collingbourne   bool AllLoadsStores = true;
2634cdf47884SChandler Carruth   for (User *U : I.users()) {
2635cdf47884SChandler Carruth     if (isa<LoadInst>(U))
2636e5d5b0c7SPeter Collingbourne       continue;
2637e5d5b0c7SPeter Collingbourne 
2638cdf47884SChandler Carruth     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2639e5d5b0c7SPeter Collingbourne       if (SI->getPointerOperand() == &I)
2640e5d5b0c7SPeter Collingbourne         continue;
2641e5d5b0c7SPeter Collingbourne     }
2642e5d5b0c7SPeter Collingbourne 
2643e5d5b0c7SPeter Collingbourne     AllLoadsStores = false;
2644e5d5b0c7SPeter Collingbourne     break;
2645e5d5b0c7SPeter Collingbourne   }
2646e5d5b0c7SPeter Collingbourne   if (AllLoadsStores) {
2647e5d5b0c7SPeter Collingbourne     IRBuilder<> IRB(&I);
2648bd726d27SJianzhou Zhao     DFSF.AllocaShadowMap[&I] = IRB.CreateAlloca(DFSF.DFS.PrimitiveShadowTy);
2649d866b9c9SJianzhou Zhao     if (DFSF.DFS.shouldTrackOrigins()) {
2650d866b9c9SJianzhou Zhao       DFSF.AllocaOriginMap[&I] =
2651d866b9c9SJianzhou Zhao           IRB.CreateAlloca(DFSF.DFS.OriginTy, nullptr, "_dfsa");
2652d866b9c9SJianzhou Zhao     }
2653e5d5b0c7SPeter Collingbourne   }
2654bd726d27SJianzhou Zhao   DFSF.setShadow(&I, DFSF.DFS.ZeroPrimitiveShadow);
2655d866b9c9SJianzhou Zhao   DFSF.setOrigin(&I, DFSF.DFS.ZeroOrigin);
2656e5d5b0c7SPeter Collingbourne }
2657e5d5b0c7SPeter Collingbourne 
visitSelectInst(SelectInst & I)2658e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitSelectInst(SelectInst &I) {
2659e5d5b0c7SPeter Collingbourne   Value *CondShadow = DFSF.getShadow(I.getCondition());
2660e5d5b0c7SPeter Collingbourne   Value *TrueShadow = DFSF.getShadow(I.getTrueValue());
2661e5d5b0c7SPeter Collingbourne   Value *FalseShadow = DFSF.getShadow(I.getFalseValue());
26620dd87825SJianzhou Zhao   Value *ShadowSel = nullptr;
26637424efd5SJianzhou Zhao   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
26647424efd5SJianzhou Zhao   std::vector<Value *> Shadows;
26657424efd5SJianzhou Zhao   std::vector<Value *> Origins;
26667424efd5SJianzhou Zhao   Value *TrueOrigin =
26677424efd5SJianzhou Zhao       ShouldTrackOrigins ? DFSF.getOrigin(I.getTrueValue()) : nullptr;
26687424efd5SJianzhou Zhao   Value *FalseOrigin =
26697424efd5SJianzhou Zhao       ShouldTrackOrigins ? DFSF.getOrigin(I.getFalseValue()) : nullptr;
2670e5d5b0c7SPeter Collingbourne 
26714e173585SAndrew Browne   DFSF.addConditionalCallbacksIfEnabled(I, I.getCondition());
26724e173585SAndrew Browne 
2673e5d5b0c7SPeter Collingbourne   if (isa<VectorType>(I.getCondition()->getType())) {
2674ea981165SJianzhou Zhao     ShadowSel = DFSF.combineShadowsThenConvert(I.getType(), TrueShadow,
2675ea981165SJianzhou Zhao                                                FalseShadow, &I);
26767424efd5SJianzhou Zhao     if (ShouldTrackOrigins) {
26777424efd5SJianzhou Zhao       Shadows.push_back(TrueShadow);
26787424efd5SJianzhou Zhao       Shadows.push_back(FalseShadow);
26797424efd5SJianzhou Zhao       Origins.push_back(TrueOrigin);
26807424efd5SJianzhou Zhao       Origins.push_back(FalseOrigin);
26817424efd5SJianzhou Zhao     }
2682e5d5b0c7SPeter Collingbourne   } else {
2683e5d5b0c7SPeter Collingbourne     if (TrueShadow == FalseShadow) {
2684e5d5b0c7SPeter Collingbourne       ShadowSel = TrueShadow;
26857424efd5SJianzhou Zhao       if (ShouldTrackOrigins) {
26867424efd5SJianzhou Zhao         Shadows.push_back(TrueShadow);
26877424efd5SJianzhou Zhao         Origins.push_back(TrueOrigin);
26887424efd5SJianzhou Zhao       }
2689e5d5b0c7SPeter Collingbourne     } else {
2690e5d5b0c7SPeter Collingbourne       ShadowSel =
2691e5d5b0c7SPeter Collingbourne           SelectInst::Create(I.getCondition(), TrueShadow, FalseShadow, "", &I);
26927424efd5SJianzhou Zhao       if (ShouldTrackOrigins) {
26937424efd5SJianzhou Zhao         Shadows.push_back(ShadowSel);
26947424efd5SJianzhou Zhao         Origins.push_back(SelectInst::Create(I.getCondition(), TrueOrigin,
26957424efd5SJianzhou Zhao                                              FalseOrigin, "", &I));
26967424efd5SJianzhou Zhao       }
2697e5d5b0c7SPeter Collingbourne     }
2698e5d5b0c7SPeter Collingbourne   }
26990dd87825SJianzhou Zhao   DFSF.setShadow(&I, ClTrackSelectControlFlow
2700ea981165SJianzhou Zhao                          ? DFSF.combineShadowsThenConvert(
2701ea981165SJianzhou Zhao                                I.getType(), CondShadow, ShadowSel, &I)
27020dd87825SJianzhou Zhao                          : ShadowSel);
27037424efd5SJianzhou Zhao   if (ShouldTrackOrigins) {
27047424efd5SJianzhou Zhao     if (ClTrackSelectControlFlow) {
27057424efd5SJianzhou Zhao       Shadows.push_back(CondShadow);
27067424efd5SJianzhou Zhao       Origins.push_back(DFSF.getOrigin(I.getCondition()));
27077424efd5SJianzhou Zhao     }
27087424efd5SJianzhou Zhao     DFSF.setOrigin(&I, DFSF.combineOrigins(Shadows, Origins, &I));
27097424efd5SJianzhou Zhao   }
2710e5d5b0c7SPeter Collingbourne }
2711e5d5b0c7SPeter Collingbourne 
visitMemSetInst(MemSetInst & I)27129d31d6f3SPeter Collingbourne void DFSanVisitor::visitMemSetInst(MemSetInst &I) {
27139d31d6f3SPeter Collingbourne   IRBuilder<> IRB(&I);
27149d31d6f3SPeter Collingbourne   Value *ValShadow = DFSF.getShadow(I.getValue());
2715a05aa0ddSJianzhou Zhao   Value *ValOrigin = DFSF.DFS.shouldTrackOrigins()
2716a05aa0ddSJianzhou Zhao                          ? DFSF.getOrigin(I.getValue())
2717a05aa0ddSJianzhou Zhao                          : DFSF.DFS.ZeroOrigin;
271847211fa8SArthur Eubanks   IRB.CreateCall(
2719a05aa0ddSJianzhou Zhao       DFSF.DFS.DFSanSetLabelFn,
2720a05aa0ddSJianzhou Zhao       {ValShadow, ValOrigin,
2721a05aa0ddSJianzhou Zhao        IRB.CreateBitCast(I.getDest(), Type::getInt8PtrTy(*DFSF.DFS.Ctx)),
2722ff6409d0SDavid Blaikie        IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
27239d31d6f3SPeter Collingbourne }
27249d31d6f3SPeter Collingbourne 
visitMemTransferInst(MemTransferInst & I)2725e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitMemTransferInst(MemTransferInst &I) {
2726e5d5b0c7SPeter Collingbourne   IRBuilder<> IRB(&I);
27278506fe5bSJianzhou Zhao 
27288506fe5bSJianzhou Zhao   // CopyOrMoveOrigin transfers origins by refering to their shadows. So we
27298506fe5bSJianzhou Zhao   // need to move origins before moving shadows.
27308506fe5bSJianzhou Zhao   if (DFSF.DFS.shouldTrackOrigins()) {
27318506fe5bSJianzhou Zhao     IRB.CreateCall(
27328506fe5bSJianzhou Zhao         DFSF.DFS.DFSanMemOriginTransferFn,
27338506fe5bSJianzhou Zhao         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
27348506fe5bSJianzhou Zhao          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
27358506fe5bSJianzhou Zhao          IRB.CreateIntCast(I.getArgOperand(2), DFSF.DFS.IntptrTy, false)});
27368506fe5bSJianzhou Zhao   }
27378506fe5bSJianzhou Zhao 
2738f668baa4SMatt Morehouse   Value *RawDestShadow = DFSF.DFS.getShadowAddress(I.getDest(), &I);
2739e5d5b0c7SPeter Collingbourne   Value *SrcShadow = DFSF.DFS.getShadowAddress(I.getSource(), &I);
2740ff858d77SGuillaume Chatelet   Value *LenShadow =
2741ff858d77SGuillaume Chatelet       IRB.CreateMul(I.getLength(), ConstantInt::get(I.getLength()->getType(),
2742ff858d77SGuillaume Chatelet                                                     DFSF.DFS.ShadowWidthBytes));
2743e5d5b0c7SPeter Collingbourne   Type *Int8Ptr = Type::getInt8PtrTy(*DFSF.DFS.Ctx);
2744f668baa4SMatt Morehouse   Value *DestShadow = IRB.CreateBitCast(RawDestShadow, Int8Ptr);
2745e5d5b0c7SPeter Collingbourne   SrcShadow = IRB.CreateBitCast(SrcShadow, Int8Ptr);
27461e68724dSDaniel Neilson   auto *MTI = cast<MemTransferInst>(
2747a58b62b4SCraig Topper       IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(),
27481e68724dSDaniel Neilson                      {DestShadow, SrcShadow, LenShadow, I.getVolatileCst()}));
2749*009fe075SGuillaume Chatelet   MTI->setDestAlignment(DFSF.getShadowAlign(I.getDestAlign().valueOrOne()));
2750*009fe075SGuillaume Chatelet   MTI->setSourceAlignment(DFSF.getShadowAlign(I.getSourceAlign().valueOrOne()));
2751f668baa4SMatt Morehouse   if (ClEventCallbacks) {
2752f668baa4SMatt Morehouse     IRB.CreateCall(DFSF.DFS.DFSanMemTransferCallbackFn,
27532627f996SElia Geretto                    {RawDestShadow,
27542627f996SElia Geretto                     IRB.CreateZExtOrTrunc(I.getLength(), DFSF.DFS.IntptrTy)});
2755f668baa4SMatt Morehouse   }
2756e5d5b0c7SPeter Collingbourne }
2757e5d5b0c7SPeter Collingbourne 
visitBranchInst(BranchInst & BR)27584e173585SAndrew Browne void DFSanVisitor::visitBranchInst(BranchInst &BR) {
27594e173585SAndrew Browne   if (!BR.isConditional())
27604e173585SAndrew Browne     return;
27614e173585SAndrew Browne 
27624e173585SAndrew Browne   DFSF.addConditionalCallbacksIfEnabled(BR, BR.getCondition());
27634e173585SAndrew Browne }
27644e173585SAndrew Browne 
visitSwitchInst(SwitchInst & SW)27654e173585SAndrew Browne void DFSanVisitor::visitSwitchInst(SwitchInst &SW) {
27664e173585SAndrew Browne   DFSF.addConditionalCallbacksIfEnabled(SW, SW.getCondition());
27674e173585SAndrew Browne }
27684e173585SAndrew Browne 
isAMustTailRetVal(Value * RetVal)276970804f2aSAndrew Browne static bool isAMustTailRetVal(Value *RetVal) {
277070804f2aSAndrew Browne   // Tail call may have a bitcast between return.
277170804f2aSAndrew Browne   if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
277270804f2aSAndrew Browne     RetVal = I->getOperand(0);
277370804f2aSAndrew Browne   }
277470804f2aSAndrew Browne   if (auto *I = dyn_cast<CallInst>(RetVal)) {
277570804f2aSAndrew Browne     return I->isMustTailCall();
277670804f2aSAndrew Browne   }
277770804f2aSAndrew Browne   return false;
277870804f2aSAndrew Browne }
277970804f2aSAndrew Browne 
visitReturnInst(ReturnInst & RI)2780e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitReturnInst(ReturnInst &RI) {
278168162e75SPeter Collingbourne   if (!DFSF.IsNativeABI && RI.getReturnValue()) {
278270804f2aSAndrew Browne     // Don't emit the instrumentation for musttail call returns.
278370804f2aSAndrew Browne     if (isAMustTailRetVal(RI.getReturnValue()))
278470804f2aSAndrew Browne       return;
278570804f2aSAndrew Browne 
2786e5d5b0c7SPeter Collingbourne     Value *S = DFSF.getShadow(RI.getReturnValue());
2787e5d5b0c7SPeter Collingbourne     IRBuilder<> IRB(&RI);
2788a28db8b2SJianzhou Zhao     Type *RT = DFSF.F->getFunctionType()->getReturnType();
278961ec2148SAndrew Browne     unsigned Size = getDataLayout().getTypeAllocSize(DFSF.DFS.getShadowTy(RT));
27906ff18b08SGeorge Balatsouras     if (Size <= RetvalTLSSize) {
279180e326a8SJianzhou Zhao       // If the size overflows, stores nothing. At callsite, oversized return
279280e326a8SJianzhou Zhao       // shadows are set to zero.
279361ec2148SAndrew Browne       IRB.CreateAlignedStore(S, DFSF.getRetvalTLS(RT, IRB), ShadowTLSAlignment);
279480e326a8SJianzhou Zhao     }
27957424efd5SJianzhou Zhao     if (DFSF.DFS.shouldTrackOrigins()) {
27967424efd5SJianzhou Zhao       Value *O = DFSF.getOrigin(RI.getReturnValue());
27977424efd5SJianzhou Zhao       IRB.CreateStore(O, DFSF.getRetvalOriginTLS());
27987424efd5SJianzhou Zhao     }
2799e5d5b0c7SPeter Collingbourne   }
2800e5d5b0c7SPeter Collingbourne }
2801e5d5b0c7SPeter Collingbourne 
addShadowArguments(Function & F,CallBase & CB,std::vector<Value * > & Args,IRBuilder<> & IRB)2802a47d435bSJianzhou Zhao void DFSanVisitor::addShadowArguments(Function &F, CallBase &CB,
2803a47d435bSJianzhou Zhao                                       std::vector<Value *> &Args,
2804a47d435bSJianzhou Zhao                                       IRBuilder<> &IRB) {
2805a47d435bSJianzhou Zhao   FunctionType *FT = F.getFunctionType();
2806a47d435bSJianzhou Zhao 
2807a47d435bSJianzhou Zhao   auto *I = CB.arg_begin();
2808a47d435bSJianzhou Zhao 
2809a47d435bSJianzhou Zhao   // Adds non-variable argument shadows.
2810a47d435bSJianzhou Zhao   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2811a47d435bSJianzhou Zhao     Args.push_back(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB));
2812a47d435bSJianzhou Zhao 
2813a47d435bSJianzhou Zhao   // Adds variable argument shadows.
2814a47d435bSJianzhou Zhao   if (FT->isVarArg()) {
2815a47d435bSJianzhou Zhao     auto *LabelVATy = ArrayType::get(DFSF.DFS.PrimitiveShadowTy,
2816a47d435bSJianzhou Zhao                                      CB.arg_size() - FT->getNumParams());
2817a47d435bSJianzhou Zhao     auto *LabelVAAlloca =
2818a47d435bSJianzhou Zhao         new AllocaInst(LabelVATy, getDataLayout().getAllocaAddrSpace(),
2819a47d435bSJianzhou Zhao                        "labelva", &DFSF.F->getEntryBlock().front());
2820a47d435bSJianzhou Zhao 
2821a47d435bSJianzhou Zhao     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2822a47d435bSJianzhou Zhao       auto *LabelVAPtr = IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, N);
2823a47d435bSJianzhou Zhao       IRB.CreateStore(DFSF.collapseToPrimitiveShadow(DFSF.getShadow(*I), &CB),
2824a47d435bSJianzhou Zhao                       LabelVAPtr);
2825a47d435bSJianzhou Zhao     }
2826a47d435bSJianzhou Zhao 
2827a47d435bSJianzhou Zhao     Args.push_back(IRB.CreateStructGEP(LabelVATy, LabelVAAlloca, 0));
2828a47d435bSJianzhou Zhao   }
2829a47d435bSJianzhou Zhao 
2830a47d435bSJianzhou Zhao   // Adds the return value shadow.
2831a47d435bSJianzhou Zhao   if (!FT->getReturnType()->isVoidTy()) {
2832a47d435bSJianzhou Zhao     if (!DFSF.LabelReturnAlloca) {
2833a47d435bSJianzhou Zhao       DFSF.LabelReturnAlloca = new AllocaInst(
2834a47d435bSJianzhou Zhao           DFSF.DFS.PrimitiveShadowTy, getDataLayout().getAllocaAddrSpace(),
2835a47d435bSJianzhou Zhao           "labelreturn", &DFSF.F->getEntryBlock().front());
2836a47d435bSJianzhou Zhao     }
2837a47d435bSJianzhou Zhao     Args.push_back(DFSF.LabelReturnAlloca);
2838a47d435bSJianzhou Zhao   }
2839a47d435bSJianzhou Zhao }
2840a47d435bSJianzhou Zhao 
addOriginArguments(Function & F,CallBase & CB,std::vector<Value * > & Args,IRBuilder<> & IRB)2841a47d435bSJianzhou Zhao void DFSanVisitor::addOriginArguments(Function &F, CallBase &CB,
2842a47d435bSJianzhou Zhao                                       std::vector<Value *> &Args,
2843a47d435bSJianzhou Zhao                                       IRBuilder<> &IRB) {
2844a47d435bSJianzhou Zhao   FunctionType *FT = F.getFunctionType();
2845a47d435bSJianzhou Zhao 
2846a47d435bSJianzhou Zhao   auto *I = CB.arg_begin();
2847a47d435bSJianzhou Zhao 
2848a47d435bSJianzhou Zhao   // Add non-variable argument origins.
2849a47d435bSJianzhou Zhao   for (unsigned N = FT->getNumParams(); N != 0; ++I, --N)
2850a47d435bSJianzhou Zhao     Args.push_back(DFSF.getOrigin(*I));
2851a47d435bSJianzhou Zhao 
2852a47d435bSJianzhou Zhao   // Add variable argument origins.
2853a47d435bSJianzhou Zhao   if (FT->isVarArg()) {
2854a47d435bSJianzhou Zhao     auto *OriginVATy =
2855a47d435bSJianzhou Zhao         ArrayType::get(DFSF.DFS.OriginTy, CB.arg_size() - FT->getNumParams());
2856a47d435bSJianzhou Zhao     auto *OriginVAAlloca =
2857a47d435bSJianzhou Zhao         new AllocaInst(OriginVATy, getDataLayout().getAllocaAddrSpace(),
2858a47d435bSJianzhou Zhao                        "originva", &DFSF.F->getEntryBlock().front());
2859a47d435bSJianzhou Zhao 
2860a47d435bSJianzhou Zhao     for (unsigned N = 0; I != CB.arg_end(); ++I, ++N) {
2861a47d435bSJianzhou Zhao       auto *OriginVAPtr = IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, N);
2862a47d435bSJianzhou Zhao       IRB.CreateStore(DFSF.getOrigin(*I), OriginVAPtr);
2863a47d435bSJianzhou Zhao     }
2864a47d435bSJianzhou Zhao 
2865a47d435bSJianzhou Zhao     Args.push_back(IRB.CreateStructGEP(OriginVATy, OriginVAAlloca, 0));
2866a47d435bSJianzhou Zhao   }
2867a47d435bSJianzhou Zhao 
2868a47d435bSJianzhou Zhao   // Add the return value origin.
2869a47d435bSJianzhou Zhao   if (!FT->getReturnType()->isVoidTy()) {
2870a47d435bSJianzhou Zhao     if (!DFSF.OriginReturnAlloca) {
2871a47d435bSJianzhou Zhao       DFSF.OriginReturnAlloca = new AllocaInst(
2872a47d435bSJianzhou Zhao           DFSF.DFS.OriginTy, getDataLayout().getAllocaAddrSpace(),
2873a47d435bSJianzhou Zhao           "originreturn", &DFSF.F->getEntryBlock().front());
2874a47d435bSJianzhou Zhao     }
2875a47d435bSJianzhou Zhao     Args.push_back(DFSF.OriginReturnAlloca);
2876a47d435bSJianzhou Zhao   }
2877a47d435bSJianzhou Zhao }
2878a47d435bSJianzhou Zhao 
visitWrappedCallBase(Function & F,CallBase & CB)287964b448b9SJianzhou Zhao bool DFSanVisitor::visitWrappedCallBase(Function &F, CallBase &CB) {
288064b448b9SJianzhou Zhao   IRBuilder<> IRB(&CB);
288164b448b9SJianzhou Zhao   switch (DFSF.DFS.getWrapperKind(&F)) {
288264b448b9SJianzhou Zhao   case DataFlowSanitizer::WK_Warning:
288364b448b9SJianzhou Zhao     CB.setCalledFunction(&F);
288464b448b9SJianzhou Zhao     IRB.CreateCall(DFSF.DFS.DFSanUnimplementedFn,
288564b448b9SJianzhou Zhao                    IRB.CreateGlobalStringPtr(F.getName()));
2886204c12eeSAndrew Browne     DFSF.DFS.buildExternWeakCheckIfNeeded(IRB, &F);
288764b448b9SJianzhou Zhao     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2888a47d435bSJianzhou Zhao     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
288964b448b9SJianzhou Zhao     return true;
289064b448b9SJianzhou Zhao   case DataFlowSanitizer::WK_Discard:
289164b448b9SJianzhou Zhao     CB.setCalledFunction(&F);
2892204c12eeSAndrew Browne     DFSF.DFS.buildExternWeakCheckIfNeeded(IRB, &F);
289364b448b9SJianzhou Zhao     DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
2894a47d435bSJianzhou Zhao     DFSF.setOrigin(&CB, DFSF.DFS.ZeroOrigin);
289564b448b9SJianzhou Zhao     return true;
289664b448b9SJianzhou Zhao   case DataFlowSanitizer::WK_Functional:
289764b448b9SJianzhou Zhao     CB.setCalledFunction(&F);
2898204c12eeSAndrew Browne     DFSF.DFS.buildExternWeakCheckIfNeeded(IRB, &F);
28997424efd5SJianzhou Zhao     visitInstOperands(CB);
290064b448b9SJianzhou Zhao     return true;
290164b448b9SJianzhou Zhao   case DataFlowSanitizer::WK_Custom:
290264b448b9SJianzhou Zhao     // Don't try to handle invokes of custom functions, it's too complicated.
290364b448b9SJianzhou Zhao     // Instead, invoke the dfsw$ wrapper, which will in turn call the __dfsw_
290464b448b9SJianzhou Zhao     // wrapper.
290564b448b9SJianzhou Zhao     CallInst *CI = dyn_cast<CallInst>(&CB);
290664b448b9SJianzhou Zhao     if (!CI)
290764b448b9SJianzhou Zhao       return false;
290864b448b9SJianzhou Zhao 
2909a47d435bSJianzhou Zhao     const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
291064b448b9SJianzhou Zhao     FunctionType *FT = F.getFunctionType();
291164b448b9SJianzhou Zhao     TransformedFunction CustomFn = DFSF.DFS.getCustomFunctionType(FT);
2912a47d435bSJianzhou Zhao     std::string CustomFName = ShouldTrackOrigins ? "__dfso_" : "__dfsw_";
291364b448b9SJianzhou Zhao     CustomFName += F.getName();
291464b448b9SJianzhou Zhao     FunctionCallee CustomF = DFSF.DFS.Mod->getOrInsertFunction(
291564b448b9SJianzhou Zhao         CustomFName, CustomFn.TransformedType);
291664b448b9SJianzhou Zhao     if (Function *CustomFn = dyn_cast<Function>(CustomF.getCallee())) {
291764b448b9SJianzhou Zhao       CustomFn->copyAttributesFrom(&F);
291864b448b9SJianzhou Zhao 
291964b448b9SJianzhou Zhao       // Custom functions returning non-void will write to the return label.
292064b448b9SJianzhou Zhao       if (!FT->getReturnType()->isVoidTy()) {
2921ad727ab7SArthur Eubanks         CustomFn->removeFnAttrs(DFSF.DFS.ReadOnlyNoneAttrs);
292264b448b9SJianzhou Zhao       }
292364b448b9SJianzhou Zhao     }
292464b448b9SJianzhou Zhao 
292564b448b9SJianzhou Zhao     std::vector<Value *> Args;
292664b448b9SJianzhou Zhao 
292764b448b9SJianzhou Zhao     // Adds non-variable arguments.
292864b448b9SJianzhou Zhao     auto *I = CB.arg_begin();
29296ff18b08SGeorge Balatsouras     for (unsigned N = FT->getNumParams(); N != 0; ++I, --N) {
293064b448b9SJianzhou Zhao       Args.push_back(*I);
293164b448b9SJianzhou Zhao     }
293264b448b9SJianzhou Zhao 
2933a47d435bSJianzhou Zhao     // Adds shadow arguments.
293464b448b9SJianzhou Zhao     const unsigned ShadowArgStart = Args.size();
2935a47d435bSJianzhou Zhao     addShadowArguments(F, CB, Args, IRB);
293664b448b9SJianzhou Zhao 
2937a47d435bSJianzhou Zhao     // Adds origin arguments.
2938a47d435bSJianzhou Zhao     const unsigned OriginArgStart = Args.size();
2939a47d435bSJianzhou Zhao     if (ShouldTrackOrigins)
2940a47d435bSJianzhou Zhao       addOriginArguments(F, CB, Args, IRB);
294164b448b9SJianzhou Zhao 
294264b448b9SJianzhou Zhao     // Adds variable arguments.
294364b448b9SJianzhou Zhao     append_range(Args, drop_begin(CB.args(), FT->getNumParams()));
294464b448b9SJianzhou Zhao 
294564b448b9SJianzhou Zhao     CallInst *CustomCI = IRB.CreateCall(CustomF, Args);
294664b448b9SJianzhou Zhao     CustomCI->setCallingConv(CI->getCallingConv());
29476ff18b08SGeorge Balatsouras     CustomCI->setAttributes(transformFunctionAttributes(
294864b448b9SJianzhou Zhao         CustomFn, CI->getContext(), CI->getAttributes()));
294964b448b9SJianzhou Zhao 
295064b448b9SJianzhou Zhao     // Update the parameter attributes of the custom call instruction to
295164b448b9SJianzhou Zhao     // zero extend the shadow parameters. This is required for targets
295264b448b9SJianzhou Zhao     // which consider PrimitiveShadowTy an illegal type.
295364b448b9SJianzhou Zhao     for (unsigned N = 0; N < FT->getNumParams(); N++) {
295464b448b9SJianzhou Zhao       const unsigned ArgNo = ShadowArgStart + N;
295564b448b9SJianzhou Zhao       if (CustomCI->getArgOperand(ArgNo)->getType() ==
295664b448b9SJianzhou Zhao           DFSF.DFS.PrimitiveShadowTy)
295764b448b9SJianzhou Zhao         CustomCI->addParamAttr(ArgNo, Attribute::ZExt);
2958a47d435bSJianzhou Zhao       if (ShouldTrackOrigins) {
2959a47d435bSJianzhou Zhao         const unsigned OriginArgNo = OriginArgStart + N;
2960a47d435bSJianzhou Zhao         if (CustomCI->getArgOperand(OriginArgNo)->getType() ==
2961a47d435bSJianzhou Zhao             DFSF.DFS.OriginTy)
2962a47d435bSJianzhou Zhao           CustomCI->addParamAttr(OriginArgNo, Attribute::ZExt);
2963a47d435bSJianzhou Zhao       }
296464b448b9SJianzhou Zhao     }
296564b448b9SJianzhou Zhao 
2966a47d435bSJianzhou Zhao     // Loads the return value shadow and origin.
296764b448b9SJianzhou Zhao     if (!FT->getReturnType()->isVoidTy()) {
296864b448b9SJianzhou Zhao       LoadInst *LabelLoad =
296964b448b9SJianzhou Zhao           IRB.CreateLoad(DFSF.DFS.PrimitiveShadowTy, DFSF.LabelReturnAlloca);
297064b448b9SJianzhou Zhao       DFSF.setShadow(CustomCI, DFSF.expandFromPrimitiveShadow(
297164b448b9SJianzhou Zhao                                    FT->getReturnType(), LabelLoad, &CB));
2972a47d435bSJianzhou Zhao       if (ShouldTrackOrigins) {
2973a47d435bSJianzhou Zhao         LoadInst *OriginLoad =
2974a47d435bSJianzhou Zhao             IRB.CreateLoad(DFSF.DFS.OriginTy, DFSF.OriginReturnAlloca);
2975a47d435bSJianzhou Zhao         DFSF.setOrigin(CustomCI, OriginLoad);
2976a47d435bSJianzhou Zhao       }
297764b448b9SJianzhou Zhao     }
297864b448b9SJianzhou Zhao 
297964b448b9SJianzhou Zhao     CI->replaceAllUsesWith(CustomCI);
298064b448b9SJianzhou Zhao     CI->eraseFromParent();
298164b448b9SJianzhou Zhao     return true;
298264b448b9SJianzhou Zhao   }
298364b448b9SJianzhou Zhao   return false;
298464b448b9SJianzhou Zhao }
298564b448b9SJianzhou Zhao 
visitCallBase(CallBase & CB)29866235951eSCraig Topper void DFSanVisitor::visitCallBase(CallBase &CB) {
29876235951eSCraig Topper   Function *F = CB.getCalledFunction();
2988a58b62b4SCraig Topper   if ((F && F->isIntrinsic()) || CB.isInlineAsm()) {
29897424efd5SJianzhou Zhao     visitInstOperands(CB);
2990e5d5b0c7SPeter Collingbourne     return;
2991e5d5b0c7SPeter Collingbourne   }
2992e5d5b0c7SPeter Collingbourne 
2993a1099840SPeter Collingbourne   // Calls to this function are synthesized in wrappers, and we shouldn't
2994a1099840SPeter Collingbourne   // instrument them.
299513680223SJames Y Knight   if (F == DFSF.DFS.DFSanVarargWrapperFn.getCallee()->stripPointerCasts())
2996a1099840SPeter Collingbourne     return;
2997a1099840SPeter Collingbourne 
29986ff18b08SGeorge Balatsouras   DenseMap<Value *, Function *>::iterator UnwrappedFnIt =
2999a58b62b4SCraig Topper       DFSF.DFS.UnwrappedFnMap.find(CB.getCalledOperand());
30006ff18b08SGeorge Balatsouras   if (UnwrappedFnIt != DFSF.DFS.UnwrappedFnMap.end())
30016ff18b08SGeorge Balatsouras     if (visitWrappedCallBase(*UnwrappedFnIt->second, CB))
3002e5d5b0c7SPeter Collingbourne       return;
3003e5d5b0c7SPeter Collingbourne 
300464b448b9SJianzhou Zhao   IRBuilder<> IRB(&CB);
3005e5d5b0c7SPeter Collingbourne 
3006a47d435bSJianzhou Zhao   const bool ShouldTrackOrigins = DFSF.DFS.shouldTrackOrigins();
3007a58b62b4SCraig Topper   FunctionType *FT = CB.getFunctionType();
300861ec2148SAndrew Browne   const DataLayout &DL = getDataLayout();
300961ec2148SAndrew Browne 
301064b448b9SJianzhou Zhao   // Stores argument shadows.
301180e326a8SJianzhou Zhao   unsigned ArgOffset = 0;
301280e326a8SJianzhou Zhao   for (unsigned I = 0, N = FT->getNumParams(); I != N; ++I) {
3013a47d435bSJianzhou Zhao     if (ShouldTrackOrigins) {
3014a47d435bSJianzhou Zhao       // Ignore overflowed origins
3015a47d435bSJianzhou Zhao       Value *ArgShadow = DFSF.getShadow(CB.getArgOperand(I));
30166ff18b08SGeorge Balatsouras       if (I < DFSF.DFS.NumOfElementsInArgOrgTLS &&
3017a47d435bSJianzhou Zhao           !DFSF.DFS.isZeroShadow(ArgShadow))
3018a47d435bSJianzhou Zhao         IRB.CreateStore(DFSF.getOrigin(CB.getArgOperand(I)),
3019a47d435bSJianzhou Zhao                         DFSF.getArgOriginTLS(I, IRB));
3020a47d435bSJianzhou Zhao     }
3021a47d435bSJianzhou Zhao 
3022a28db8b2SJianzhou Zhao     unsigned Size =
3023a28db8b2SJianzhou Zhao         DL.getTypeAllocSize(DFSF.DFS.getShadowTy(FT->getParamType(I)));
302480e326a8SJianzhou Zhao     // Stop storing if arguments' size overflows. Inside a function, arguments
302580e326a8SJianzhou Zhao     // after overflow have zero shadow values.
30266ff18b08SGeorge Balatsouras     if (ArgOffset + Size > ArgTLSSize)
302780e326a8SJianzhou Zhao       break;
302861ec2148SAndrew Browne     IRB.CreateAlignedStore(DFSF.getShadow(CB.getArgOperand(I)),
3029a28db8b2SJianzhou Zhao                            DFSF.getArgTLS(FT->getParamType(I), ArgOffset, IRB),
30306ff18b08SGeorge Balatsouras                            ShadowTLSAlignment);
30316ff18b08SGeorge Balatsouras     ArgOffset += alignTo(Size, ShadowTLSAlignment);
3032e5d5b0c7SPeter Collingbourne   }
3033e5d5b0c7SPeter Collingbourne 
3034f40110f4SCraig Topper   Instruction *Next = nullptr;
30356235951eSCraig Topper   if (!CB.getType()->isVoidTy()) {
30366235951eSCraig Topper     if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) {
3037e5d5b0c7SPeter Collingbourne       if (II->getNormalDest()->getSinglePredecessor()) {
3038e82c286fSDuncan P. N. Exon Smith         Next = &II->getNormalDest()->front();
3039e5d5b0c7SPeter Collingbourne       } else {
3040e5d5b0c7SPeter Collingbourne         BasicBlock *NewBB =
3041d450056cSChandler Carruth             SplitEdge(II->getParent(), II->getNormalDest(), &DFSF.DT);
3042e82c286fSDuncan P. N. Exon Smith         Next = &NewBB->front();
3043e5d5b0c7SPeter Collingbourne       }
3044e5d5b0c7SPeter Collingbourne     } else {
30456235951eSCraig Topper       assert(CB.getIterator() != CB.getParent()->end());
30466235951eSCraig Topper       Next = CB.getNextNode();
3047e5d5b0c7SPeter Collingbourne     }
3048e5d5b0c7SPeter Collingbourne 
304970804f2aSAndrew Browne     // Don't emit the epilogue for musttail call returns.
305070804f2aSAndrew Browne     if (isa<CallInst>(CB) && cast<CallInst>(CB).isMustTailCall())
305170804f2aSAndrew Browne       return;
305270804f2aSAndrew Browne 
305364b448b9SJianzhou Zhao     // Loads the return value shadow.
3054e5d5b0c7SPeter Collingbourne     IRBuilder<> NextIRB(Next);
3055a28db8b2SJianzhou Zhao     unsigned Size = DL.getTypeAllocSize(DFSF.DFS.getShadowTy(&CB));
30566ff18b08SGeorge Balatsouras     if (Size > RetvalTLSSize) {
305780e326a8SJianzhou Zhao       // Set overflowed return shadow to be zero.
3058a28db8b2SJianzhou Zhao       DFSF.setShadow(&CB, DFSF.DFS.getZeroShadow(&CB));
305980e326a8SJianzhou Zhao     } else {
306080e326a8SJianzhou Zhao       LoadInst *LI = NextIRB.CreateAlignedLoad(
3061a28db8b2SJianzhou Zhao           DFSF.DFS.getShadowTy(&CB), DFSF.getRetvalTLS(CB.getType(), NextIRB),
30626ff18b08SGeorge Balatsouras           ShadowTLSAlignment, "_dfsret");
3063e5d5b0c7SPeter Collingbourne       DFSF.SkipInsts.insert(LI);
30646235951eSCraig Topper       DFSF.setShadow(&CB, LI);
3065fab565a5SPeter Collingbourne       DFSF.NonZeroChecks.push_back(LI);
3066e5d5b0c7SPeter Collingbourne     }
3067a47d435bSJianzhou Zhao 
3068a47d435bSJianzhou Zhao     if (ShouldTrackOrigins) {
306961ec2148SAndrew Browne       LoadInst *LI = NextIRB.CreateLoad(DFSF.DFS.OriginTy,
307061ec2148SAndrew Browne                                         DFSF.getRetvalOriginTLS(), "_dfsret_o");
3071a47d435bSJianzhou Zhao       DFSF.SkipInsts.insert(LI);
3072a47d435bSJianzhou Zhao       DFSF.setOrigin(&CB, LI);
3073a47d435bSJianzhou Zhao     }
3074e5d5b0c7SPeter Collingbourne   }
307580e326a8SJianzhou Zhao }
3076e5d5b0c7SPeter Collingbourne 
visitPHINode(PHINode & PN)3077e5d5b0c7SPeter Collingbourne void DFSanVisitor::visitPHINode(PHINode &PN) {
3078a28db8b2SJianzhou Zhao   Type *ShadowTy = DFSF.DFS.getShadowTy(&PN);
3079a28db8b2SJianzhou Zhao   PHINode *ShadowPN =
3080a28db8b2SJianzhou Zhao       PHINode::Create(ShadowTy, PN.getNumIncomingValues(), "", &PN);
3081e5d5b0c7SPeter Collingbourne 
3082e5d5b0c7SPeter Collingbourne   // Give the shadow phi node valid predecessors to fool SplitEdge into working.
3083a28db8b2SJianzhou Zhao   Value *UndefShadow = UndefValue::get(ShadowTy);
30846ff18b08SGeorge Balatsouras   for (BasicBlock *BB : PN.blocks())
30856ff18b08SGeorge Balatsouras     ShadowPN->addIncoming(UndefShadow, BB);
3086e5d5b0c7SPeter Collingbourne 
3087e5d5b0c7SPeter Collingbourne   DFSF.setShadow(&PN, ShadowPN);
30886a9a686cSJianzhou Zhao 
30896a9a686cSJianzhou Zhao   PHINode *OriginPN = nullptr;
30906a9a686cSJianzhou Zhao   if (DFSF.DFS.shouldTrackOrigins()) {
30916a9a686cSJianzhou Zhao     OriginPN =
30926a9a686cSJianzhou Zhao         PHINode::Create(DFSF.DFS.OriginTy, PN.getNumIncomingValues(), "", &PN);
30936a9a686cSJianzhou Zhao     Value *UndefOrigin = UndefValue::get(DFSF.DFS.OriginTy);
30946a9a686cSJianzhou Zhao     for (BasicBlock *BB : PN.blocks())
30956a9a686cSJianzhou Zhao       OriginPN->addIncoming(UndefOrigin, BB);
30966a9a686cSJianzhou Zhao     DFSF.setOrigin(&PN, OriginPN);
30976a9a686cSJianzhou Zhao   }
30986a9a686cSJianzhou Zhao 
30996a9a686cSJianzhou Zhao   DFSF.PHIFixups.push_back({&PN, ShadowPN, OriginPN});
3100e5d5b0c7SPeter Collingbourne }
310171d0a2b8SArthur Eubanks 
3102c6f08b14SBenjamin Kramer namespace {
310371d0a2b8SArthur Eubanks class DataFlowSanitizerLegacyPass : public ModulePass {
310471d0a2b8SArthur Eubanks private:
310571d0a2b8SArthur Eubanks   std::vector<std::string> ABIListFiles;
310671d0a2b8SArthur Eubanks 
310771d0a2b8SArthur Eubanks public:
310871d0a2b8SArthur Eubanks   static char ID;
310971d0a2b8SArthur Eubanks 
DataFlowSanitizerLegacyPass(const std::vector<std::string> & ABIListFiles=std::vector<std::string> ())311071d0a2b8SArthur Eubanks   DataFlowSanitizerLegacyPass(
311171d0a2b8SArthur Eubanks       const std::vector<std::string> &ABIListFiles = std::vector<std::string>())
311271d0a2b8SArthur Eubanks       : ModulePass(ID), ABIListFiles(ABIListFiles) {}
311371d0a2b8SArthur Eubanks 
runOnModule(Module & M)311471d0a2b8SArthur Eubanks   bool runOnModule(Module &M) override {
311571d0a2b8SArthur Eubanks     return DataFlowSanitizer(ABIListFiles).runImpl(M);
311671d0a2b8SArthur Eubanks   }
311771d0a2b8SArthur Eubanks };
3118c6f08b14SBenjamin Kramer } // namespace
311971d0a2b8SArthur Eubanks 
312071d0a2b8SArthur Eubanks char DataFlowSanitizerLegacyPass::ID;
312171d0a2b8SArthur Eubanks 
312271d0a2b8SArthur Eubanks INITIALIZE_PASS(DataFlowSanitizerLegacyPass, "dfsan",
312371d0a2b8SArthur Eubanks                 "DataFlowSanitizer: dynamic data flow analysis.", false, false)
312471d0a2b8SArthur Eubanks 
createDataFlowSanitizerLegacyPassPass(const std::vector<std::string> & ABIListFiles)312571d0a2b8SArthur Eubanks ModulePass *llvm::createDataFlowSanitizerLegacyPassPass(
312671d0a2b8SArthur Eubanks     const std::vector<std::string> &ABIListFiles) {
312771d0a2b8SArthur Eubanks   return new DataFlowSanitizerLegacyPass(ABIListFiles);
312871d0a2b8SArthur Eubanks }
312971d0a2b8SArthur Eubanks 
run(Module & M,ModuleAnalysisManager & AM)313071d0a2b8SArthur Eubanks PreservedAnalyses DataFlowSanitizerPass::run(Module &M,
313171d0a2b8SArthur Eubanks                                              ModuleAnalysisManager &AM) {
313271d0a2b8SArthur Eubanks   if (DataFlowSanitizer(ABIListFiles).runImpl(M)) {
313371d0a2b8SArthur Eubanks     return PreservedAnalyses::none();
313471d0a2b8SArthur Eubanks   }
313571d0a2b8SArthur Eubanks   return PreservedAnalyses::all();
313671d0a2b8SArthur Eubanks }
3137