Replace r102368 with code that's less fragile. This creates DBG_VALUE instructions...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / FunctionLoweringInfo.cpp
1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating functions from LLVM IR into
11 // Machine IR.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "function-lowering-info"
16 #include "FunctionLoweringInfo.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetFrameInfo.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetIntrinsicInfo.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
43 /// PHI nodes or outside of the basic block that defines it, or used by a
44 /// switch or atomic instruction, which may expand to multiple basic blocks.
45 static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
46   if (I->use_empty()) return false;
47   if (isa<PHINode>(I)) return true;
48   const BasicBlock *BB = I->getParent();
49   for (Value::const_use_iterator UI = I->use_begin(), E = I->use_end();
50         UI != E; ++UI)
51     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
52       return true;
53   return false;
54 }
55
56 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
57 /// entry block, return true.  This includes arguments used by switches, since
58 /// the switch may expand into multiple basic blocks.
59 static bool isOnlyUsedInEntryBlock(const Argument *A, bool EnableFastISel) {
60   // With FastISel active, we may be splitting blocks, so force creation
61   // of virtual registers for all non-dead arguments.
62   // Don't force virtual registers for byval arguments though, because
63   // fast-isel can't handle those in all cases.
64   if (EnableFastISel && !A->hasByValAttr())
65     return A->use_empty();
66
67   const BasicBlock *Entry = A->getParent()->begin();
68   for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
69        UI != E; ++UI)
70     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
71       return false;  // Use not in entry block.
72   return true;
73 }
74
75 FunctionLoweringInfo::FunctionLoweringInfo(const TargetLowering &tli)
76   : TLI(tli) {
77 }
78
79 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
80                                bool EnableFastISel) {
81   Fn = &fn;
82   MF = &mf;
83   RegInfo = &MF->getRegInfo();
84
85   // Create a vreg for each argument register that is not dead and is used
86   // outside of the entry block for the function.
87   for (Function::const_arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
88        AI != E; ++AI)
89     if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
90       InitializeRegForValue(AI);
91
92   // Initialize the mapping of values to registers.  This is only set up for
93   // instruction values that are used outside of the block that defines
94   // them.
95   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
96   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
97     if (const AllocaInst *AI = dyn_cast<AllocaInst>(I))
98       if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
99         const Type *Ty = AI->getAllocatedType();
100         uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
101         unsigned Align =
102           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
103                    AI->getAlignment());
104
105         TySize *= CUI->getZExtValue();   // Get total allocated size.
106         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
107         StaticAllocaMap[AI] =
108           MF->getFrameInfo()->CreateStackObject(TySize, Align, false);
109       }
110
111   for (; BB != EB; ++BB)
112     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
113       if (isUsedOutsideOfDefiningBlock(I))
114         if (!isa<AllocaInst>(I) ||
115             !StaticAllocaMap.count(cast<AllocaInst>(I)))
116           InitializeRegForValue(I);
117
118   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
119   // also creates the initial PHI MachineInstrs, though none of the input
120   // operands are populated.
121   for (BB = Fn->begin(); BB != EB; ++BB) {
122     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
123     MBBMap[BB] = MBB;
124     MF->push_back(MBB);
125
126     // Transfer the address-taken flag. This is necessary because there could
127     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
128     // the first one should be marked.
129     if (BB->hasAddressTaken())
130       MBB->setHasAddressTaken();
131
132     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
133     // appropriate.
134     for (BasicBlock::const_iterator I = BB->begin();
135          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
136       if (PN->use_empty()) continue;
137
138       DebugLoc DL = PN->getDebugLoc();
139       unsigned PHIReg = ValueMap[PN];
140       assert(PHIReg && "PHI node does not have an assigned virtual register!");
141
142       SmallVector<EVT, 4> ValueVTs;
143       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
144       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
145         EVT VT = ValueVTs[vti];
146         unsigned NumRegisters = TLI.getNumRegisters(Fn->getContext(), VT);
147         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
148         for (unsigned i = 0; i != NumRegisters; ++i)
149           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
150         PHIReg += NumRegisters;
151       }
152     }
153   }
154
155   // Mark landing pad blocks.
156   for (BB = Fn->begin(); BB != EB; ++BB)
157     if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
158       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
159 }
160
161 /// clear - Clear out all the function-specific state. This returns this
162 /// FunctionLoweringInfo to an empty state, ready to be used for a
163 /// different function.
164 void FunctionLoweringInfo::clear() {
165   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
166          "Not all catch info was assigned to a landing pad!");
167
168   MBBMap.clear();
169   ValueMap.clear();
170   StaticAllocaMap.clear();
171 #ifndef NDEBUG
172   CatchInfoLost.clear();
173   CatchInfoFound.clear();
174 #endif
175   LiveOutRegInfo.clear();
176   ArgDbgValues.clear();
177 }
178
179 unsigned FunctionLoweringInfo::MakeReg(EVT VT) {
180   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
181 }
182
183 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
184 /// the correctly promoted or expanded types.  Assign these registers
185 /// consecutive vreg numbers and return the first assigned number.
186 ///
187 /// In the case that the given value has struct or array type, this function
188 /// will assign registers for each member or element.
189 ///
190 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
191   SmallVector<EVT, 4> ValueVTs;
192   ComputeValueVTs(TLI, V->getType(), ValueVTs);
193
194   unsigned FirstReg = 0;
195   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
196     EVT ValueVT = ValueVTs[Value];
197     EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT);
198
199     unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT);
200     for (unsigned i = 0; i != NumRegs; ++i) {
201       unsigned R = MakeReg(RegisterVT);
202       if (!FirstReg) FirstReg = R;
203     }
204   }
205   return FirstReg;
206 }
207
208 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
209 /// call, and add them to the specified machine basic block.
210 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
211                         MachineBasicBlock *MBB) {
212   // Inform the MachineModuleInfo of the personality for this landing pad.
213   const ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
214   assert(CE->getOpcode() == Instruction::BitCast &&
215          isa<Function>(CE->getOperand(0)) &&
216          "Personality should be a function");
217   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
218
219   // Gather all the type infos for this landing pad and pass them along to
220   // MachineModuleInfo.
221   std::vector<const GlobalVariable *> TyInfo;
222   unsigned N = I.getNumOperands();
223
224   for (unsigned i = N - 1; i > 2; --i) {
225     if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
226       unsigned FilterLength = CI->getZExtValue();
227       unsigned FirstCatch = i + FilterLength + !FilterLength;
228       assert (FirstCatch <= N && "Invalid filter length");
229
230       if (FirstCatch < N) {
231         TyInfo.reserve(N - FirstCatch);
232         for (unsigned j = FirstCatch; j < N; ++j)
233           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
234         MMI->addCatchTypeInfo(MBB, TyInfo);
235         TyInfo.clear();
236       }
237
238       if (!FilterLength) {
239         // Cleanup.
240         MMI->addCleanup(MBB);
241       } else {
242         // Filter.
243         TyInfo.reserve(FilterLength - 1);
244         for (unsigned j = i + 1; j < FirstCatch; ++j)
245           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
246         MMI->addFilterTypeInfo(MBB, TyInfo);
247         TyInfo.clear();
248       }
249
250       N = i;
251     }
252   }
253
254   if (N > 3) {
255     TyInfo.reserve(N - 3);
256     for (unsigned j = 3; j < N; ++j)
257       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
258     MMI->addCatchTypeInfo(MBB, TyInfo);
259   }
260 }
261
262 void llvm::CopyCatchInfo(const BasicBlock *SrcBB, const BasicBlock *DestBB,
263                          MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
264   for (BasicBlock::const_iterator I = SrcBB->begin(), E = --SrcBB->end();
265        I != E; ++I)
266     if (const EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
267       // Apply the catch info to DestBB.
268       AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
269 #ifndef NDEBUG
270       if (!FLI.MBBMap[SrcBB]->isLandingPad())
271         FLI.CatchInfoFound.insert(EHSel);
272 #endif
273     }
274 }