Make DataLayout Non-Optional in the Module

Summary:
DataLayout keeps the string used for its creation.

As a side effect it is no longer needed in the Module.
This is "almost" NFC, the string is no longer
canonicalized, you can't rely on two "equals" DataLayout
having the same string returned by getStringRepresentation().

Get rid of DataLayoutPass: the DataLayout is in the Module

The DataLayout is "per-module", let's enforce this by not
duplicating it more than necessary.
One more step toward non-optionality of the DataLayout in the
module.

Make DataLayout Non-Optional in the Module

Module->getDataLayout() will never returns nullptr anymore.

Reviewers: echristo

Subscribers: resistor, llvm-commits, jholewinski

Differential Revision: http://reviews.llvm.org/D7992

From: Mehdi Amini <mehdi.amini@apple.com>
llvm-svn: 231270
This commit is contained in:
Mehdi Amini 2015-03-04 18:43:29 +00:00
parent 2ae03e1783
commit 46a43556db
163 changed files with 617 additions and 973 deletions

View File

@ -1973,7 +1973,6 @@ int main(int argc, char *argv[]) {
// Start with registering info about how the // Start with registering info about how the
// target lays out data structures. // target lays out data structures.
module->setDataLayout(executionEngine->getDataLayout()); module->setDataLayout(executionEngine->getDataLayout());
fpm.add(new llvm::DataLayoutPass());
// Optimizations turned on // Optimizations turned on
#ifdef ADD_OPT_PASSES #ifdef ADD_OPT_PASSES

View File

@ -561,7 +561,6 @@ void *MCJITHelper::getPointerToFunction(Function *F) {
// Set up the optimizer pipeline. Start with registering info about how the // Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures. // target lays out data structures.
OpenModule->setDataLayout(NewEngine->getDataLayout()); OpenModule->setDataLayout(NewEngine->getDataLayout());
FPM->add(new DataLayoutPass());
// Provide basic AliasAnalysis support for GVN. // Provide basic AliasAnalysis support for GVN.
FPM->add(createBasicAliasAnalysisPass()); FPM->add(createBasicAliasAnalysisPass());
// Promote allocas to registers. // Promote allocas to registers.

View File

@ -914,7 +914,6 @@ int main() {
// Set up the optimizer pipeline. Start with registering info about how the // Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures. // target lays out data structures.
TheModule->setDataLayout(TheExecutionEngine->getDataLayout()); TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
OurFPM.add(new DataLayoutPass());
// Provide basic AliasAnalysis support for GVN. // Provide basic AliasAnalysis support for GVN.
OurFPM.add(createBasicAliasAnalysisPass()); OurFPM.add(createBasicAliasAnalysisPass());
// Do simple "peephole" optimizations and bit-twiddling optzns. // Do simple "peephole" optimizations and bit-twiddling optzns.

View File

@ -1035,7 +1035,6 @@ int main() {
// Set up the optimizer pipeline. Start with registering info about how the // Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures. // target lays out data structures.
TheModule->setDataLayout(TheExecutionEngine->getDataLayout()); TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
OurFPM.add(new DataLayoutPass());
// Provide basic AliasAnalysis support for GVN. // Provide basic AliasAnalysis support for GVN.
OurFPM.add(createBasicAliasAnalysisPass()); OurFPM.add(createBasicAliasAnalysisPass());
// Do simple "peephole" optimizations and bit-twiddling optzns. // Do simple "peephole" optimizations and bit-twiddling optzns.

View File

@ -1209,7 +1209,6 @@ int main() {
// Set up the optimizer pipeline. Start with registering info about how the // Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures. // target lays out data structures.
TheModule->setDataLayout(TheExecutionEngine->getDataLayout()); TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
OurFPM.add(new DataLayoutPass());
// Provide basic AliasAnalysis support for GVN. // Provide basic AliasAnalysis support for GVN.
OurFPM.add(createBasicAliasAnalysisPass()); OurFPM.add(createBasicAliasAnalysisPass());
// Promote allocas to registers. // Promote allocas to registers.

View File

@ -1460,7 +1460,6 @@ int main() {
// Set up the optimizer pipeline. Start with registering info about how the // Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures. // target lays out data structures.
TheModule->setDataLayout(TheExecutionEngine->getDataLayout()); TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
OurFPM.add(new DataLayoutPass());
#if 0 #if 0
// Provide basic AliasAnalysis support for GVN. // Provide basic AliasAnalysis support for GVN.
OurFPM.add(createBasicAliasAnalysisPass()); OurFPM.add(createBasicAliasAnalysisPass());

View File

@ -716,7 +716,7 @@ public:
M(new Module(GenerateUniqueName("jit_module_"), M(new Module(GenerateUniqueName("jit_module_"),
Session.getLLVMContext())), Session.getLLVMContext())),
Builder(Session.getLLVMContext()) { Builder(Session.getLLVMContext()) {
M->setDataLayout(Session.getTarget().getDataLayout()); M->setDataLayout(*Session.getTarget().getDataLayout());
} }
SessionContext& getSession() { return Session; } SessionContext& getSession() { return Session; }

View File

@ -715,7 +715,7 @@ public:
M(new Module(GenerateUniqueName("jit_module_"), M(new Module(GenerateUniqueName("jit_module_"),
Session.getLLVMContext())), Session.getLLVMContext())),
Builder(Session.getLLVMContext()) { Builder(Session.getLLVMContext()) {
M->setDataLayout(Session.getTarget().getDataLayout()); M->setDataLayout(*Session.getTarget().getDataLayout());
} }
SessionContext& getSession() { return Session; } SessionContext& getSession() { return Session; }

View File

@ -715,7 +715,7 @@ public:
M(new Module(GenerateUniqueName("jit_module_"), M(new Module(GenerateUniqueName("jit_module_"),
Session.getLLVMContext())), Session.getLLVMContext())),
Builder(Session.getLLVMContext()) { Builder(Session.getLLVMContext()) {
M->setDataLayout(Session.getTarget().getDataLayout()); M->setDataLayout(*Session.getTarget().getDataLayout());
} }
SessionContext& getSession() { return Session; } SessionContext& getSession() { return Session; }

View File

@ -715,7 +715,7 @@ public:
M(new Module(GenerateUniqueName("jit_module_"), M(new Module(GenerateUniqueName("jit_module_"),
Session.getLLVMContext())), Session.getLLVMContext())),
Builder(Session.getLLVMContext()) { Builder(Session.getLLVMContext()) {
M->setDataLayout(Session.getTarget().getDataLayout()); M->setDataLayout(*Session.getTarget().getDataLayout());
} }
SessionContext& getSession() { return Session; } SessionContext& getSession() { return Session; }

View File

@ -68,7 +68,7 @@ protected:
/// typically called by the run* methods of these subclasses. This may be /// typically called by the run* methods of these subclasses. This may be
/// called multiple times. /// called multiple times.
/// ///
void InitializeAliasAnalysis(Pass *P); void InitializeAliasAnalysis(Pass *P, const DataLayout *DL);
/// getAnalysisUsage - All alias analysis implementations should invoke this /// getAnalysisUsage - All alias analysis implementations should invoke this
/// directly (using AliasAnalysis::getAnalysisUsage(AU)). /// directly (using AliasAnalysis::getAnalysisUsage(AU)).

View File

@ -15,6 +15,7 @@
#define LLVM_ANALYSIS_LIBCALLALIASANALYSIS_H #define LLVM_ANALYSIS_LIBCALLALIASANALYSIS_H
#include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h" #include "llvm/Pass.h"
namespace llvm { namespace llvm {
@ -48,11 +49,8 @@ namespace llvm {
void getAnalysisUsage(AnalysisUsage &AU) const override; void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnFunction(Function &F) override { bool runOnFunction(Function &F) override;
InitializeAliasAnalysis(this); // set up super class
return false;
}
/// getAdjustedAnalysisPointer - This method is used when a pass implements /// getAdjustedAnalysisPointer - This method is used when a pass implements
/// an analysis interface through multiple inheritance. If needed, it /// an analysis interface through multiple inheritance. If needed, it
/// should override this to adjust the this pointer as needed for the /// should override this to adjust the this pointer as needed for the

View File

@ -183,7 +183,7 @@ private:
auto Names = llvm::make_unique<StringMap<bool>>(); auto Names = llvm::make_unique<StringMap<bool>>();
for (const auto &M : Ms) { for (const auto &M : Ms) {
Mangler Mang(M->getDataLayout()); Mangler Mang(&M->getDataLayout());
for (const auto &GV : M->globals()) for (const auto &GV : M->globals())
if (addGlobalValue(*Names, GV, Mang, SearchName, ExportedSymbolsOnly)) if (addGlobalValue(*Names, GV, Mang, SearchName, ExportedSymbolsOnly))

View File

@ -116,6 +116,9 @@ private:
/// \brief Primitive type alignment data. /// \brief Primitive type alignment data.
SmallVector<LayoutAlignElem, 16> Alignments; SmallVector<LayoutAlignElem, 16> Alignments;
/// \brief The string representation used to create this DataLayout
std::string StringRepresentation;
typedef SmallVector<PointerAlignElem, 8> PointersTy; typedef SmallVector<PointerAlignElem, 8> PointersTy;
PointersTy Pointers; PointersTy Pointers;
@ -185,6 +188,7 @@ public:
DataLayout &operator=(const DataLayout &DL) { DataLayout &operator=(const DataLayout &DL) {
clear(); clear();
StringRepresentation = DL.StringRepresentation;
BigEndian = DL.isBigEndian(); BigEndian = DL.isBigEndian();
StackNaturalAlign = DL.StackNaturalAlign; StackNaturalAlign = DL.StackNaturalAlign;
ManglingMode = DL.ManglingMode; ManglingMode = DL.ManglingMode;
@ -209,8 +213,12 @@ public:
/// \brief Returns the string representation of the DataLayout. /// \brief Returns the string representation of the DataLayout.
/// ///
/// This representation is in the same format accepted by the string /// This representation is in the same format accepted by the string
/// constructor above. /// constructor above. This should not be used to compare two DataLayout as
std::string getStringRepresentation() const; /// different string can represent the same layout.
std::string getStringRepresentation() const { return StringRepresentation; }
/// \brief Test if the DataLayout was constructed from an empty string.
bool isDefault() const { return StringRepresentation.empty(); }
/// \brief Returns true if the specified type is known to be a native integer /// \brief Returns true if the specified type is known to be a native integer
/// type supported by the CPU. /// type supported by the CPU.
@ -451,22 +459,6 @@ inline LLVMTargetDataRef wrap(const DataLayout *P) {
return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P)); return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
} }
class DataLayoutPass : public ImmutablePass {
DataLayout DL;
public:
/// This has to exist, because this is a pass, but it should never be used.
DataLayoutPass();
~DataLayoutPass();
const DataLayout &getDataLayout() const { return DL; }
static char ID; // Pass identification, replacement for typeid
bool doFinalization(Module &M) override;
bool doInitialization(Module &M) override;
};
/// Used to lazily calculate structure layout information for a target machine, /// Used to lazily calculate structure layout information for a target machine,
/// based on the DataLayout structure. /// based on the DataLayout structure.
class StructLayout { class StructLayout {

View File

@ -219,14 +219,7 @@ private:
std::string TargetTriple; ///< Platform target triple Module compiled on std::string TargetTriple; ///< Platform target triple Module compiled on
///< Format: (arch)(sub)-(vendor)-(sys0-(abi) ///< Format: (arch)(sub)-(vendor)-(sys0-(abi)
void *NamedMDSymTab; ///< NamedMDNode names. void *NamedMDSymTab; ///< NamedMDNode names.
DataLayout DL; ///< DataLayout associated with the module
// We need to keep the string because the C API expects us to own the string
// representation.
// Since we have it, we also use an empty string to represent a module without
// a DataLayout. If it has a DataLayout, these variables are in sync and the
// string is just a cache of getDataLayout()->getStringRepresentation().
std::string DataLayoutStr;
DataLayout DL;
friend class Constant; friend class Constant;
@ -256,10 +249,12 @@ public:
/// Get the data layout string for the module's target platform. This is /// Get the data layout string for the module's target platform. This is
/// equivalent to getDataLayout()->getStringRepresentation(). /// equivalent to getDataLayout()->getStringRepresentation().
const std::string &getDataLayoutStr() const { return DataLayoutStr; } const std::string getDataLayoutStr() const {
return DL.getStringRepresentation();
}
/// Get the data layout for the module's target platform. /// Get the data layout for the module's target platform.
const DataLayout *getDataLayout() const; const DataLayout &getDataLayout() const;
/// Get the target triple which is a string describing the target host. /// Get the target triple which is a string describing the target host.
/// @returns a string containing the target triple. /// @returns a string containing the target triple.
@ -293,7 +288,7 @@ public:
/// Set the data layout /// Set the data layout
void setDataLayout(StringRef Desc); void setDataLayout(StringRef Desc);
void setDataLayout(const DataLayout *Other); void setDataLayout(const DataLayout &Other);
/// Set the target triple. /// Set the target triple.
void setTargetTriple(StringRef T) { TargetTriple = T; } void setTargetTriple(StringRef T) { TargetTriple = T; }

View File

@ -192,15 +192,13 @@ void CloneAndPruneFunctionInto(Function *NewFunc, const Function *OldFunc,
class InlineFunctionInfo { class InlineFunctionInfo {
public: public:
explicit InlineFunctionInfo(CallGraph *cg = nullptr, explicit InlineFunctionInfo(CallGraph *cg = nullptr,
const DataLayout *DL = nullptr,
AliasAnalysis *AA = nullptr, AliasAnalysis *AA = nullptr,
AssumptionCacheTracker *ACT = nullptr) AssumptionCacheTracker *ACT = nullptr)
: CG(cg), DL(DL), AA(AA), ACT(ACT) {} : CG(cg), AA(AA), ACT(ACT) {}
/// CG - If non-null, InlineFunction will update the callgraph to reflect the /// CG - If non-null, InlineFunction will update the callgraph to reflect the
/// changes it makes. /// changes it makes.
CallGraph *CG; CallGraph *CG;
const DataLayout *DL;
AliasAnalysis *AA; AliasAnalysis *AA;
AssumptionCacheTracker *ACT; AssumptionCacheTracker *ACT;

View File

@ -462,9 +462,8 @@ AliasAnalysis::~AliasAnalysis() {}
/// InitializeAliasAnalysis - Subclasses must call this method to initialize the /// InitializeAliasAnalysis - Subclasses must call this method to initialize the
/// AliasAnalysis interface before any other methods are called. /// AliasAnalysis interface before any other methods are called.
/// ///
void AliasAnalysis::InitializeAliasAnalysis(Pass *P) { void AliasAnalysis::InitializeAliasAnalysis(Pass *P, const DataLayout *NewDL) {
DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>(); DL = NewDL;
DL = DLP ? &DLP->getDataLayout() : nullptr;
auto *TLIP = P->getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); auto *TLIP = P->getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
TLI = TLIP ? &TLIP->getTLI() : nullptr; TLI = TLIP ? &TLIP->getTLI() : nullptr;
AA = &P->getAnalysis<AliasAnalysis>(); AA = &P->getAnalysis<AliasAnalysis>();

View File

@ -14,6 +14,7 @@
#include "llvm/Analysis/Passes.h" #include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h" #include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
@ -76,7 +77,7 @@ namespace {
bool runOnModule(Module &M) override { bool runOnModule(Module &M) override {
this->M = &M; this->M = &M;
InitializeAliasAnalysis(this); InitializeAliasAnalysis(this, &M.getDataLayout());
return false; return false;
} }

View File

@ -44,7 +44,7 @@ namespace {
} }
bool runOnModule(Module &M) override { bool runOnModule(Module &M) override {
InitializeAliasAnalysis(this); // set up super class InitializeAliasAnalysis(this, &M.getDataLayout()); // set up super class
for(Module::global_iterator I = M.global_begin(), for(Module::global_iterator I = M.global_begin(),
E = M.global_end(); I != E; ++I) { E = M.global_end(); I != E; ++I) {

View File

@ -461,9 +461,7 @@ namespace {
initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry()); initializeBasicAliasAnalysisPass(*PassRegistry::getPassRegistry());
} }
void initializePass() override { bool doInitialization(Module &M) override;
InitializeAliasAnalysis(this);
}
void getAnalysisUsage(AnalysisUsage &AU) const override { void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<AliasAnalysis>(); AU.addRequired<AliasAnalysis>();
@ -815,6 +813,11 @@ static bool isAssumeIntrinsic(ImmutableCallSite CS) {
return false; return false;
} }
bool BasicAliasAnalysis::doInitialization(Module &M) {
InitializeAliasAnalysis(this, &M.getDataLayout());
return true;
}
/// getModRefInfo - Check to see if the specified callsite can clobber the /// getModRefInfo - Check to see if the specified callsite can clobber the
/// specified memory object. Since we only look at local properties of this /// specified memory object. Since we only look at local properties of this
/// function, we really can't say much about this query. We do, however, use /// function, we really can't say much about this query. We do, however, use

View File

@ -240,7 +240,7 @@ public:
return QueryResult; return QueryResult;
} }
void initializePass() override { InitializeAliasAnalysis(this); } bool doInitialization(Module &M) override;
}; };
void FunctionHandle::removeSelfFromCache() { void FunctionHandle::removeSelfFromCache() {
@ -1034,3 +1034,8 @@ CFLAliasAnalysis::query(const AliasAnalysis::Location &LocA,
return AliasAnalysis::NoAlias; return AliasAnalysis::NoAlias;
} }
bool CFLAliasAnalysis::doInitialization(Module &M) {
InitializeAliasAnalysis(this, &M.getDataLayout());
return true;
}

View File

@ -96,7 +96,7 @@ namespace {
} }
bool runOnModule(Module &M) override { bool runOnModule(Module &M) override {
InitializeAliasAnalysis(this); InitializeAliasAnalysis(this, &M.getDataLayout());
// Find non-addr taken globals. // Find non-addr taken globals.
AnalyzeGlobals(M); AnalyzeGlobals(M);

View File

@ -396,7 +396,6 @@ bool CallAnalyzer::visitBitCast(BitCastInst &I) {
} }
bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) { bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
const DataLayout *DL = I.getModule()->getDataLayout();
// Propagate constants through ptrtoint. // Propagate constants through ptrtoint.
Constant *COp = dyn_cast<Constant>(I.getOperand(0)); Constant *COp = dyn_cast<Constant>(I.getOperand(0));
if (!COp) if (!COp)
@ -410,7 +409,8 @@ bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
// Track base/offset pairs when converted to a plain integer provided the // Track base/offset pairs when converted to a plain integer provided the
// integer is large enough to represent the pointer. // integer is large enough to represent the pointer.
unsigned IntegerSize = I.getType()->getScalarSizeInBits(); unsigned IntegerSize = I.getType()->getScalarSizeInBits();
if (DL && IntegerSize >= DL->getPointerSizeInBits()) { const DataLayout &DL = I.getModule()->getDataLayout();
if (IntegerSize >= DL.getPointerSizeInBits()) {
std::pair<Value *, APInt> BaseAndOffset std::pair<Value *, APInt> BaseAndOffset
= ConstantOffsetPtrs.lookup(I.getOperand(0)); = ConstantOffsetPtrs.lookup(I.getOperand(0));
if (BaseAndOffset.first) if (BaseAndOffset.first)
@ -433,7 +433,6 @@ bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
} }
bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) { bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
const DataLayout *DL = I.getModule()->getDataLayout();
// Propagate constants through ptrtoint. // Propagate constants through ptrtoint.
Constant *COp = dyn_cast<Constant>(I.getOperand(0)); Constant *COp = dyn_cast<Constant>(I.getOperand(0));
if (!COp) if (!COp)
@ -448,7 +447,8 @@ bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
// modifications provided the integer is not too large. // modifications provided the integer is not too large.
Value *Op = I.getOperand(0); Value *Op = I.getOperand(0);
unsigned IntegerSize = Op->getType()->getScalarSizeInBits(); unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
if (DL && IntegerSize <= DL->getPointerSizeInBits()) { const DataLayout &DL = I.getModule()->getDataLayout();
if (IntegerSize <= DL.getPointerSizeInBits()) {
std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op); std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
if (BaseAndOffset.first) if (BaseAndOffset.first)
ConstantOffsetPtrs[&I] = BaseAndOffset; ConstantOffsetPtrs[&I] = BaseAndOffset;
@ -1333,7 +1333,7 @@ InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName() DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName()
<< "...\n"); << "...\n");
CallAnalyzer CA(Callee->getParent()->getDataLayout(), TTIWP->getTTI(*Callee), CallAnalyzer CA(&Callee->getParent()->getDataLayout(), TTIWP->getTTI(*Callee),
ACT, *Callee, Threshold); ACT, *Callee, Threshold);
bool ShouldInline = CA.analyzeCall(CS); bool ShouldInline = CA.analyzeCall(CS);

View File

@ -22,6 +22,7 @@
#include "llvm/IR/DerivedTypes.h" #include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h" #include "llvm/IR/Dominators.h"
#include "llvm/IR/Instructions.h" #include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h" #include "llvm/IR/Type.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
@ -253,8 +254,7 @@ bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &L->getHeader()->getModule()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
// Find all uses of induction variables in this loop, and categorize // Find all uses of induction variables in this loop, and categorize
// them by stride. Start by finding all of the PHI nodes in the header for // them by stride. Start by finding all of the PHI nodes in the header for

View File

@ -1117,8 +1117,7 @@ bool LazyValueInfo::runOnFunction(Function &F) {
getAnalysisIfAvailable<DominatorTreeWrapperPass>(); getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DT = DTWP ? &DTWP->getDomTree() : nullptr; DT = DTWP ? &DTWP->getDomTree() : nullptr;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();

View File

@ -36,7 +36,11 @@ void LibCallAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll(); // Does not transform code AU.setPreservesAll(); // Does not transform code
} }
bool LibCallAliasAnalysis::runOnFunction(Function &F) {
// set up super class
InitializeAliasAnalysis(this, &F.getParent()->getDataLayout());
return false;
}
/// AnalyzeLibCallDetails - Given a call to a function with the specified /// AnalyzeLibCallDetails - Given a call to a function with the specified
/// LibCallFunctionInfo, see if we can improve the mod/ref footprint of the call /// LibCallFunctionInfo, see if we can improve the mod/ref footprint of the call

View File

@ -184,8 +184,7 @@ bool Lint::runOnFunction(Function &F) {
AA = &getAnalysis<AliasAnalysis>(); AA = &getAnalysis<AliasAnalysis>();
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
visit(F); visit(F);
dbgs() << MessagesStr.str(); dbgs() << MessagesStr.str();

View File

@ -179,11 +179,10 @@ Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
// Try to get the DataLayout for this module. This may be null, in which case // Try to get the DataLayout for this module. This may be null, in which case
// the optimizations will be limited. // the optimizations will be limited.
const DataLayout *DL = ScanBB->getModule()->getDataLayout(); const DataLayout &DL = ScanBB->getModule()->getDataLayout();
// Try to get the store size for the type. // Try to get the store size for the type.
uint64_t AccessSize = DL ? DL->getTypeStoreSize(AccessTy) uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
: AA ? AA->getTypeStoreSize(AccessTy) : 0;
Value *StrippedPtr = Ptr->stripPointerCasts(); Value *StrippedPtr = Ptr->stripPointerCasts();
@ -208,7 +207,7 @@ Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
if (AreEquivalentAddressValues( if (AreEquivalentAddressValues(
LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) && LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) { CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, &DL)) {
if (AATags) if (AATags)
LI->getAAMetadata(*AATags); LI->getAAMetadata(*AATags);
return LI; return LI;
@ -221,7 +220,7 @@ Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
// those cases are unlikely.) // those cases are unlikely.)
if (AreEquivalentAddressValues(StorePtr, StrippedPtr) && if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(), CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
AccessTy, DL)) { AccessTy, &DL)) {
if (AATags) if (AATags)
SI->getAAMetadata(*AATags); SI->getAAMetadata(*AATags);
return SI->getOperand(0); return SI->getOperand(0);

View File

@ -1360,7 +1360,7 @@ void LoopAccessAnalysis::print(raw_ostream &OS, const Module *M) const {
bool LoopAccessAnalysis::runOnFunction(Function &F) { bool LoopAccessAnalysis::runOnFunction(Function &F) {
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DL = F.getParent()->getDataLayout(); DL = &F.getParent()->getDataLayout();
auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
TLI = TLIP ? &TLIP->getTLI() : nullptr; TLI = TLIP ? &TLIP->getTLI() : nullptr;
AA = &getAnalysis<AliasAnalysis>(); AA = &getAnalysis<AliasAnalysis>();

View File

@ -14,6 +14,7 @@
#include "llvm/IR/DataLayout.h" #include "llvm/IR/DataLayout.h"
#include "llvm/IR/InstIterator.h" #include "llvm/IR/InstIterator.h"
#include "llvm/IR/LLVMContext.h" #include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ErrorHandling.h" #include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
using namespace llvm; using namespace llvm;
@ -27,7 +28,6 @@ namespace {
initializeMemDerefPrinterPass(*PassRegistry::getPassRegistry()); initializeMemDerefPrinterPass(*PassRegistry::getPassRegistry());
} }
void getAnalysisUsage(AnalysisUsage &AU) const override { void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DataLayoutPass>();
AU.setPreservesAll(); AU.setPreservesAll();
} }
bool runOnFunction(Function &F) override; bool runOnFunction(Function &F) override;
@ -41,7 +41,6 @@ namespace {
char MemDerefPrinter::ID = 0; char MemDerefPrinter::ID = 0;
INITIALIZE_PASS_BEGIN(MemDerefPrinter, "print-memderefs", INITIALIZE_PASS_BEGIN(MemDerefPrinter, "print-memderefs",
"Memory Dereferenciblity of pointers in function", false, true) "Memory Dereferenciblity of pointers in function", false, true)
INITIALIZE_PASS_DEPENDENCY(DataLayoutPass)
INITIALIZE_PASS_END(MemDerefPrinter, "print-memderefs", INITIALIZE_PASS_END(MemDerefPrinter, "print-memderefs",
"Memory Dereferenciblity of pointers in function", false, true) "Memory Dereferenciblity of pointers in function", false, true)
@ -50,11 +49,11 @@ FunctionPass *llvm::createMemDerefPrinter() {
} }
bool MemDerefPrinter::runOnFunction(Function &F) { bool MemDerefPrinter::runOnFunction(Function &F) {
const DataLayout *DL = &getAnalysis<DataLayoutPass>().getDataLayout(); const DataLayout &DL = F.getParent()->getDataLayout();
for (auto &I: inst_range(F)) { for (auto &I: inst_range(F)) {
if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Value *PO = LI->getPointerOperand(); Value *PO = LI->getPointerOperand();
if (PO->isDereferenceablePointer(DL)) if (PO->isDereferenceablePointer(&DL))
Vec.push_back(PO); Vec.push_back(PO);
} }
} }

View File

@ -93,8 +93,7 @@ void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
bool MemoryDependenceAnalysis::runOnFunction(Function &F) { bool MemoryDependenceAnalysis::runOnFunction(Function &F) {
AA = &getAnalysis<AliasAnalysis>(); AA = &getAnalysis<AliasAnalysis>();
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
DominatorTreeWrapperPass *DTWP = DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>(); getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DT = DTWP ? &DTWP->getDomTree() : nullptr; DT = DTWP ? &DTWP->getDomTree() : nullptr;

View File

@ -16,6 +16,7 @@
#include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/IR/DataLayout.h" #include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h" #include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h" #include "llvm/Pass.h"
using namespace llvm; using namespace llvm;
@ -33,11 +34,11 @@ namespace {
void getAnalysisUsage(AnalysisUsage &AU) const override {} void getAnalysisUsage(AnalysisUsage &AU) const override {}
void initializePass() override { bool doInitialization(Module &M) override {
// Note: NoAA does not call InitializeAliasAnalysis because it's // Note: NoAA does not call InitializeAliasAnalysis because it's
// special and does not support chaining. // special and does not support chaining.
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr; return true;
} }
AliasResult alias(const Location &LocA, const Location &LocB) override { AliasResult alias(const Location &LocA, const Location &LocB) override {

View File

@ -7956,8 +7956,7 @@ bool ScalarEvolution::runOnFunction(Function &F) {
this->F = &F; this->F = &F;
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
return false; return false;

View File

@ -22,6 +22,7 @@
#include "llvm/Analysis/Passes.h" #include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h" #include "llvm/Pass.h"
using namespace llvm; using namespace llvm;
@ -79,7 +80,7 @@ ScalarEvolutionAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
bool bool
ScalarEvolutionAliasAnalysis::runOnFunction(Function &F) { ScalarEvolutionAliasAnalysis::runOnFunction(Function &F) {
InitializeAliasAnalysis(this); InitializeAliasAnalysis(this, &F.getParent()->getDataLayout());
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
return false; return false;
} }

View File

@ -80,7 +80,7 @@ public:
initializeScopedNoAliasAAPass(*PassRegistry::getPassRegistry()); initializeScopedNoAliasAAPass(*PassRegistry::getPassRegistry());
} }
void initializePass() override { InitializeAliasAnalysis(this); } bool doInitialization(Module &M) override;
/// getAdjustedAnalysisPointer - This method is used when a pass implements /// getAdjustedAnalysisPointer - This method is used when a pass implements
/// an analysis interface through multiple inheritance. If needed, it /// an analysis interface through multiple inheritance. If needed, it
@ -119,6 +119,11 @@ ImmutablePass *llvm::createScopedNoAliasAAPass() {
return new ScopedNoAliasAA(); return new ScopedNoAliasAA();
} }
bool ScopedNoAliasAA::doInitialization(Module &M) {
InitializeAliasAnalysis(this, &M.getDataLayout());
return true;
}
void void
ScopedNoAliasAA::getAnalysisUsage(AnalysisUsage &AU) const { ScopedNoAliasAA::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll(); AU.setPreservesAll();

View File

@ -277,7 +277,7 @@ TargetIRAnalysis::Result TargetIRAnalysis::run(Function &F) {
char TargetIRAnalysis::PassID; char TargetIRAnalysis::PassID;
TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(Function &F) { TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(Function &F) {
return Result(F.getParent()->getDataLayout()); return Result(&F.getParent()->getDataLayout());
} }
// Register the basic pass. // Register the basic pass.

View File

@ -282,9 +282,7 @@ namespace {
initializeTypeBasedAliasAnalysisPass(*PassRegistry::getPassRegistry()); initializeTypeBasedAliasAnalysisPass(*PassRegistry::getPassRegistry());
} }
void initializePass() override { bool doInitialization(Module &M) override;
InitializeAliasAnalysis(this);
}
/// getAdjustedAnalysisPointer - This method is used when a pass implements /// getAdjustedAnalysisPointer - This method is used when a pass implements
/// an analysis interface through multiple inheritance. If needed, it /// an analysis interface through multiple inheritance. If needed, it
@ -321,6 +319,11 @@ ImmutablePass *llvm::createTypeBasedAliasAnalysisPass() {
return new TypeBasedAliasAnalysis(); return new TypeBasedAliasAnalysis();
} }
bool TypeBasedAliasAnalysis::doInitialization(Module &M) {
InitializeAliasAnalysis(this, &M.getDataLayout());
return true;
}
void void
TypeBasedAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { TypeBasedAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll(); AU.setPreservesAll();

View File

@ -369,7 +369,7 @@ bool WinEHPrepare::prepareCPPEHHandlers(
Builder.SetInsertPoint(Entry->getFirstInsertionPt()); Builder.SetInsertPoint(Entry->getFirstInsertionPt());
Function *FrameAllocFn = Function *FrameAllocFn =
Intrinsic::getDeclaration(M, Intrinsic::frameallocate); Intrinsic::getDeclaration(M, Intrinsic::frameallocate);
uint64_t EHAllocSize = M->getDataLayout()->getTypeAllocSize(EHDataStructTy); uint64_t EHAllocSize = M->getDataLayout().getTypeAllocSize(EHDataStructTy);
Value *FrameAllocArgs[] = { Value *FrameAllocArgs[] = {
ConstantInt::get(Type::getInt32Ty(Context), EHAllocSize)}; ConstantInt::get(Type::getInt32Ty(Context), EHAllocSize)};
CallInst *FrameAlloc = CallInst *FrameAlloc =
@ -538,7 +538,7 @@ bool WinEHPrepare::outlineHandler(HandlerType CatchOrCleanup, Function *SrcFn,
CloneAndPruneIntoFromInst( CloneAndPruneIntoFromInst(
Handler, SrcFn, ++II, VMap, Handler, SrcFn, ++II, VMap,
/*ModuleLevelChanges=*/false, Returns, "", &InlinedFunctionInfo, /*ModuleLevelChanges=*/false, Returns, "", &InlinedFunctionInfo,
SrcFn->getParent()->getDataLayout(), Director.get()); &SrcFn->getParent()->getDataLayout(), Director.get());
// Move all the instructions in the first cloned block into our entry block. // Move all the instructions in the first cloned block into our entry block.
BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry)); BasicBlock *FirstClonedBB = std::next(Function::iterator(Entry));

View File

@ -137,8 +137,7 @@ std::unique_ptr<MemoryBuffer> MCJIT::emitObject(Module *M) {
legacy::PassManager PM; legacy::PassManager PM;
M->setDataLayout(TM->getDataLayout()); M->setDataLayout(*TM->getDataLayout());
PM.add(new DataLayoutPass());
// The RuntimeDyld will take ownership of this shortly // The RuntimeDyld will take ownership of this shortly
SmallVector<char, 4096> ObjBufferSV; SmallVector<char, 4096> ObjBufferSV;

View File

@ -133,8 +133,8 @@ public:
// If this module doesn't have a DataLayout attached then attach the // If this module doesn't have a DataLayout attached then attach the
// default. // default.
if (!M->getDataLayout()) if (M->getDataLayout().isDefault())
M->setDataLayout(getDataLayout()); M->setDataLayout(*getDataLayout());
Modules.push_back(std::move(M)); Modules.push_back(std::move(M));
std::vector<Module *> Ms; std::vector<Module *> Ms;

View File

@ -33,11 +33,6 @@
#include <cstdlib> #include <cstdlib>
using namespace llvm; using namespace llvm;
// Handle the Pass registration stuff necessary to use DataLayout's.
INITIALIZE_PASS(DataLayoutPass, "datalayout", "Data Layout", false, true)
char DataLayoutPass::ID = 0;
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// Support for StructLayout // Support for StructLayout
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
@ -221,6 +216,7 @@ static unsigned inBytes(unsigned Bits) {
} }
void DataLayout::parseSpecifier(StringRef Desc) { void DataLayout::parseSpecifier(StringRef Desc) {
StringRepresentation = Desc;
while (!Desc.empty()) { while (!Desc.empty()) {
// Split at '-'. // Split at '-'.
std::pair<StringRef, StringRef> Split = split(Desc, '-'); std::pair<StringRef, StringRef> Split = split(Desc, '-');
@ -378,13 +374,7 @@ DataLayout::DataLayout(const Module *M) : LayoutMap(nullptr) {
init(M); init(M);
} }
void DataLayout::init(const Module *M) { void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
const DataLayout *Other = M->getDataLayout();
if (Other)
*this = *Other;
else
reset("");
}
bool DataLayout::operator==(const DataLayout &Other) const { bool DataLayout::operator==(const DataLayout &Other) const {
bool Ret = BigEndian == Other.BigEndian && bool Ret = BigEndian == Other.BigEndian &&
@ -392,7 +382,7 @@ bool DataLayout::operator==(const DataLayout &Other) const {
ManglingMode == Other.ManglingMode && ManglingMode == Other.ManglingMode &&
LegalIntWidths == Other.LegalIntWidths && LegalIntWidths == Other.LegalIntWidths &&
Alignments == Other.Alignments && Pointers == Other.Pointers; Alignments == Other.Alignments && Pointers == Other.Pointers;
assert(Ret == (getStringRepresentation() == Other.getStringRepresentation())); // Note: getStringRepresentation() might differs, it is not canonicalized
return Ret; return Ret;
} }
@ -567,68 +557,6 @@ const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
return L; return L;
} }
std::string DataLayout::getStringRepresentation() const {
std::string Result;
raw_string_ostream OS(Result);
OS << (BigEndian ? "E" : "e");
switch (ManglingMode) {
case MM_None:
break;
case MM_ELF:
OS << "-m:e";
break;
case MM_MachO:
OS << "-m:o";
break;
case MM_WINCOFF:
OS << "-m:w";
break;
case MM_Mips:
OS << "-m:m";
break;
}
for (const PointerAlignElem &PI : Pointers) {
// Skip default.
if (PI.AddressSpace == 0 && PI.ABIAlign == 8 && PI.PrefAlign == 8 &&
PI.TypeByteWidth == 8)
continue;
OS << "-p";
if (PI.AddressSpace) {
OS << PI.AddressSpace;
}
OS << ":" << PI.TypeByteWidth*8 << ':' << PI.ABIAlign*8;
if (PI.PrefAlign != PI.ABIAlign)
OS << ':' << PI.PrefAlign*8;
}
for (const LayoutAlignElem &AI : Alignments) {
if (std::find(std::begin(DefaultAlignments), std::end(DefaultAlignments),
AI) != std::end(DefaultAlignments))
continue;
OS << '-' << (char)AI.AlignType;
if (AI.TypeBitWidth)
OS << AI.TypeBitWidth;
OS << ':' << AI.ABIAlign*8;
if (AI.ABIAlign != AI.PrefAlign)
OS << ':' << AI.PrefAlign*8;
}
if (!LegalIntWidths.empty()) {
OS << "-n" << (unsigned)LegalIntWidths[0];
for (unsigned i = 1, e = LegalIntWidths.size(); i != e; ++i)
OS << ':' << (unsigned)LegalIntWidths[i];
}
if (StackNaturalAlign)
OS << "-S" << StackNaturalAlign*8;
return OS.str();
}
unsigned DataLayout::getPointerABIAlignment(unsigned AS) const { unsigned DataLayout::getPointerABIAlignment(unsigned AS) const {
PointersTy::const_iterator I = findPointerLowerBound(AS); PointersTy::const_iterator I = findPointerLowerBound(AS);
@ -844,18 +772,3 @@ unsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
return Log2_32(getPreferredAlignment(GV)); return Log2_32(getPreferredAlignment(GV));
} }
DataLayoutPass::DataLayoutPass() : ImmutablePass(ID), DL("") {
initializeDataLayoutPassPass(*PassRegistry::getPassRegistry());
}
DataLayoutPass::~DataLayoutPass() {}
bool DataLayoutPass::doInitialization(Module &M) {
DL.init(&M);
return false;
}
bool DataLayoutPass::doFinalization(Module &M) {
DL.reset("");
return false;
}

View File

@ -365,31 +365,11 @@ void Module::addModuleFlag(MDNode *Node) {
void Module::setDataLayout(StringRef Desc) { void Module::setDataLayout(StringRef Desc) {
DL.reset(Desc); DL.reset(Desc);
if (Desc.empty()) {
DataLayoutStr = "";
} else {
DataLayoutStr = DL.getStringRepresentation();
// DataLayoutStr is now equivalent to Desc, but since the representation
// is not unique, they may not be identical.
}
} }
void Module::setDataLayout(const DataLayout *Other) { void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
if (!Other) {
DataLayoutStr = "";
DL.reset("");
} else {
DL = *Other;
DataLayoutStr = DL.getStringRepresentation();
}
}
const DataLayout *Module::getDataLayout() const { const DataLayout &Module::getDataLayout() const { return DL; }
if (DataLayoutStr.empty())
return nullptr;
return &DL;
}
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// Methods to control the materialization of GlobalValues in the Module. // Methods to control the materialization of GlobalValues in the Module.

View File

@ -529,9 +529,8 @@ bool LTOCodeGenerator::optimize(bool DisableOpt,
legacy::PassManager passes; legacy::PassManager passes;
// Add an appropriate DataLayout instance for this module... // Add an appropriate DataLayout instance for this module...
mergedModule->setDataLayout(TargetMach->getDataLayout()); mergedModule->setDataLayout(*TargetMach->getDataLayout());
passes.add(new DataLayoutPass());
passes.add( passes.add(
createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis())); createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
@ -567,8 +566,6 @@ bool LTOCodeGenerator::compileOptimized(raw_ostream &out, std::string &errMsg) {
legacy::PassManager codeGenPasses; legacy::PassManager codeGenPasses;
codeGenPasses.add(new DataLayoutPass());
formatted_raw_ostream Out(out); formatted_raw_ostream Out(out);
// If the bitcode files contain ARC code and were compiled with optimization, // If the bitcode files contain ARC code and were compiled with optimization,

View File

@ -229,7 +229,7 @@ LTOModule *LTOModule::makeLTOModule(MemoryBufferRef Buffer,
TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr, TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
options); options);
M->setDataLayout(target->getDataLayout()); M->setDataLayout(*target->getDataLayout());
std::unique_ptr<object::IRObjectFile> IRObj( std::unique_ptr<object::IRObjectFile> IRObj(
new object::IRObjectFile(Buffer, std::move(M))); new object::IRObjectFile(Buffer, std::move(M)));

View File

@ -672,17 +672,12 @@ bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
getComdatLeader(SrcM, ComdatName, SrcGV)) getComdatLeader(SrcM, ComdatName, SrcGV))
return true; return true;
const DataLayout *DstDL = DstM->getDataLayout(); const DataLayout &DstDL = DstM->getDataLayout();
const DataLayout *SrcDL = SrcM->getDataLayout(); const DataLayout &SrcDL = SrcM->getDataLayout();
if (!DstDL || !SrcDL) {
return emitError(
"Linking COMDATs named '" + ComdatName +
"': can't do size dependent selection without DataLayout!");
}
uint64_t DstSize = uint64_t DstSize =
DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
uint64_t SrcSize = uint64_t SrcSize =
SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
if (Result == Comdat::SelectionKind::ExactMatch) { if (Result == Comdat::SelectionKind::ExactMatch) {
if (SrcGV->getInitializer() != DstGV->getInitializer()) if (SrcGV->getInitializer() != DstGV->getInitializer())
return emitError("Linking COMDATs named '" + ComdatName + return emitError("Linking COMDATs named '" + ComdatName +
@ -1482,11 +1477,10 @@ bool ModuleLinker::run() {
// Inherit the target data from the source module if the destination module // Inherit the target data from the source module if the destination module
// doesn't have one already. // doesn't have one already.
if (!DstM->getDataLayout() && SrcM->getDataLayout()) if (DstM->getDataLayout().isDefault())
DstM->setDataLayout(SrcM->getDataLayout()); DstM->setDataLayout(SrcM->getDataLayout());
if (SrcM->getDataLayout() && DstM->getDataLayout() && if (SrcM->getDataLayout() != DstM->getDataLayout()) {
*SrcM->getDataLayout() != *DstM->getDataLayout()) {
emitWarning("Linking two modules of different data layouts: '" + emitWarning("Linking two modules of different data layouts: '" +
SrcM->getModuleIdentifier() + "' is '" + SrcM->getModuleIdentifier() + "' is '" +
SrcM->getDataLayoutStr() + "' whereas '" + SrcM->getDataLayoutStr() + "' whereas '" +

View File

@ -36,12 +36,9 @@ using namespace object;
IRObjectFile::IRObjectFile(MemoryBufferRef Object, std::unique_ptr<Module> Mod) IRObjectFile::IRObjectFile(MemoryBufferRef Object, std::unique_ptr<Module> Mod)
: SymbolicFile(Binary::ID_IR, Object), M(std::move(Mod)) { : SymbolicFile(Binary::ID_IR, Object), M(std::move(Mod)) {
// If we have a DataLayout, setup a mangler. // Setup a mangler with the DataLayout.
const DataLayout *DL = M->getDataLayout(); const DataLayout &DL = M->getDataLayout();
if (!DL) Mang.reset(new Mangler(&DL));
return;
Mang.reset(new Mangler(DL));
const std::string &InlineAsm = M->getModuleInlineAsm(); const std::string &InlineAsm = M->getModuleInlineAsm();
if (InlineAsm.empty()) if (InlineAsm.empty())

View File

@ -1981,7 +1981,8 @@ void CppWriter::printModule(const std::string& fname,
printEscapedString(mName); printEscapedString(mName);
Out << "\", getGlobalContext());"; Out << "\", getGlobalContext());";
if (!TheModule->getTargetTriple().empty()) { if (!TheModule->getTargetTriple().empty()) {
nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayout() << "\");"; nl(Out) << "mod->setDataLayout(\"" << TheModule->getDataLayoutStr()
<< "\");";
} }
if (!TheModule->getTargetTriple().empty()) { if (!TheModule->getTargetTriple().empty()) {
nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple() nl(Out) << "mod->setTargetTriple(\"" << TheModule->getTargetTriple()

View File

@ -32,7 +32,6 @@ public:
NVPTXAllocaHoisting() : FunctionPass(ID) {} NVPTXAllocaHoisting() : FunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const override { void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DataLayoutPass>();
AU.addPreserved<MachineFunctionAnalysis>(); AU.addPreserved<MachineFunctionAnalysis>();
AU.addPreserved<StackProtector>(); AU.addPreserved<StackProtector>();
} }

View File

@ -22,6 +22,9 @@
#include "llvm/IR/Intrinsics.h" #include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h" #include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h" #include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h"
#define DEBUG_TYPE "nvptx"
using namespace llvm; using namespace llvm;
@ -104,7 +107,7 @@ bool NVPTXLowerAggrCopies::runOnFunction(Function &F) {
SmallVector<MemTransferInst *, 4> aggrMemcpys; SmallVector<MemTransferInst *, 4> aggrMemcpys;
SmallVector<MemSetInst *, 4> aggrMemsets; SmallVector<MemSetInst *, 4> aggrMemsets;
const DataLayout *DL = &getAnalysis<DataLayoutPass>().getDataLayout(); const DataLayout &DL = F.getParent()->getDataLayout();
LLVMContext &Context = F.getParent()->getContext(); LLVMContext &Context = F.getParent()->getContext();
// //
@ -120,7 +123,7 @@ bool NVPTXLowerAggrCopies::runOnFunction(Function &F) {
if (load->hasOneUse() == false) if (load->hasOneUse() == false)
continue; continue;
if (DL->getTypeStoreSize(load->getType()) < MaxAggrCopySize) if (DL.getTypeStoreSize(load->getType()) < MaxAggrCopySize)
continue; continue;
User *use = load->user_back(); User *use = load->user_back();
@ -166,7 +169,7 @@ bool NVPTXLowerAggrCopies::runOnFunction(Function &F) {
StoreInst *store = dyn_cast<StoreInst>(*load->user_begin()); StoreInst *store = dyn_cast<StoreInst>(*load->user_begin());
Value *srcAddr = load->getOperand(0); Value *srcAddr = load->getOperand(0);
Value *dstAddr = store->getOperand(1); Value *dstAddr = store->getOperand(1);
unsigned numLoads = DL->getTypeStoreSize(load->getType()); unsigned numLoads = DL.getTypeStoreSize(load->getType());
Value *len = ConstantInt::get(Type::getInt32Ty(Context), numLoads); Value *len = ConstantInt::get(Type::getInt32Ty(Context), numLoads);
convertTransferToLoop(store, srcAddr, dstAddr, len, load->isVolatile(), convertTransferToLoop(store, srcAddr, dstAddr, len, load->isVolatile(),

View File

@ -29,7 +29,6 @@ struct NVPTXLowerAggrCopies : public FunctionPass {
NVPTXLowerAggrCopies() : FunctionPass(ID) {} NVPTXLowerAggrCopies() : FunctionPass(ID) {}
void getAnalysisUsage(AnalysisUsage &AU) const override { void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DataLayoutPass>();
AU.addPreserved<MachineFunctionAnalysis>(); AU.addPreserved<MachineFunctionAnalysis>();
AU.addPreserved<StackProtector>(); AU.addPreserved<StackProtector>();
} }

View File

@ -171,8 +171,7 @@ bool PPCCTRLoops::runOnFunction(Function &F) {
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
LibInfo = TLIP ? &TLIP->getTLI() : nullptr; LibInfo = TLIP ? &TLIP->getTLI() : nullptr;

View File

@ -104,7 +104,7 @@ FunctionPass *llvm::createPPCLoopDataPrefetchPass() { return new PPCLoopDataPref
bool PPCLoopDataPrefetch::runOnFunction(Function &F) { bool PPCLoopDataPrefetch::runOnFunction(Function &F) {
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DL = F.getParent()->getDataLayout(); DL = &F.getParent()->getDataLayout();
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);

View File

@ -36,6 +36,7 @@
#include "llvm/IR/Dominators.h" #include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h" #include "llvm/IR/Function.h"
#include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
#include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Scalar.h"
@ -84,7 +85,6 @@ namespace {
PPCTargetMachine *TM; PPCTargetMachine *TM;
LoopInfo *LI; LoopInfo *LI;
ScalarEvolution *SE; ScalarEvolution *SE;
const DataLayout *DL;
}; };
} }
@ -141,9 +141,6 @@ bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
DL = DLP ? &DLP->getDataLayout() : 0;
bool MadeChange = false; bool MadeChange = false;
for (LoopInfo::iterator I = LI->begin(), E = LI->end(); for (LoopInfo::iterator I = LI->begin(), E = LI->end();
@ -158,9 +155,6 @@ bool PPCLoopPreIncPrep::runOnFunction(Function &F) {
bool PPCLoopPreIncPrep::runOnLoop(Loop *L) { bool PPCLoopPreIncPrep::runOnLoop(Loop *L) {
bool MadeChange = false; bool MadeChange = false;
if (!DL)
return MadeChange;
// Only prep. the inner-most loop // Only prep. the inner-most loop
if (!L->empty()) if (!L->empty())
return MadeChange; return MadeChange;

View File

@ -87,7 +87,7 @@ bool AMDGPUPromoteAlloca::runOnFunction(Function &F) {
continue; continue;
if (Use->getParent()->getParent() == &F) if (Use->getParent()->getParent() == &F)
LocalMemAvailable -= LocalMemAvailable -=
Mod->getDataLayout()->getTypeAllocSize(GVTy->getElementType()); Mod->getDataLayout().getTypeAllocSize(GVTy->getElementType());
} }
} }
} }
@ -276,8 +276,8 @@ void AMDGPUPromoteAlloca::visitAlloca(AllocaInst &I) {
// value from the reqd_work_group_size function attribute if it is // value from the reqd_work_group_size function attribute if it is
// available. // available.
unsigned WorkGroupSize = 256; unsigned WorkGroupSize = 256;
int AllocaSize = WorkGroupSize * int AllocaSize =
Mod->getDataLayout()->getTypeAllocSize(AllocaTy); WorkGroupSize * Mod->getDataLayout().getTypeAllocSize(AllocaTy);
if (AllocaSize > LocalMemAvailable) { if (AllocaSize > LocalMemAvailable) {
DEBUG(dbgs() << " Not enough local memory to promote alloca.\n"); DEBUG(dbgs() << " Not enough local memory to promote alloca.\n");

View File

@ -34,7 +34,6 @@ inline LLVMTargetLibraryInfoRef wrap(const TargetLibraryInfoImpl *P) {
} }
void llvm::initializeTarget(PassRegistry &Registry) { void llvm::initializeTarget(PassRegistry &Registry) {
initializeDataLayoutPassPass(Registry);
initializeTargetLibraryInfoWrapperPassPass(Registry); initializeTargetLibraryInfoWrapperPassPass(Registry);
initializeTargetTransformInfoWrapperPassPass(Registry); initializeTargetTransformInfoWrapperPassPass(Registry);
} }
@ -48,9 +47,6 @@ LLVMTargetDataRef LLVMCreateTargetData(const char *StringRep) {
} }
void LLVMAddTargetData(LLVMTargetDataRef TD, LLVMPassManagerRef PM) { void LLVMAddTargetData(LLVMTargetDataRef TD, LLVMPassManagerRef PM) {
// The DataLayoutPass must now be in sync with the module. Unfortunatelly we
// cannot enforce that from the C api.
unwrap(PM)->add(new DataLayoutPass());
} }
void LLVMAddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI, void LLVMAddTargetLibraryInfo(LLVMTargetLibraryInfoRef TLI,

View File

@ -198,8 +198,7 @@ static LLVMBool LLVMTargetMachineEmit(LLVMTargetMachineRef T, LLVMModuleRef M,
*ErrorMessage = strdup(error.c_str()); *ErrorMessage = strdup(error.c_str());
return true; return true;
} }
Mod->setDataLayout(td); Mod->setDataLayout(*td);
pass.add(new DataLayoutPass());
TargetMachine::CodeGenFileType ft; TargetMachine::CodeGenFileType ft;
switch (codegen) { switch (codegen) {

View File

@ -109,9 +109,6 @@ Pass *llvm::createArgumentPromotionPass(unsigned maxElements) {
bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) { bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) {
bool Changed = false, LocalChange; bool Changed = false, LocalChange;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
DL = DLP ? &DLP->getDataLayout() : nullptr;
do { // Iterate until we stop promoting from this SCC. do { // Iterate until we stop promoting from this SCC.
LocalChange = false; LocalChange = false;
// Attempt to promote arguments from all functions in this SCC. // Attempt to promote arguments from all functions in this SCC.
@ -210,6 +207,8 @@ CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
// Make sure that it is local to this module. // Make sure that it is local to this module.
if (!F || !F->hasLocalLinkage()) return nullptr; if (!F || !F->hasLocalLinkage()) return nullptr;
DL = &F->getParent()->getDataLayout();
// First check: see if there are any pointer arguments! If not, quick exit. // First check: see if there are any pointer arguments! If not, quick exit.
SmallVector<Argument*, 16> PointerArgs; SmallVector<Argument*, 16> PointerArgs;
for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)

View File

@ -103,8 +103,7 @@ unsigned ConstantMerge::getAlignment(GlobalVariable *GV) const {
} }
bool ConstantMerge::runOnModule(Module &M) { bool ConstantMerge::runOnModule(Module &M) {
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
// Find all the globals that are marked "used". These cannot be merged. // Find all the globals that are marked "used". These cannot be merged.
SmallPtrSet<const GlobalValue*, 8> UsedGlobals; SmallPtrSet<const GlobalValue*, 8> UsedGlobals;

View File

@ -86,7 +86,7 @@ namespace {
const GlobalStatus &GS); const GlobalStatus &GS);
bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn); bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
const DataLayout *DL; // const DataLayout *DL;
TargetLibraryInfo *TLI; TargetLibraryInfo *TLI;
SmallSet<const Comdat *, 8> NotDiscardableComdats; SmallSet<const Comdat *, 8> NotDiscardableComdats;
}; };
@ -269,7 +269,7 @@ static bool CleanupPointerRootUsers(GlobalVariable *GV,
/// quick scan over the use list to clean up the easy and obvious cruft. This /// quick scan over the use list to clean up the easy and obvious cruft. This
/// returns true if it made a change. /// returns true if it made a change.
static bool CleanupConstantGlobalUsers(Value *V, Constant *Init, static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
const DataLayout *DL, const DataLayout &DL,
TargetLibraryInfo *TLI) { TargetLibraryInfo *TLI) {
bool Changed = false; bool Changed = false;
// Note that we need to use a weak value handle for the worklist items. When // Note that we need to use a weak value handle for the worklist items. When
@ -318,8 +318,8 @@ static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
// and will invalidate our notion of what Init is. // and will invalidate our notion of what Init is.
Constant *SubInit = nullptr; Constant *SubInit = nullptr;
if (!isa<ConstantExpr>(GEP->getOperand(0))) { if (!isa<ConstantExpr>(GEP->getOperand(0))) {
ConstantExpr *CE = ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(
dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, DL, TLI)); ConstantFoldInstruction(GEP, &DL, TLI));
if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr) if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE); SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
@ -739,7 +739,7 @@ static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
/// if the loaded value is dynamically null, then we know that they cannot be /// if the loaded value is dynamically null, then we know that they cannot be
/// reachable with a null optimize away the load. /// reachable with a null optimize away the load.
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
const DataLayout *DL, const DataLayout &DL,
TargetLibraryInfo *TLI) { TargetLibraryInfo *TLI) {
bool Changed = false; bool Changed = false;
@ -802,11 +802,11 @@ static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
/// ConstantPropUsersOf - Walk the use list of V, constant folding all of the /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
/// instructions that are foldable. /// instructions that are foldable.
static void ConstantPropUsersOf(Value *V, const DataLayout *DL, static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
TargetLibraryInfo *TLI) { TargetLibraryInfo *TLI) {
for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; ) for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
if (Instruction *I = dyn_cast<Instruction>(*UI++)) if (Instruction *I = dyn_cast<Instruction>(*UI++))
if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) { if (Constant *NewC = ConstantFoldInstruction(I, &DL, TLI)) {
I->replaceAllUsesWith(NewC); I->replaceAllUsesWith(NewC);
// Advance UI to the next non-I use to avoid invalidating it! // Advance UI to the next non-I use to avoid invalidating it!
@ -822,12 +822,10 @@ static void ConstantPropUsersOf(Value *V, const DataLayout *DL,
/// the specified malloc. Because it is always the result of the specified /// the specified malloc. Because it is always the result of the specified
/// malloc, there is no reason to actually DO the malloc. Instead, turn the /// malloc, there is no reason to actually DO the malloc. Instead, turn the
/// malloc into a global, and any loads of GV as uses of the new global. /// malloc into a global, and any loads of GV as uses of the new global.
static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, static GlobalVariable *
CallInst *CI, OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy,
Type *AllocTy, ConstantInt *NElements, const DataLayout &DL,
ConstantInt *NElements, TargetLibraryInfo *TLI) {
const DataLayout *DL,
TargetLibraryInfo *TLI) {
DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n'); DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
Type *GlobalType; Type *GlobalType;
@ -1271,7 +1269,7 @@ static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
/// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
/// it up into multiple allocations of arrays of the fields. /// it up into multiple allocations of arrays of the fields.
static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI, static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
Value *NElems, const DataLayout *DL, Value *NElems, const DataLayout &DL,
const TargetLibraryInfo *TLI) { const TargetLibraryInfo *TLI) {
DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n'); DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
Type *MAT = getMallocAllocatedType(CI, TLI); Type *MAT = getMallocAllocatedType(CI, TLI);
@ -1301,10 +1299,10 @@ static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
GV->getThreadLocalMode()); GV->getThreadLocalMode());
FieldGlobals.push_back(NGV); FieldGlobals.push_back(NGV);
unsigned TypeSize = DL->getTypeAllocSize(FieldTy); unsigned TypeSize = DL.getTypeAllocSize(FieldTy);
if (StructType *ST = dyn_cast<StructType>(FieldTy)) if (StructType *ST = dyn_cast<StructType>(FieldTy))
TypeSize = DL->getStructLayout(ST)->getSizeInBytes(); TypeSize = DL.getStructLayout(ST)->getSizeInBytes();
Type *IntPtrTy = DL->getIntPtrType(CI->getType()); Type *IntPtrTy = DL.getIntPtrType(CI->getType());
Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy, Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
ConstantInt::get(IntPtrTy, TypeSize), ConstantInt::get(IntPtrTy, TypeSize),
NElems, nullptr, NElems, nullptr,
@ -1459,16 +1457,12 @@ static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
/// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
/// pointer global variable with a single value stored it that is a malloc or /// pointer global variable with a single value stored it that is a malloc or
/// cast of malloc. /// cast of malloc.
static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI,
CallInst *CI,
Type *AllocTy, Type *AllocTy,
AtomicOrdering Ordering, AtomicOrdering Ordering,
Module::global_iterator &GVI, Module::global_iterator &GVI,
const DataLayout *DL, const DataLayout &DL,
TargetLibraryInfo *TLI) { TargetLibraryInfo *TLI) {
if (!DL)
return false;
// If this is a malloc of an abstract type, don't touch it. // If this is a malloc of an abstract type, don't touch it.
if (!AllocTy->isSized()) if (!AllocTy->isSized())
return false; return false;
@ -1496,7 +1490,7 @@ static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
// This eliminates dynamic allocation, avoids an indirection accessing the // This eliminates dynamic allocation, avoids an indirection accessing the
// data, and exposes the resultant global to further GlobalOpt. // data, and exposes the resultant global to further GlobalOpt.
// We cannot optimize the malloc if we cannot determine malloc array size. // We cannot optimize the malloc if we cannot determine malloc array size.
Value *NElems = getMallocArraySize(CI, DL, TLI, true); Value *NElems = getMallocArraySize(CI, &DL, TLI, true);
if (!NElems) if (!NElems)
return false; return false;
@ -1504,7 +1498,7 @@ static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
// Restrict this transformation to only working on small allocations // Restrict this transformation to only working on small allocations
// (2048 bytes currently), as we don't want to introduce a 16M global or // (2048 bytes currently), as we don't want to introduce a 16M global or
// something. // something.
if (NElements->getZExtValue() * DL->getTypeAllocSize(AllocTy) < 2048) { if (NElements->getZExtValue() * DL.getTypeAllocSize(AllocTy) < 2048) {
GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI); GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI);
return true; return true;
} }
@ -1534,8 +1528,8 @@ static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
// If this is a fixed size array, transform the Malloc to be an alloc of // If this is a fixed size array, transform the Malloc to be an alloc of
// structs. malloc [100 x struct],1 -> malloc struct, 100 // structs. malloc [100 x struct],1 -> malloc struct, 100
if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) { if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
Type *IntPtrTy = DL->getIntPtrType(CI->getType()); Type *IntPtrTy = DL.getIntPtrType(CI->getType());
unsigned TypeSize = DL->getStructLayout(AllocSTy)->getSizeInBytes(); unsigned TypeSize = DL.getStructLayout(AllocSTy)->getSizeInBytes();
Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize); Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements()); Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy, Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
@ -1550,7 +1544,7 @@ static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
CI = cast<CallInst>(Malloc); CI = cast<CallInst>(Malloc);
} }
GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true), GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, &DL, TLI, true),
DL, TLI); DL, TLI);
return true; return true;
} }
@ -1563,7 +1557,7 @@ static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
AtomicOrdering Ordering, AtomicOrdering Ordering,
Module::global_iterator &GVI, Module::global_iterator &GVI,
const DataLayout *DL, const DataLayout &DL,
TargetLibraryInfo *TLI) { TargetLibraryInfo *TLI) {
// Ignore no-op GEPs and bitcasts. // Ignore no-op GEPs and bitcasts.
StoredOnceVal = StoredOnceVal->stripPointerCasts(); StoredOnceVal = StoredOnceVal->stripPointerCasts();
@ -1733,6 +1727,7 @@ bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV, bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Module::global_iterator &GVI, Module::global_iterator &GVI,
const GlobalStatus &GS) { const GlobalStatus &GS) {
auto &DL = GV->getParent()->getDataLayout();
// If this is a first class global and has only one accessing function // If this is a first class global and has only one accessing function
// and this function is main (which we know is not recursive), we replace // and this function is main (which we know is not recursive), we replace
// the global with a local alloca in this function. // the global with a local alloca in this function.
@ -1804,12 +1799,10 @@ bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
++NumMarked; ++NumMarked;
return true; return true;
} else if (!GV->getInitializer()->getType()->isSingleValueType()) { } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
if (DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>()) { const DataLayout &DL = GV->getParent()->getDataLayout();
const DataLayout &DL = DLP->getDataLayout(); if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) {
if (GlobalVariable *FirstNewGV = SRAGlobal(GV, DL)) { GVI = FirstNewGV; // Don't skip the newly produced globals!
GVI = FirstNewGV; // Don't skip the newly produced globals! return true;
return true;
}
} }
} else if (GS.StoredType == GlobalStatus::StoredOnce) { } else if (GS.StoredType == GlobalStatus::StoredOnce) {
// If the initial value for the global was an undef value, and if only // If the initial value for the global was an undef value, and if only
@ -1954,7 +1947,8 @@ bool GlobalOpt::OptimizeGlobalVars(Module &M) {
// Simplify the initializer. // Simplify the initializer.
if (GV->hasInitializer()) if (GV->hasInitializer())
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) { if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
Constant *New = ConstantFoldConstantExpression(CE, DL, TLI); auto &DL = M.getDataLayout();
Constant *New = ConstantFoldConstantExpression(CE, &DL, TLI);
if (New && New != CE) if (New && New != CE)
GV->setInitializer(New); GV->setInitializer(New);
} }
@ -1971,9 +1965,8 @@ bool GlobalOpt::OptimizeGlobalVars(Module &M) {
static inline bool static inline bool
isSimpleEnoughValueToCommit(Constant *C, isSimpleEnoughValueToCommit(Constant *C,
SmallPtrSetImpl<Constant*> &SimpleConstants, SmallPtrSetImpl<Constant *> &SimpleConstants,
const DataLayout *DL); const DataLayout &DL);
/// isSimpleEnoughValueToCommit - Return true if the specified constant can be /// isSimpleEnoughValueToCommit - Return true if the specified constant can be
/// handled by the code generator. We don't want to generate something like: /// handled by the code generator. We don't want to generate something like:
@ -1983,9 +1976,10 @@ isSimpleEnoughValueToCommit(Constant *C,
/// This function should be called if C was not found (but just got inserted) /// This function should be called if C was not found (but just got inserted)
/// in SimpleConstants to avoid having to rescan the same constants all the /// in SimpleConstants to avoid having to rescan the same constants all the
/// time. /// time.
static bool isSimpleEnoughValueToCommitHelper(Constant *C, static bool
SmallPtrSetImpl<Constant*> &SimpleConstants, isSimpleEnoughValueToCommitHelper(Constant *C,
const DataLayout *DL) { SmallPtrSetImpl<Constant *> &SimpleConstants,
const DataLayout &DL) {
// Simple global addresses are supported, do not allow dllimport or // Simple global addresses are supported, do not allow dllimport or
// thread-local globals. // thread-local globals.
if (auto *GV = dyn_cast<GlobalValue>(C)) if (auto *GV = dyn_cast<GlobalValue>(C))
@ -2019,8 +2013,8 @@ static bool isSimpleEnoughValueToCommitHelper(Constant *C,
case Instruction::PtrToInt: case Instruction::PtrToInt:
// int <=> ptr is fine if the int type is the same size as the // int <=> ptr is fine if the int type is the same size as the
// pointer type. // pointer type.
if (!DL || DL->getTypeSizeInBits(CE->getType()) != if (DL.getTypeSizeInBits(CE->getType()) !=
DL->getTypeSizeInBits(CE->getOperand(0)->getType())) DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
return false; return false;
return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL); return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
@ -2042,8 +2036,8 @@ static bool isSimpleEnoughValueToCommitHelper(Constant *C,
static inline bool static inline bool
isSimpleEnoughValueToCommit(Constant *C, isSimpleEnoughValueToCommit(Constant *C,
SmallPtrSetImpl<Constant*> &SimpleConstants, SmallPtrSetImpl<Constant *> &SimpleConstants,
const DataLayout *DL) { const DataLayout &DL) {
// If we already checked this constant, we win. // If we already checked this constant, we win.
if (!SimpleConstants.insert(C).second) if (!SimpleConstants.insert(C).second)
return true; return true;
@ -2174,8 +2168,8 @@ namespace {
/// Once an evaluation call fails, the evaluation object should not be reused. /// Once an evaluation call fails, the evaluation object should not be reused.
class Evaluator { class Evaluator {
public: public:
Evaluator(const DataLayout *DL, const TargetLibraryInfo *TLI) Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI)
: DL(DL), TLI(TLI) { : DL(DL), TLI(TLI) {
ValueStack.emplace_back(); ValueStack.emplace_back();
} }
@ -2249,7 +2243,7 @@ private:
/// simple enough to live in a static initializer of a global. /// simple enough to live in a static initializer of a global.
SmallPtrSet<Constant*, 8> SimpleConstants; SmallPtrSet<Constant*, 8> SimpleConstants;
const DataLayout *DL; const DataLayout &DL;
const TargetLibraryInfo *TLI; const TargetLibraryInfo *TLI;
}; };
@ -2302,7 +2296,7 @@ bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
Constant *Ptr = getVal(SI->getOperand(1)); Constant *Ptr = getVal(SI->getOperand(1));
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) { if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr); DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
Ptr = ConstantFoldConstantExpression(CE, DL, TLI); Ptr = ConstantFoldConstantExpression(CE, &DL, TLI);
DEBUG(dbgs() << "; To: " << *Ptr << "\n"); DEBUG(dbgs() << "; To: " << *Ptr << "\n");
} }
if (!isSimpleEnoughPointerToCommit(Ptr)) { if (!isSimpleEnoughPointerToCommit(Ptr)) {
@ -2347,7 +2341,7 @@ bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList); Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Ptr = ConstantFoldConstantExpression(CE, DL, TLI); Ptr = ConstantFoldConstantExpression(CE, &DL, TLI);
// If we can't improve the situation by introspecting NewTy, // If we can't improve the situation by introspecting NewTy,
// we have to give up. // we have to give up.
@ -2422,7 +2416,7 @@ bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
Constant *Ptr = getVal(LI->getOperand(0)); Constant *Ptr = getVal(LI->getOperand(0));
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) { if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
Ptr = ConstantFoldConstantExpression(CE, DL, TLI); Ptr = ConstantFoldConstantExpression(CE, &DL, TLI);
DEBUG(dbgs() << "Found a constant pointer expression, constant " DEBUG(dbgs() << "Found a constant pointer expression, constant "
"folding: " << *Ptr << "\n"); "folding: " << *Ptr << "\n");
} }
@ -2498,9 +2492,9 @@ bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
Value *Ptr = PtrArg->stripPointerCasts(); Value *Ptr = PtrArg->stripPointerCasts();
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) { if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
Type *ElemTy = cast<PointerType>(GV->getType())->getElementType(); Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
if (DL && !Size->isAllOnesValue() && if (!Size->isAllOnesValue() &&
Size->getValue().getLimitedValue() >= Size->getValue().getLimitedValue() >=
DL->getTypeStoreSize(ElemTy)) { DL.getTypeStoreSize(ElemTy)) {
Invariants.insert(GV); Invariants.insert(GV);
DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
<< "\n"); << "\n");
@ -2606,7 +2600,7 @@ bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
if (!CurInst->use_empty()) { if (!CurInst->use_empty()) {
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult)) if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
InstResult = ConstantFoldConstantExpression(CE, DL, TLI); InstResult = ConstantFoldConstantExpression(CE, &DL, TLI);
setVal(CurInst, InstResult); setVal(CurInst, InstResult);
} }
@ -2689,7 +2683,7 @@ bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
/// EvaluateStaticConstructor - Evaluate static constructors in the function, if /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
/// we can. Return true if we can, false otherwise. /// we can. Return true if we can, false otherwise.
static bool EvaluateStaticConstructor(Function *F, const DataLayout *DL, static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
const TargetLibraryInfo *TLI) { const TargetLibraryInfo *TLI) {
// Call the function. // Call the function.
Evaluator Eval(DL, TLI); Evaluator Eval(DL, TLI);
@ -3040,8 +3034,7 @@ bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
bool GlobalOpt::runOnModule(Module &M) { bool GlobalOpt::runOnModule(Module &M) {
bool Changed = false; bool Changed = false;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); auto &DL = M.getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
bool LocalChange = true; bool LocalChange = true;

View File

@ -121,8 +121,7 @@ static void AdjustCallerSSPLevel(Function *Caller, Function *Callee) {
/// any new allocas to the set if not possible. /// any new allocas to the set if not possible.
static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI, static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
InlinedArrayAllocasTy &InlinedArrayAllocas, InlinedArrayAllocasTy &InlinedArrayAllocas,
int InlineHistory, bool InsertLifetime, int InlineHistory, bool InsertLifetime) {
const DataLayout *DL) {
Function *Callee = CS.getCalledFunction(); Function *Callee = CS.getCalledFunction();
Function *Caller = CS.getCaller(); Function *Caller = CS.getCaller();
@ -198,11 +197,6 @@ static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
unsigned Align1 = AI->getAlignment(), unsigned Align1 = AI->getAlignment(),
Align2 = AvailableAlloca->getAlignment(); Align2 = AvailableAlloca->getAlignment();
// If we don't have data layout information, and only one alloca is using
// the target default, then we can't safely merge them because we can't
// pick the greater alignment.
if (!DL && (!Align1 || !Align2) && Align1 != Align2)
continue;
// The available alloca has to be in the right function, not in some other // The available alloca has to be in the right function, not in some other
// function in this SCC. // function in this SCC.
@ -223,8 +217,8 @@ static bool InlineCallIfPossible(CallSite CS, InlineFunctionInfo &IFI,
if (Align1 != Align2) { if (Align1 != Align2) {
if (!Align1 || !Align2) { if (!Align1 || !Align2) {
assert(DL && "DataLayout required to compare default alignments"); const DataLayout &DL = Caller->getParent()->getDataLayout();
unsigned TypeAlign = DL->getABITypeAlignment(AI->getAllocatedType()); unsigned TypeAlign = DL.getABITypeAlignment(AI->getAllocatedType());
Align1 = Align1 ? Align1 : TypeAlign; Align1 = Align1 ? Align1 : TypeAlign;
Align2 = Align2 ? Align2 : TypeAlign; Align2 = Align2 ? Align2 : TypeAlign;
@ -432,8 +426,6 @@ static bool InlineHistoryIncludes(Function *F, int InlineHistoryID,
bool Inliner::runOnSCC(CallGraphSCC &SCC) { bool Inliner::runOnSCC(CallGraphSCC &SCC) {
CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
AssumptionCacheTracker *ACT = &getAnalysis<AssumptionCacheTracker>(); AssumptionCacheTracker *ACT = &getAnalysis<AssumptionCacheTracker>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
const TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI() : nullptr; const TargetLibraryInfo *TLI = TLIP ? &TLIP->getTLI() : nullptr;
AliasAnalysis *AA = &getAnalysis<AliasAnalysis>(); AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
@ -495,7 +487,7 @@ bool Inliner::runOnSCC(CallGraphSCC &SCC) {
InlinedArrayAllocasTy InlinedArrayAllocas; InlinedArrayAllocasTy InlinedArrayAllocas;
InlineFunctionInfo InlineInfo(&CG, DL, AA, ACT); InlineFunctionInfo InlineInfo(&CG, AA, ACT);
// Now that we have all of the call sites, loop over them and inline them if // Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so. // it looks profitable to do so.
@ -553,7 +545,7 @@ bool Inliner::runOnSCC(CallGraphSCC &SCC) {
// Attempt to inline the function. // Attempt to inline the function.
if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas, if (!InlineCallIfPossible(CS, InlineInfo, InlinedArrayAllocas,
InlineHistoryID, InsertLifetime, DL)) { InlineHistoryID, InsertLifetime)) {
emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc, emitOptimizationRemarkMissed(CallerCtx, DEBUG_TYPE, *Caller, DLoc,
Twine(Callee->getName() + Twine(Callee->getName() +
" will not be inlined into " + " will not be inlined into " +

View File

@ -234,10 +234,7 @@ ModulePass *llvm::createLowerBitSetsPass() { return new LowerBitSets; }
bool LowerBitSets::doInitialization(Module &Mod) { bool LowerBitSets::doInitialization(Module &Mod) {
M = &Mod; M = &Mod;
DL = &Mod.getDataLayout();
DL = M->getDataLayout();
if (!DL)
report_fatal_error("Data layout required");
Int1Ty = Type::getInt1Ty(M->getContext()); Int1Ty = Type::getInt1Ty(M->getContext());
Int8Ty = Type::getInt8Ty(M->getContext()); Int8Ty = Type::getInt8Ty(M->getContext());

View File

@ -1212,8 +1212,7 @@ bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) {
bool MergeFunctions::runOnModule(Module &M) { bool MergeFunctions::runOnModule(Module &M) {
bool Changed = false; bool Changed = false;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())

View File

@ -2910,17 +2910,18 @@ static bool prepareICWorklistFromFunction(Function &F, const DataLayout *DL,
return MadeIRChange; return MadeIRChange;
} }
static bool combineInstructionsOverFunction( static bool
Function &F, InstCombineWorklist &Worklist, AssumptionCache &AC, combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
TargetLibraryInfo &TLI, DominatorTree &DT, const DataLayout *DL = nullptr, AssumptionCache &AC, TargetLibraryInfo &TLI,
LoopInfo *LI = nullptr) { DominatorTree &DT, LoopInfo *LI = nullptr) {
// Minimizing size? // Minimizing size?
bool MinimizeSize = F.hasFnAttribute(Attribute::MinSize); bool MinimizeSize = F.hasFnAttribute(Attribute::MinSize);
const DataLayout &DL = F.getParent()->getDataLayout();
/// Builder - This is an IRBuilder that automatically inserts new /// Builder - This is an IRBuilder that automatically inserts new
/// instructions into the worklist when they are created. /// instructions into the worklist when they are created.
IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder( IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC)); F.getContext(), TargetFolder(&DL), InstCombineIRInserter(Worklist, &AC));
// Lower dbg.declare intrinsics otherwise their value may be clobbered // Lower dbg.declare intrinsics otherwise their value may be clobbered
// by instcombiner. // by instcombiner.
@ -2934,10 +2935,10 @@ static bool combineInstructionsOverFunction(
<< F.getName() << "\n"); << F.getName() << "\n");
bool Changed = false; bool Changed = false;
if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist)) if (prepareICWorklistFromFunction(F, &DL, &TLI, Worklist))
Changed = true; Changed = true;
InstCombiner IC(Worklist, &Builder, MinimizeSize, &AC, &TLI, &DT, DL, LI); InstCombiner IC(Worklist, &Builder, MinimizeSize, &AC, &TLI, &DT, &DL, LI);
if (IC.run()) if (IC.run())
Changed = true; Changed = true;
@ -2950,15 +2951,13 @@ static bool combineInstructionsOverFunction(
PreservedAnalyses InstCombinePass::run(Function &F, PreservedAnalyses InstCombinePass::run(Function &F,
AnalysisManager<Function> *AM) { AnalysisManager<Function> *AM) {
auto *DL = F.getParent()->getDataLayout();
auto &AC = AM->getResult<AssumptionAnalysis>(F); auto &AC = AM->getResult<AssumptionAnalysis>(F);
auto &DT = AM->getResult<DominatorTreeAnalysis>(F); auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
auto &TLI = AM->getResult<TargetLibraryAnalysis>(F); auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
auto *LI = AM->getCachedResult<LoopAnalysis>(F); auto *LI = AM->getCachedResult<LoopAnalysis>(F);
if (!combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, DL, LI)) if (!combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, LI))
// No changes, all analyses are preserved. // No changes, all analyses are preserved.
return PreservedAnalyses::all(); return PreservedAnalyses::all();
@ -3007,12 +3006,10 @@ bool InstructionCombiningPass::runOnFunction(Function &F) {
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
// Optional analyses. // Optional analyses.
auto *DLP = getAnalysisIfAvailable<DataLayoutPass>();
auto *DL = DLP ? &DLP->getDataLayout() : nullptr;
auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
return combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, DL, LI); return combineInstructionsOverFunction(F, Worklist, AC, TLI, DT, LI);
} }
char InstructionCombiningPass::ID = 0; char InstructionCombiningPass::ID = 0;

View File

@ -392,7 +392,6 @@ struct AddressSanitizer : public FunctionPass {
} }
void getAnalysisUsage(AnalysisUsage &AU) const override { void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<DataLayoutPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>(); AU.addRequired<TargetLibraryInfoWrapperPass>();
} }
uint64_t getAllocaSizeInBytes(AllocaInst *AI) const { uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
@ -1321,9 +1320,7 @@ bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
} }
bool AddressSanitizerModule::runOnModule(Module &M) { bool AddressSanitizerModule::runOnModule(Module &M) {
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
if (!DLP) return false;
DL = &DLP->getDataLayout();
C = &(M.getContext()); C = &(M.getContext());
int LongSize = DL->getPointerSizeInBits(); int LongSize = DL->getPointerSizeInBits();
IntptrTy = Type::getIntNTy(*C, LongSize); IntptrTy = Type::getIntNTy(*C, LongSize);
@ -1399,9 +1396,7 @@ void AddressSanitizer::initializeCallbacks(Module &M) {
// virtual // virtual
bool AddressSanitizer::doInitialization(Module &M) { bool AddressSanitizer::doInitialization(Module &M) {
// Initialize the private fields. No one has accessed them before. // Initialize the private fields. No one has accessed them before.
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
if (!DLP) report_fatal_error("data layout missing");
DL = &DLP->getDataLayout();
GlobalsMD.init(M); GlobalsMD.init(M);

View File

@ -49,7 +49,6 @@ namespace {
bool runOnFunction(Function &F) override; bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override { void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DataLayoutPass>();
AU.addRequired<TargetLibraryInfoWrapperPass>(); AU.addRequired<TargetLibraryInfoWrapperPass>();
} }
@ -165,7 +164,7 @@ bool BoundsChecking::instrument(Value *Ptr, Value *InstVal) {
} }
bool BoundsChecking::runOnFunction(Function &F) { bool BoundsChecking::runOnFunction(Function &F) {
DL = &getAnalysis<DataLayoutPass>().getDataLayout(); DL = &F.getParent()->getDataLayout();
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
TrapBB = nullptr; TrapBB = nullptr;

View File

@ -422,10 +422,7 @@ bool DataFlowSanitizer::doInitialization(Module &M) {
bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 || bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
TargetTriple.getArch() == llvm::Triple::mips64el; TargetTriple.getArch() == llvm::Triple::mips64el;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
if (!DLP)
report_fatal_error("data layout missing");
DL = &DLP->getDataLayout();
Mod = &M; Mod = &M;
Ctx = &M.getContext(); Ctx = &M.getContext();
@ -593,8 +590,6 @@ Constant *DataFlowSanitizer::getOrBuildTrampolineFunction(FunctionType *FT,
} }
bool DataFlowSanitizer::runOnModule(Module &M) { bool DataFlowSanitizer::runOnModule(Module &M) {
if (!DL)
return false;
if (ABIList.isIn(M, "skip")) if (ABIList.isIn(M, "skip"))
return false; return false;

View File

@ -449,10 +449,7 @@ void MemorySanitizer::initializeCallbacks(Module &M) {
/// ///
/// inserts a call to __msan_init to the module's constructor list. /// inserts a call to __msan_init to the module's constructor list.
bool MemorySanitizer::doInitialization(Module &M) { bool MemorySanitizer::doInitialization(Module &M) {
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
if (!DLP)
report_fatal_error("data layout missing");
DL = &DLP->getDataLayout();
Triple TargetTriple(M.getTargetTriple()); Triple TargetTriple(M.getTargetTriple());
switch (TargetTriple.getOS()) { switch (TargetTriple.getOS()) {

View File

@ -104,10 +104,6 @@ class SanitizerCoverageModule : public ModulePass {
return "SanitizerCoverageModule"; return "SanitizerCoverageModule";
} }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DataLayoutPass>();
}
private: private:
void InjectCoverageForIndirectCalls(Function &F, void InjectCoverageForIndirectCalls(Function &F,
ArrayRef<Instruction *> IndirCalls); ArrayRef<Instruction *> IndirCalls);
@ -144,8 +140,8 @@ static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
bool SanitizerCoverageModule::runOnModule(Module &M) { bool SanitizerCoverageModule::runOnModule(Module &M) {
if (!CoverageLevel) return false; if (!CoverageLevel) return false;
C = &(M.getContext()); C = &(M.getContext());
DataLayoutPass *DLP = &getAnalysis<DataLayoutPass>(); auto &DL = M.getDataLayout();
IntptrTy = Type::getIntNTy(*C, DLP->getDataLayout().getPointerSizeInBits()); IntptrTy = Type::getIntNTy(*C, DL.getPointerSizeInBits());
Type *VoidTy = Type::getVoidTy(*C); Type *VoidTy = Type::getVoidTy(*C);
IRBuilder<> IRB(*C); IRBuilder<> IRB(*C);
Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty()); Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());

View File

@ -230,10 +230,7 @@ void ThreadSanitizer::initializeCallbacks(Module &M) {
} }
bool ThreadSanitizer::doInitialization(Module &M) { bool ThreadSanitizer::doInitialization(Module &M) {
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
if (!DLP)
report_fatal_error("data layout missing");
DL = &DLP->getDataLayout();
// Always insert a call to __tsan_init into the module's CTORs. // Always insert a call to __tsan_init into the module's CTORs.
IRBuilder<> IRB(M.getContext()); IRBuilder<> IRB(M.getContext());

View File

@ -46,6 +46,11 @@ ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
return new ObjCARCAliasAnalysis(); return new ObjCARCAliasAnalysis();
} }
bool ObjCARCAliasAnalysis::doInitialization(Module &M) {
InitializeAliasAnalysis(this, &M.getDataLayout());
return true;
}
void void
ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll(); AU.setPreservesAll();

View File

@ -44,9 +44,7 @@ namespace objcarc {
} }
private: private:
void initializePass() override { bool doInitialization(Module &M) override;
InitializeAliasAnalysis(this);
}
/// This method is used when a pass implements an analysis interface through /// This method is used when a pass implements an analysis interface through
/// multiple inheritance. If needed, it should override this to adjust the /// multiple inheritance. If needed, it should override this to adjust the

View File

@ -32,6 +32,7 @@
#include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h" #include "llvm/IR/Intrinsics.h"
#include "llvm/IR/DataLayout.h" #include "llvm/IR/DataLayout.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
using namespace llvm; using namespace llvm;
@ -413,8 +414,7 @@ bool AlignmentFromAssumptions::runOnFunction(Function &F) {
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
NewDestAlignments.clear(); NewDestAlignments.clear();
NewSrcAlignments.clear(); NewSrcAlignments.clear();

View File

@ -263,7 +263,7 @@ bool BDCE::runOnFunction(Function& F) {
return false; return false;
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
DL = F.getParent()->getDataLayout(); DL = &F.getParent()->getDataLayout();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DenseMap<Instruction *, APInt> AliveBits; DenseMap<Instruction *, APInt> AliveBits;

View File

@ -68,8 +68,7 @@ bool ConstantPropagation::runOnFunction(Function &F) {
WorkList.insert(&*i); WorkList.insert(&*i);
} }
bool Changed = false; bool Changed = false;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); const DataLayout &DL = F.getParent()->getDataLayout();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
TargetLibraryInfo *TLI = TargetLibraryInfo *TLI =
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
@ -78,7 +77,7 @@ bool ConstantPropagation::runOnFunction(Function &F) {
WorkList.erase(WorkList.begin()); // Get an element from the worklist... WorkList.erase(WorkList.begin()); // Get an element from the worklist...
if (!I->use_empty()) // Don't muck with dead instructions... if (!I->use_empty()) // Don't muck with dead instructions...
if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) { if (Constant *C = ConstantFoldInstruction(I, &DL, TLI)) {
// Add all of the users of this instruction to the worklist, they might // Add all of the users of this instruction to the worklist, they might
// be constant propagatable now... // be constant propagatable now...
for (User *U : I->users()) for (User *U : I->users())

View File

@ -685,14 +685,14 @@ bool EarlyCSE::run() {
PreservedAnalyses EarlyCSEPass::run(Function &F, PreservedAnalyses EarlyCSEPass::run(Function &F,
AnalysisManager<Function> *AM) { AnalysisManager<Function> *AM) {
const DataLayout *DL = F.getParent()->getDataLayout(); const DataLayout &DL = F.getParent()->getDataLayout();
auto &TLI = AM->getResult<TargetLibraryAnalysis>(F); auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
auto &TTI = AM->getResult<TargetIRAnalysis>(F); auto &TTI = AM->getResult<TargetIRAnalysis>(F);
auto &DT = AM->getResult<DominatorTreeAnalysis>(F); auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
auto &AC = AM->getResult<AssumptionAnalysis>(F); auto &AC = AM->getResult<AssumptionAnalysis>(F);
EarlyCSE CSE(F, DL, TLI, TTI, DT, AC); EarlyCSE CSE(F, &DL, TLI, TTI, DT, AC);
if (!CSE.run()) if (!CSE.run())
return PreservedAnalyses::all(); return PreservedAnalyses::all();
@ -724,14 +724,13 @@ public:
if (skipOptnoneFunction(F)) if (skipOptnoneFunction(F))
return false; return false;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); auto &DL = F.getParent()->getDataLayout();
auto *DL = DLP ? &DLP->getDataLayout() : nullptr;
auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
EarlyCSE CSE(F, DL, TLI, TTI, DT, AC); EarlyCSE CSE(F, &DL, TLI, TTI, DT, AC);
return CSE.run(); return CSE.run();
} }

View File

@ -2357,8 +2357,7 @@ bool GVN::runOnFunction(Function& F) {
if (!NoLoads) if (!NoLoads)
MD = &getAnalysis<MemoryDependenceAnalysis>(); MD = &getAnalysis<MemoryDependenceAnalysis>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>()); VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());

View File

@ -1896,8 +1896,7 @@ bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &L->getHeader()->getModule()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
TLI = TLIP ? &TLIP->getTLI() : nullptr; TLI = TLIP ? &TLIP->getTLI() : nullptr;
auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>(); auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();

View File

@ -159,8 +159,7 @@ bool JumpThreading::runOnFunction(Function &F) {
return false; return false;
DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n"); DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
LVI = &getAnalysis<LazyValueInfo>(); LVI = &getAnalysis<LazyValueInfo>();

View File

@ -48,6 +48,7 @@
#include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h" #include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h" #include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PredIteratorCache.h" #include "llvm/IR/PredIteratorCache.h"
#include "llvm/Support/CommandLine.h" #include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
@ -181,8 +182,7 @@ bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
AA = &getAnalysis<AliasAnalysis>(); AA = &getAnalysis<AliasAnalysis>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &L->getHeader()->getModule()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");

View File

@ -23,6 +23,7 @@
#include "llvm/IR/Function.h" #include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h" #include "llvm/IR/Instructions.h"
#include "llvm/IR/IRBuilder.h" #include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h" #include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
@ -85,12 +86,11 @@ private:
bool LoadCombine::doInitialization(Function &F) { bool LoadCombine::doInitialization(Function &F) {
DEBUG(dbgs() << "LoadCombine function: " << F.getName() << "\n"); DEBUG(dbgs() << "LoadCombine function: " << F.getName() << "\n");
C = &F.getContext(); C = &F.getContext();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
if (!DLP) { if (!DL) {
DEBUG(dbgs() << " Skipping LoadCombine -- no target data!\n"); DEBUG(dbgs() << " Skipping LoadCombine -- no target data!\n");
return false; return false;
} }
DL = &DLP->getDataLayout();
return true; return true;
} }

View File

@ -130,7 +130,6 @@ namespace {
class LoopIdiomRecognize : public LoopPass { class LoopIdiomRecognize : public LoopPass {
Loop *CurLoop; Loop *CurLoop;
const DataLayout *DL;
DominatorTree *DT; DominatorTree *DT;
ScalarEvolution *SE; ScalarEvolution *SE;
TargetLibraryInfo *TLI; TargetLibraryInfo *TLI;
@ -139,7 +138,10 @@ namespace {
static char ID; static char ID;
explicit LoopIdiomRecognize() : LoopPass(ID) { explicit LoopIdiomRecognize() : LoopPass(ID) {
initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry()); initializeLoopIdiomRecognizePass(*PassRegistry::getPassRegistry());
DL = nullptr; DT = nullptr; SE = nullptr; TLI = nullptr; TTI = nullptr; DT = nullptr;
SE = nullptr;
TLI = nullptr;
TTI = nullptr;
} }
bool runOnLoop(Loop *L, LPPassManager &LPM) override; bool runOnLoop(Loop *L, LPPassManager &LPM) override;
@ -179,14 +181,6 @@ namespace {
AU.addRequired<TargetTransformInfoWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>();
} }
const DataLayout *getDataLayout() {
if (DL)
return DL;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
DL = DLP ? &DLP->getDataLayout() : nullptr;
return DL;
}
DominatorTree *getDominatorTree() { DominatorTree *getDominatorTree() {
return DT ? DT return DT ? DT
: (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree()); : (DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree());
@ -625,10 +619,6 @@ bool LoopIdiomRecognize::runOnCountableLoop() {
if (BECst->getValue()->getValue() == 0) if (BECst->getValue()->getValue() == 0)
return false; return false;
// We require target data for now.
if (!getDataLayout())
return false;
// set DT // set DT
(void)getDominatorTree(); (void)getDominatorTree();
@ -742,7 +732,8 @@ bool LoopIdiomRecognize::processLoopStore(StoreInst *SI, const SCEV *BECount) {
Value *StorePtr = SI->getPointerOperand(); Value *StorePtr = SI->getPointerOperand();
// Reject stores that are so large that they overflow an unsigned. // Reject stores that are so large that they overflow an unsigned.
uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->getType()); auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
uint64_t SizeInBits = DL.getTypeSizeInBits(StoredVal->getType());
if ((SizeInBits & 7) || (SizeInBits >> 32) != 0) if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
return false; return false;
@ -917,7 +908,7 @@ processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
// but it can be turned into memset_pattern if the target supports it. // but it can be turned into memset_pattern if the target supports it.
Value *SplatValue = isBytewiseValue(StoredVal); Value *SplatValue = isBytewiseValue(StoredVal);
Constant *PatternValue = nullptr; Constant *PatternValue = nullptr;
auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
unsigned DestAS = DestPtr->getType()->getPointerAddressSpace(); unsigned DestAS = DestPtr->getType()->getPointerAddressSpace();
// If we're allowed to form a memset, and the stored value would be acceptable // If we're allowed to form a memset, and the stored value would be acceptable
@ -928,9 +919,8 @@ processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
CurLoop->isLoopInvariant(SplatValue)) { CurLoop->isLoopInvariant(SplatValue)) {
// Keep and use SplatValue. // Keep and use SplatValue.
PatternValue = nullptr; PatternValue = nullptr;
} else if (DestAS == 0 && } else if (DestAS == 0 && TLI->has(LibFunc::memset_pattern16) &&
TLI->has(LibFunc::memset_pattern16) && (PatternValue = getMemSetPatternValue(StoredVal, DL))) {
(PatternValue = getMemSetPatternValue(StoredVal, *DL))) {
// Don't create memset_pattern16s with address spaces. // Don't create memset_pattern16s with address spaces.
// It looks like we can use PatternValue! // It looks like we can use PatternValue!
SplatValue = nullptr; SplatValue = nullptr;
@ -971,7 +961,7 @@ processLoopStridedStore(Value *DestPtr, unsigned StoreSize,
// The # stored bytes is (BECount+1)*Size. Expand the trip count out to // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
// pointer size if it isn't already. // pointer size if it isn't already.
Type *IntPtr = Builder.getIntPtrTy(DL, DestAS); Type *IntPtr = Builder.getIntPtrTy(&DL, DestAS);
BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr); BECount = SE->getTruncateOrZeroExtend(BECount, IntPtr);
const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1), const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtr, 1),
@ -1085,7 +1075,8 @@ processLoopStoreOfLoopLoad(StoreInst *SI, unsigned StoreSize,
// The # stored bytes is (BECount+1)*Size. Expand the trip count out to // The # stored bytes is (BECount+1)*Size. Expand the trip count out to
// pointer size if it isn't already. // pointer size if it isn't already.
Type *IntPtrTy = Builder.getIntPtrTy(DL, SI->getPointerAddressSpace()); auto &DL = CurLoop->getHeader()->getModule()->getDataLayout();
Type *IntPtrTy = Builder.getIntPtrTy(&DL, SI->getPointerAddressSpace());
BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy); BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1), const SCEV *NumBytesS = SE->getAddExpr(BECount, SE->getConstant(IntPtrTy, 1),

View File

@ -77,8 +77,7 @@ bool LoopInstSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
getAnalysisIfAvailable<DominatorTreeWrapperPass>(); getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); const DataLayout *DL = &L->getHeader()->getModule()->getDataLayout();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
const TargetLibraryInfo *TLI = const TargetLibraryInfo *TLI =
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache( auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(

View File

@ -1477,8 +1477,7 @@ bool LoopReroll::runOnLoop(Loop *L, LPPassManager &LPM) {
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &L->getHeader()->getModule()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
BasicBlock *Header = L->getHeader(); BasicBlock *Header = L->getHeader();

View File

@ -1077,8 +1077,7 @@ bool MemCpyOpt::runOnFunction(Function &F) {
bool MadeChange = false; bool MadeChange = false;
MD = &getAnalysis<MemoryDependenceAnalysis>(); MD = &getAnalysis<MemoryDependenceAnalysis>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
// If we don't have at least memset and memcpy, there is little point of doing // If we don't have at least memset and memcpy, there is little point of doing

View File

@ -154,7 +154,7 @@ namespace {
/// Constant Propagation. /// Constant Propagation.
/// ///
class SCCPSolver : public InstVisitor<SCCPSolver> { class SCCPSolver : public InstVisitor<SCCPSolver> {
const DataLayout *DL; const DataLayout &DL;
const TargetLibraryInfo *TLI; const TargetLibraryInfo *TLI;
SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable. SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
DenseMap<Value*, LatticeVal> ValueState; // The state each value is in. DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
@ -206,8 +206,8 @@ class SCCPSolver : public InstVisitor<SCCPSolver> {
typedef std::pair<BasicBlock*, BasicBlock*> Edge; typedef std::pair<BasicBlock*, BasicBlock*> Edge;
DenseSet<Edge> KnownFeasibleEdges; DenseSet<Edge> KnownFeasibleEdges;
public: public:
SCCPSolver(const DataLayout *DL, const TargetLibraryInfo *tli) SCCPSolver(const DataLayout &DL, const TargetLibraryInfo *tli)
: DL(DL), TLI(tli) {} : DL(DL), TLI(tli) {}
/// MarkBlockExecutable - This method can be used by clients to mark all of /// MarkBlockExecutable - This method can be used by clients to mark all of
/// the blocks that are known to be intrinsically live in the processed unit. /// the blocks that are known to be intrinsically live in the processed unit.
@ -1070,7 +1070,7 @@ void SCCPSolver::visitLoadInst(LoadInst &I) {
} }
// Transform load from a constant into a constant if possible. // Transform load from a constant into a constant if possible.
if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, DL)) if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, &DL))
return markConstant(IV, &I, C); return markConstant(IV, &I, C);
// Otherwise we cannot say for certain what value this load will produce. // Otherwise we cannot say for certain what value this load will produce.
@ -1561,8 +1561,7 @@ bool SCCP::runOnFunction(Function &F) {
return false; return false;
DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n"); DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
const DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); const DataLayout &DL = F.getParent()->getDataLayout();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
const TargetLibraryInfo *TLI = const TargetLibraryInfo *TLI =
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
SCCPSolver Solver(DL, TLI); SCCPSolver Solver(DL, TLI);
@ -1691,8 +1690,7 @@ static bool AddressIsTaken(const GlobalValue *GV) {
} }
bool IPSCCP::runOnModule(Module &M) { bool IPSCCP::runOnModule(Module &M) {
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); const DataLayout &DL = M.getDataLayout();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
const TargetLibraryInfo *TLI = const TargetLibraryInfo *TLI =
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
SCCPSolver Solver(DL, TLI); SCCPSolver Solver(DL, TLI);

View File

@ -4423,12 +4423,7 @@ bool SROA::runOnFunction(Function &F) {
DEBUG(dbgs() << "SROA function: " << F.getName() << "\n"); DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
C = &F.getContext(); C = &F.getContext();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
if (!DLP) {
DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
return false;
}
DL = &DLP->getDataLayout();
DominatorTreeWrapperPass *DTWP = DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>(); getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DT = DTWP ? &DTWP->getDomTree() : nullptr; DT = DTWP ? &DTWP->getDomTree() : nullptr;

View File

@ -1032,8 +1032,7 @@ bool SROA::runOnFunction(Function &F) {
if (skipOptnoneFunction(F)) if (skipOptnoneFunction(F))
return false; return false;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
bool Changed = performPromotion(F); bool Changed = performPromotion(F);

View File

@ -248,8 +248,7 @@ bool Scalarizer::doInitialization(Module &M) {
} }
bool Scalarizer::runOnFunction(Function &F) { bool Scalarizer::runOnFunction(Function &F) {
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) { for (Function::iterator BBI = F.begin(), BBE = F.end(); BBI != BBE; ++BBI) {
BasicBlock *BB = BBI; BasicBlock *BB = BBI;
for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) { for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {

View File

@ -312,16 +312,12 @@ class SeparateConstOffsetFromGEP : public FunctionPass {
} }
void getAnalysisUsage(AnalysisUsage &AU) const override { void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<DataLayoutPass>();
AU.addRequired<TargetTransformInfoWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>();
AU.setPreservesCFG(); AU.setPreservesCFG();
} }
bool doInitialization(Module &M) override { bool doInitialization(Module &M) override {
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &M.getDataLayout();
if (DLP == nullptr)
report_fatal_error("data layout missing");
DL = &DLP->getDataLayout();
return false; return false;
} }
@ -386,7 +382,6 @@ INITIALIZE_PASS_BEGIN(
"Split GEPs to a variadic base and a constant offset for better CSE", false, "Split GEPs to a variadic base and a constant offset for better CSE", false,
false) false)
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DataLayoutPass)
INITIALIZE_PASS_END( INITIALIZE_PASS_END(
SeparateConstOffsetFromGEP, "separate-const-offset-from-gep", SeparateConstOffsetFromGEP, "separate-const-offset-from-gep",
"Split GEPs to a variadic base and a constant offset for better CSE", false, "Split GEPs to a variadic base and a constant offset for better CSE", false,

View File

@ -181,11 +181,11 @@ SimplifyCFGPass::SimplifyCFGPass(int BonusInstThreshold)
PreservedAnalyses SimplifyCFGPass::run(Function &F, PreservedAnalyses SimplifyCFGPass::run(Function &F,
AnalysisManager<Function> *AM) { AnalysisManager<Function> *AM) {
auto *DL = F.getParent()->getDataLayout(); auto &DL = F.getParent()->getDataLayout();
auto &TTI = AM->getResult<TargetIRAnalysis>(F); auto &TTI = AM->getResult<TargetIRAnalysis>(F);
auto &AC = AM->getResult<AssumptionAnalysis>(F); auto &AC = AM->getResult<AssumptionAnalysis>(F);
if (!simplifyFunctionCFG(F, TTI, DL, &AC, BonusInstThreshold)) if (!simplifyFunctionCFG(F, TTI, &DL, &AC, BonusInstThreshold))
return PreservedAnalyses::none(); return PreservedAnalyses::none();
return PreservedAnalyses::all(); return PreservedAnalyses::all();
@ -207,9 +207,8 @@ struct CFGSimplifyPass : public FunctionPass {
&getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
const TargetTransformInfo &TTI = const TargetTransformInfo &TTI =
getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); const DataLayout &DL = F.getParent()->getDataLayout();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr; return simplifyFunctionCFG(F, TTI, &DL, AC, BonusInstThreshold);
return simplifyFunctionCFG(F, TTI, DL, AC, BonusInstThreshold);
} }
void getAnalysisUsage(AnalysisUsage &AU) const override { void getAnalysisUsage(AnalysisUsage &AU) const override {

View File

@ -21,6 +21,7 @@
#include "llvm/IR/DataLayout.h" #include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h" #include "llvm/IR/Dominators.h"
#include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h" #include "llvm/Support/raw_ostream.h"
using namespace llvm; using namespace llvm;
@ -100,8 +101,7 @@ bool Sinking::runOnFunction(Function &F) {
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
AA = &getAnalysis<AliasAnalysis>(); AA = &getAnalysis<AliasAnalysis>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
bool MadeChange, EverMadeChange = false; bool MadeChange, EverMadeChange = false;

View File

@ -159,7 +159,7 @@ bool TailCallElim::runOnFunction(Function &F) {
if (skipOptnoneFunction(F)) if (skipOptnoneFunction(F))
return false; return false;
DL = F.getParent()->getDataLayout(); DL = &F.getParent()->getDataLayout();
bool AllCallsAreTailCalls = false; bool AllCallsAreTailCalls = false;
bool Modified = markTails(F, AllCallsAreTailCalls); bool Modified = markTails(F, AllCallsAreTailCalls);

View File

@ -622,8 +622,9 @@ static void AddAliasScopeMetadata(CallSite CS, ValueToValueMapTy &VMap,
/// If the inlined function has non-byval align arguments, then /// If the inlined function has non-byval align arguments, then
/// add @llvm.assume-based alignment assumptions to preserve this information. /// add @llvm.assume-based alignment assumptions to preserve this information.
static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) { static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
if (!PreserveAlignmentAssumptions || !IFI.DL) if (!PreserveAlignmentAssumptions)
return; return;
auto &DL = CS.getCaller()->getParent()->getDataLayout();
// To avoid inserting redundant assumptions, we should check for assumptions // To avoid inserting redundant assumptions, we should check for assumptions
// already in the caller. To do this, we might need a DT of the caller. // already in the caller. To do this, we might need a DT of the caller.
@ -645,13 +646,12 @@ static void AddAlignmentAssumptions(CallSite CS, InlineFunctionInfo &IFI) {
// If we can already prove the asserted alignment in the context of the // If we can already prove the asserted alignment in the context of the
// caller, then don't bother inserting the assumption. // caller, then don't bother inserting the assumption.
Value *Arg = CS.getArgument(I->getArgNo()); Value *Arg = CS.getArgument(I->getArgNo());
if (getKnownAlignment(Arg, IFI.DL, if (getKnownAlignment(Arg, &DL, &IFI.ACT->getAssumptionCache(*CalledFunc),
&IFI.ACT->getAssumptionCache(*CalledFunc),
CS.getInstruction(), &DT) >= Align) CS.getInstruction(), &DT) >= Align)
continue; continue;
IRBuilder<>(CS.getInstruction()).CreateAlignmentAssumption(*IFI.DL, Arg, IRBuilder<>(CS.getInstruction())
Align); .CreateAlignmentAssumption(DL, Arg, Align);
} }
} }
} }
@ -726,11 +726,7 @@ static void HandleByValArgumentInit(Value *Dst, Value *Src, Module *M,
Type *AggTy = cast<PointerType>(Src->getType())->getElementType(); Type *AggTy = cast<PointerType>(Src->getType())->getElementType();
IRBuilder<> Builder(InsertBlock->begin()); IRBuilder<> Builder(InsertBlock->begin());
Value *Size; Value *Size = Builder.getInt64(M->getDataLayout().getTypeStoreSize(AggTy));
if (IFI.DL == nullptr)
Size = ConstantExpr::getSizeOf(AggTy);
else
Size = Builder.getInt64(IFI.DL->getTypeStoreSize(AggTy));
// Always generate a memcpy of alignment 1 here because we don't know // Always generate a memcpy of alignment 1 here because we don't know
// the alignment of the src pointer. Other optimizations can infer // the alignment of the src pointer. Other optimizations can infer
@ -761,7 +757,8 @@ static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
// If the pointer is already known to be sufficiently aligned, or if we can // If the pointer is already known to be sufficiently aligned, or if we can
// round it up to a larger alignment, then we don't need a temporary. // round it up to a larger alignment, then we don't need a temporary.
if (getOrEnforceKnownAlignment(Arg, ByValAlignment, IFI.DL, auto &DL = Caller->getParent()->getDataLayout();
if (getOrEnforceKnownAlignment(Arg, ByValAlignment, &DL,
&IFI.ACT->getAssumptionCache(*Caller), &IFI.ACT->getAssumptionCache(*Caller),
TheCall) >= ByValAlignment) TheCall) >= ByValAlignment)
return Arg; return Arg;
@ -771,10 +768,9 @@ static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
} }
// Create the alloca. If we have DataLayout, use nice alignment. // Create the alloca. If we have DataLayout, use nice alignment.
unsigned Align = 1; unsigned Align =
if (IFI.DL) Caller->getParent()->getDataLayout().getPrefTypeAlignment(AggTy);
Align = IFI.DL->getPrefTypeAlignment(AggTy);
// If the byval had an alignment specified, we *must* use at least that // If the byval had an alignment specified, we *must* use at least that
// alignment, as it is required by the byval argument (and uses of the // alignment, as it is required by the byval argument (and uses of the
// pointer inside the callee). // pointer inside the callee).
@ -1008,6 +1004,8 @@ bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
// Keep a list of pair (dst, src) to emit byval initializations. // Keep a list of pair (dst, src) to emit byval initializations.
SmallVector<std::pair<Value*, Value*>, 4> ByValInit; SmallVector<std::pair<Value*, Value*>, 4> ByValInit;
auto &DL = Caller->getParent()->getDataLayout();
assert(CalledFunc->arg_size() == CS.arg_size() && assert(CalledFunc->arg_size() == CS.arg_size() &&
"No varargs calls can be inlined!"); "No varargs calls can be inlined!");
@ -1042,9 +1040,9 @@ bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
// have no dead or constant instructions leftover after inlining occurs // have no dead or constant instructions leftover after inlining occurs
// (which can happen, e.g., because an argument was constant), but we'll be // (which can happen, e.g., because an argument was constant), but we'll be
// happy with whatever the cloner can do. // happy with whatever the cloner can do.
CloneAndPruneFunctionInto(Caller, CalledFunc, VMap, CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
/*ModuleLevelChanges=*/false, Returns, ".i", /*ModuleLevelChanges=*/false, Returns, ".i",
&InlinedFunctionInfo, IFI.DL, TheCall); &InlinedFunctionInfo, &DL, TheCall);
// Remember the first block that is newly cloned over. // Remember the first block that is newly cloned over.
FirstNewBlock = LastBlock; ++FirstNewBlock; FirstNewBlock = LastBlock; ++FirstNewBlock;
@ -1065,7 +1063,7 @@ bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
CloneAliasScopeMetadata(CS, VMap); CloneAliasScopeMetadata(CS, VMap);
// Add noalias metadata if necessary. // Add noalias metadata if necessary.
AddAliasScopeMetadata(CS, VMap, IFI.DL, IFI.AA); AddAliasScopeMetadata(CS, VMap, &DL, IFI.AA);
// FIXME: We could register any cloned assumptions instead of clearing the // FIXME: We could register any cloned assumptions instead of clearing the
// whole function's cache. // whole function's cache.
@ -1173,18 +1171,17 @@ bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
ConstantInt *AllocaSize = nullptr; ConstantInt *AllocaSize = nullptr;
if (ConstantInt *AIArraySize = if (ConstantInt *AIArraySize =
dyn_cast<ConstantInt>(AI->getArraySize())) { dyn_cast<ConstantInt>(AI->getArraySize())) {
if (IFI.DL) { auto &DL = Caller->getParent()->getDataLayout();
Type *AllocaType = AI->getAllocatedType(); Type *AllocaType = AI->getAllocatedType();
uint64_t AllocaTypeSize = IFI.DL->getTypeAllocSize(AllocaType); uint64_t AllocaTypeSize = DL.getTypeAllocSize(AllocaType);
uint64_t AllocaArraySize = AIArraySize->getLimitedValue(); uint64_t AllocaArraySize = AIArraySize->getLimitedValue();
assert(AllocaArraySize > 0 && "array size of AllocaInst is zero"); assert(AllocaArraySize > 0 && "array size of AllocaInst is zero");
// Check that array size doesn't saturate uint64_t and doesn't // Check that array size doesn't saturate uint64_t and doesn't
// overflow when it's multiplied by type size. // overflow when it's multiplied by type size.
if (AllocaArraySize != ~0ULL && if (AllocaArraySize != ~0ULL &&
UINT64_MAX / AllocaArraySize >= AllocaTypeSize) { UINT64_MAX / AllocaArraySize >= AllocaTypeSize) {
AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()), AllocaSize = ConstantInt::get(Type::getInt64Ty(AI->getContext()),
AllocaArraySize * AllocaTypeSize); AllocaArraySize * AllocaTypeSize);
}
} }
} }
@ -1445,7 +1442,8 @@ bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI,
// the entries are the same or undef). If so, remove the PHI so it doesn't // the entries are the same or undef). If so, remove the PHI so it doesn't
// block other optimizations. // block other optimizations.
if (PHI) { if (PHI) {
if (Value *V = SimplifyInstruction(PHI, IFI.DL, nullptr, nullptr, auto &DL = Caller->getParent()->getDataLayout();
if (Value *V = SimplifyInstruction(PHI, &DL, nullptr, nullptr,
&IFI.ACT->getAssumptionCache(*Caller))) { &IFI.ACT->getAssumptionCache(*Caller))) {
PHI->replaceAllUsesWith(V); PHI->replaceAllUsesWith(V);
PHI->eraseFromParent(); PHI->eraseFromParent();

View File

@ -57,6 +57,7 @@
#include "llvm/IR/Instructions.h" #include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h" #include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h" #include "llvm/IR/Type.h"
#include "llvm/Support/Debug.h" #include "llvm/Support/Debug.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h"
@ -797,8 +798,7 @@ bool LoopSimplify::runOnFunction(Function &F) {
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
SE = getAnalysisIfAvailable<ScalarEvolution>(); SE = getAnalysisIfAvailable<ScalarEvolution>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
// Simplify each loop nest in the function. // Simplify each loop nest in the function.

View File

@ -531,9 +531,8 @@ bool llvm::UnrollLoop(Loop *L, unsigned Count, unsigned TripCount,
if (!OuterL && !CompletelyUnroll) if (!OuterL && !CompletelyUnroll)
OuterL = L; OuterL = L;
if (OuterL) { if (OuterL) {
DataLayoutPass *DLP = PP->getAnalysisIfAvailable<DataLayoutPass>(); const DataLayout &DL = F->getParent()->getDataLayout();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr; simplifyLoop(OuterL, DT, LI, PP, /*AliasAnalysis*/ nullptr, SE, &DL, AC);
simplifyLoop(OuterL, DT, LI, PP, /*AliasAnalysis*/ nullptr, SE, DL, AC);
// LCSSA must be performed on the outermost affected loop. The unrolled // LCSSA must be performed on the outermost affected loop. The unrolled
// loop's last loop latch is guaranteed to be in the outermost loop after // loop's last loop latch is guaranteed to be in the outermost loop after

View File

@ -51,8 +51,7 @@ namespace {
const DominatorTreeWrapperPass *DTWP = const DominatorTreeWrapperPass *DTWP =
getAnalysisIfAvailable<DominatorTreeWrapperPass>(); getAnalysisIfAvailable<DominatorTreeWrapperPass>();
const DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; const DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); const DataLayout &DL = F.getParent()->getDataLayout();
const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
const TargetLibraryInfo *TLI = const TargetLibraryInfo *TLI =
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
AssumptionCache *AC = AssumptionCache *AC =
@ -73,7 +72,7 @@ namespace {
continue; continue;
// Don't waste time simplifying unused instructions. // Don't waste time simplifying unused instructions.
if (!I->use_empty()) if (!I->use_empty())
if (Value *V = SimplifyInstruction(I, DL, TLI, DT, AC)) { if (Value *V = SimplifyInstruction(I, &DL, TLI, DT, AC)) {
// Mark all uses for resimplification next time round the loop. // Mark all uses for resimplification next time round the loop.
for (User *U : I->users()) for (User *U : I->users())
Next->insert(cast<Instruction>(U)); Next->insert(cast<Instruction>(U));

View File

@ -39,6 +39,7 @@
#include "llvm/IR/Intrinsics.h" #include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h" #include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h" #include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h" #include "llvm/IR/Type.h"
#include "llvm/IR/ValueHandle.h" #include "llvm/IR/ValueHandle.h"
#include "llvm/Pass.h" #include "llvm/Pass.h"
@ -206,8 +207,7 @@ namespace {
AA = &P->getAnalysis<AliasAnalysis>(); AA = &P->getAnalysis<AliasAnalysis>();
DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &P->getAnalysis<DominatorTreeWrapperPass>().getDomTree();
SE = &P->getAnalysis<ScalarEvolution>(); SE = &P->getAnalysis<ScalarEvolution>();
DataLayoutPass *DLP = P->getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TTI = IgnoreTargetInfo TTI = IgnoreTargetInfo
? nullptr ? nullptr
: &P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); : &P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
@ -442,8 +442,7 @@ namespace {
AA = &getAnalysis<AliasAnalysis>(); AA = &getAnalysis<AliasAnalysis>();
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &BB.getModule()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TTI = IgnoreTargetInfo TTI = IgnoreTargetInfo
? nullptr ? nullptr
: &getAnalysis<TargetTransformInfoWrapperPass>().getTTI( : &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(

View File

@ -1274,8 +1274,7 @@ struct LoopVectorize : public FunctionPass {
bool runOnFunction(Function &F) override { bool runOnFunction(Function &F) override {
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();

View File

@ -3064,8 +3064,7 @@ struct SLPVectorizer : public FunctionPass {
return false; return false;
SE = &getAnalysis<ScalarEvolution>(); SE = &getAnalysis<ScalarEvolution>();
DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); DL = &F.getParent()->getDataLayout();
DL = DLP ? &DLP->getDataLayout() : nullptr;
TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
TLI = TLIP ? &TLIP->getTLI() : nullptr; TLI = TLIP ? &TLIP->getTLI() : nullptr;

View File

@ -9,7 +9,7 @@
; AddRec: {{{(28 + (4 * (-4 + (3 * %m)) * %o) + %A),+,(8 * %m * %o)}<%for.i>,+,(12 * %o)}<%for.j>,+,20}<%for.k> ; AddRec: {{{(28 + (4 * (-4 + (3 * %m)) * %o) + %A),+,(8 * %m * %o)}<%for.i>,+,(12 * %o)}<%for.j>,+,20}<%for.k>
; CHECK: Base offset: %A ; CHECK: Base offset: %A
; CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(i32) bytes. ; CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of 4 bytes.
; CHECK: ArrayRef[{3,+,2}<%for.i>][{-4,+,3}<%for.j>][{7,+,5}<%for.k>] ; CHECK: ArrayRef[{3,+,2}<%for.i>][{-4,+,3}<%for.j>][{7,+,5}<%for.k>]
define void @foo(i64 %n, i64 %m, i64 %o, i32* nocapture %A) #0 { define void @foo(i64 %n, i64 %m, i64 %o, i32* nocapture %A) #0 {

Some files were not shown because too many files have changed in this diff Show More