1 //===- PreSelection.cpp - Specialize LLVM code for target machine ---------===//
3 // This file defines the PreSelection pass which specializes LLVM code for a
4 // target machine, while remaining in legal portable LLVM form and
5 // preserving type information and type safety. This is meant to enable
6 // dataflow optimizations on target-specific operations such as accesses to
7 // constants, globals, and array indexing.
9 //===----------------------------------------------------------------------===//
11 #include "llvm/CodeGen/PreSelection.h"
12 #include "llvm/Target/TargetMachine.h"
13 #include "llvm/Target/MachineInstrInfo.h"
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/Support/InstVisitor.h"
16 #include "llvm/Module.h"
17 #include "llvm/Constants.h"
18 #include "llvm/iMemory.h"
19 #include "llvm/iPHINode.h"
20 #include "llvm/iOther.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Annotation.h"
24 #include "Support/CommandLine.h"
25 #include "Support/NonCopyable.h"
30 //===--------------------------------------------------------------------===//
31 // SelectDebugLevel - Allow command line control over debugging.
33 enum PreSelectDebugLevel_t {
34 PreSelect_NoDebugInfo,
35 PreSelect_PrintOutput,
38 // Enable Debug Options to be specified on the command line
39 cl::opt<PreSelectDebugLevel_t>
40 PreSelectDebugLevel("dpreselect", cl::Hidden,
41 cl::desc("debug information for target-dependent pre-selection"),
43 clEnumValN(PreSelect_NoDebugInfo, "n", "disable debug output (default)"),
44 clEnumValN(PreSelect_PrintOutput, "y", "print generated machine code"),
45 /* default level = */ PreSelect_NoDebugInfo));
48 //===--------------------------------------------------------------------===//
49 // class ConstantPoolForModule:
51 // The pool of constants that must be emitted for a module.
52 // This is a single pool for the entire module and is shared by
53 // all invocations of the PreSelection pass for this module by putting
54 // this as as annotation on the Module object.
55 // A single GlobalVariable is created for each constant in the pool
56 // representing the memory for that constant.
58 static AnnotationID CPFM_AID(
59 AnnotationManager::getID("CodeGen::ConstantPoolForModule"));
61 class ConstantPoolForModule: private Annotation, public NonCopyable {
63 std::map<const Constant*, GlobalVariable*> gvars;
64 std::map<const Constant*, GlobalVariable*> origGVars;
65 ConstantPoolForModule(Module* M); // called only by annotation builder
66 ConstantPoolForModule(); // do not implement
68 static ConstantPoolForModule& get(Module* M) {
69 ConstantPoolForModule* cpool =
70 (ConstantPoolForModule*) M->getAnnotation(CPFM_AID);
71 if (cpool == NULL) // create a new annotation and add it to the Module
72 M->addAnnotation(cpool = new ConstantPoolForModule(M));
76 GlobalVariable* getGlobalForConstant(Constant* CV) {
77 std::map<const Constant*, GlobalVariable*>::iterator I = gvars.find(CV);
79 return I->second; // global exists so return it
80 return addToConstantPool(CV); // create a new global and return it
83 GlobalVariable* addToConstantPool(Constant* CV) {
84 GlobalVariable*& GV = gvars[CV]; // handle to global var entry in map
86 { // check if a global constant already existed; otherwise create one
87 std::map<const Constant*, GlobalVariable*>::iterator PI =
89 if (PI != origGVars.end())
90 GV = PI->second; // put in map
93 GV = new GlobalVariable(CV->getType(), true,true,CV); //put in map
94 myModule->getGlobalList().push_back(GV); // GV owned by module now
102 ConstantPoolForModule::ConstantPoolForModule(Module* M)
103 : Annotation(CPFM_AID), myModule(M)
105 // Build reverse map for pre-existing global constants so we can find them
106 for (Module::giterator GI = M->gbegin(), GE = M->gend(); GI != GE; ++GI)
107 if (GI->hasInitializer() && GI->isConstant())
108 origGVars[GI->getInitializer()] = GI;
111 //===--------------------------------------------------------------------===//
112 // PreSelection Pass - Specialize LLVM code for the current target machine.
113 // This was and will be a basicblock pass, but make it a FunctionPass until
114 // BasicBlockPass ::doFinalization(Function&) is available.
116 class PreSelection : public BasicBlockPass, public InstVisitor<PreSelection>
118 const TargetMachine ⌖
121 GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction* insertBefore = 0);
123 GlobalVariable* getGlobalForConstant(Constant* CV) {
124 Module* M = function->getParent();
125 return ConstantPoolForModule::get(M).getGlobalForConstant(CV);
129 PreSelection (const TargetMachine &T): target(T), function(NULL) {}
131 // runOnBasicBlock - apply this pass to each BB
132 bool runOnBasicBlock(BasicBlock &BB) {
133 function = BB.getParent();
138 bool doFinalization(Function &F) {
139 if (PreSelectDebugLevel >= PreSelect_PrintOutput)
140 cerr << "\n\n*** LLVM code after pre-selection for function "
141 << F.getName() << ":\n\n" << F;
145 // These methods do the actual work of specializing code
146 void visitInstruction(Instruction &I); // common work for every instr.
147 void visitGetElementPtrInst(GetElementPtrInst &I);
148 void visitLoadInst(LoadInst &I);
149 void visitStoreInst(StoreInst &I);
151 // Helper functions for visiting operands of every instruction
152 void visitOperands(Instruction &I); // work on all operands of instr.
153 void visitOneOperand(Instruction &I, Constant* CV, unsigned opNum,
154 Instruction& insertBefore); // iworks on one operand
156 } // end anonymous namespace
159 // Register the pass...
160 static RegisterOpt<PreSelection> X("preselect",
161 "Specialize LLVM code for a target machine",
162 createPreSelectionPass);
164 // PreSelection::getGlobalAddr: Put address of a global into a v. register.
166 PreSelection::getGlobalAddr(Value* ptr, Instruction* insertBefore)
168 return (isa<GlobalValue>(ptr))
169 ? new GetElementPtrInst(ptr,
170 std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)),
171 "addrOfGlobal", insertBefore)
176 //------------------------------------------------------------------------------
177 // Instruction visitor methods to perform instruction-specific operations
178 //------------------------------------------------------------------------------
180 // Common work for *all* instructions. This needs to be called explicitly
181 // by other visit<InstructionType> functions.
183 PreSelection::visitInstruction(Instruction &I)
185 visitOperands(I); // Perform operand transformations
189 // GetElementPtr instructions: check if pointer is a global
191 PreSelection::visitGetElementPtrInst(GetElementPtrInst &I)
193 // Check for a global and put its address into a register before this instr
194 if (GetElementPtrInst* gep = getGlobalAddr(I.getPointerOperand(), &I))
195 I.setOperand(I.getPointerOperandIndex(), gep); // replace pointer operand
197 // Decompose multidimensional array references
198 DecomposeArrayRef(&I);
200 // Perform other transformations common to all instructions
205 // Load instructions: check if pointer is a global
207 PreSelection::visitLoadInst(LoadInst &I)
209 // Check for a global and put its address into a register before this instr
210 if (GetElementPtrInst* gep = getGlobalAddr(I.getPointerOperand(), &I))
211 I.setOperand(I.getPointerOperandIndex(), gep); // replace pointer operand
213 // Perform other transformations common to all instructions
218 // Store instructions: check if pointer is a global
220 PreSelection::visitStoreInst(StoreInst &I)
222 // Check for a global and put its address into a register before this instr
223 if (GetElementPtrInst* gep = getGlobalAddr(I.getPointerOperand(), &I))
224 I.setOperand(I.getPointerOperandIndex(), gep); // replace pointer operand
226 // Perform other transformations common to all instructions
231 // visitOperands() transforms individual operands of all instructions:
232 // -- Load "large" int constants into a virtual register. What is large
233 // depends on the type of instruction and on the target architecture.
234 // -- For any constants that cannot be put in an immediate field,
235 // load address into virtual register first, and then load the constant.
238 PreSelection::visitOperands(Instruction &I)
240 // For any instruction other than PHI, copies go just before the instr.
241 // For a PHI, operand copies must be before the terminator of the
242 // appropriate predecessor basic block. Remaining logic is simple
243 // so just handle PHIs and other instructions separately.
245 if (PHINode* phi = dyn_cast<PHINode>(&I))
247 for (unsigned i=0, N=phi->getNumIncomingValues(); i < N; ++i)
248 if (Constant* CV = dyn_cast<Constant>(phi->getIncomingValue(i)))
249 this->visitOneOperand(I, CV, phi->getOperandNumForIncomingValue(i),
250 * phi->getIncomingBlock(i)->getTerminator());
253 for (unsigned i=0, N=I.getNumOperands(); i < N; ++i)
254 if (Constant* CV = dyn_cast<Constant>(I.getOperand(i)))
255 this->visitOneOperand(I, CV, i, I);
259 PreSelection::visitOneOperand(Instruction &I, Constant* CV, unsigned opNum,
260 Instruction& insertBefore)
262 if (target.getInstrInfo().ConstantTypeMustBeLoaded(CV))
263 { // load address of constant into a register, then load the constant
264 GetElementPtrInst* gep = getGlobalAddr(getGlobalForConstant(CV),
266 LoadInst* ldI = new LoadInst(gep, "loadConst", &insertBefore);
267 I.setOperand(opNum, ldI); // replace operand with copy in v.reg.
269 else if (target.getInstrInfo().ConstantMayNotFitInImmedField(CV, &I))
270 { // put the constant into a virtual register using a cast
271 CastInst* castI = new CastInst(CV, CV->getType(), "copyConst",
273 I.setOperand(opNum, castI); // replace operand with copy in v.reg.
277 //===----------------------------------------------------------------------===//
278 // createPreSelectionPass - Public entrypoint for pre-selection pass
279 // and this file as a whole...
282 createPreSelectionPass(TargetMachine &T)
284 return new PreSelection(T);