Don't put non-static allocas in the static alloca map
[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 "llvm/CodeGen/FunctionLoweringInfo.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/DebugInfo.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetLowering.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.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     const User *U = *UI;
52     if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
53       return true;
54   }
55   return false;
56 }
57
58 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
59   const TargetLowering *TLI = TM.getTargetLowering();
60
61   Fn = &fn;
62   MF = &mf;
63   RegInfo = &MF->getRegInfo();
64
65   // Check whether the function can return without sret-demotion.
66   SmallVector<ISD::OutputArg, 4> Outs;
67   GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
68   CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
69                                        Fn->isVarArg(),
70                                        Outs, Fn->getContext());
71
72   // Initialize the mapping of values to registers.  This is only set up for
73   // instruction values that are used outside of the block that defines
74   // them.
75   Function::const_iterator BB = Fn->begin(), EB = Fn->end();
76   for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
77     if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
78       // Don't fold inalloca allocas or other dynamic allocas into the initial
79       // stack frame allocation, even if they are in the entry block.
80       if (!AI->isStaticAlloca())
81         continue;
82
83       if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
84         Type *Ty = AI->getAllocatedType();
85         uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
86         unsigned Align =
87           std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
88                    AI->getAlignment());
89
90         TySize *= CUI->getZExtValue();   // Get total allocated size.
91         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
92
93         StaticAllocaMap[AI] =
94           MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
95       }
96     }
97
98   for (; BB != EB; ++BB)
99     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
100          I != E; ++I) {
101       // Mark values used outside their block as exported, by allocating
102       // a virtual register for them.
103       if (isUsedOutsideOfDefiningBlock(I))
104         if (!isa<AllocaInst>(I) ||
105             !StaticAllocaMap.count(cast<AllocaInst>(I)))
106           InitializeRegForValue(I);
107
108       // Collect llvm.dbg.declare information. This is done now instead of
109       // during the initial isel pass through the IR so that it is done
110       // in a predictable order.
111       if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
112         MachineModuleInfo &MMI = MF->getMMI();
113         DIVariable DIVar(DI->getVariable());
114         assert((!DIVar || DIVar.isVariable()) &&
115           "Variable in DbgDeclareInst should be either null or a DIVariable.");
116         if (MMI.hasDebugInfo() &&
117             DIVar &&
118             !DI->getDebugLoc().isUnknown()) {
119           // Don't handle byval struct arguments or VLAs, for example.
120           // Non-byval arguments are handled here (they refer to the stack
121           // temporary alloca at this point).
122           const Value *Address = DI->getAddress();
123           if (Address) {
124             if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
125               Address = BCI->getOperand(0);
126             if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
127               DenseMap<const AllocaInst *, int>::iterator SI =
128                 StaticAllocaMap.find(AI);
129               if (SI != StaticAllocaMap.end()) { // Check for VLAs.
130                 int FI = SI->second;
131                 MMI.setVariableDbgInfo(DI->getVariable(),
132                                        FI, DI->getDebugLoc());
133               }
134             }
135           }
136         }
137       }
138     }
139
140   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
141   // also creates the initial PHI MachineInstrs, though none of the input
142   // operands are populated.
143   for (BB = Fn->begin(); BB != EB; ++BB) {
144     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
145     MBBMap[BB] = MBB;
146     MF->push_back(MBB);
147
148     // Transfer the address-taken flag. This is necessary because there could
149     // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
150     // the first one should be marked.
151     if (BB->hasAddressTaken())
152       MBB->setHasAddressTaken();
153
154     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
155     // appropriate.
156     for (BasicBlock::const_iterator I = BB->begin();
157          const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
158       if (PN->use_empty()) continue;
159
160       // Skip empty types
161       if (PN->getType()->isEmptyTy())
162         continue;
163
164       DebugLoc DL = PN->getDebugLoc();
165       unsigned PHIReg = ValueMap[PN];
166       assert(PHIReg && "PHI node does not have an assigned virtual register!");
167
168       SmallVector<EVT, 4> ValueVTs;
169       ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
170       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
171         EVT VT = ValueVTs[vti];
172         unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
173         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
174         for (unsigned i = 0; i != NumRegisters; ++i)
175           BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
176         PHIReg += NumRegisters;
177       }
178     }
179   }
180
181   // Mark landing pad blocks.
182   for (BB = Fn->begin(); BB != EB; ++BB)
183     if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
184       MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
185 }
186
187 /// clear - Clear out all the function-specific state. This returns this
188 /// FunctionLoweringInfo to an empty state, ready to be used for a
189 /// different function.
190 void FunctionLoweringInfo::clear() {
191   assert(CatchInfoFound.size() == CatchInfoLost.size() &&
192          "Not all catch info was assigned to a landing pad!");
193
194   MBBMap.clear();
195   ValueMap.clear();
196   StaticAllocaMap.clear();
197 #ifndef NDEBUG
198   CatchInfoLost.clear();
199   CatchInfoFound.clear();
200 #endif
201   LiveOutRegInfo.clear();
202   VisitedBBs.clear();
203   ArgDbgValues.clear();
204   ByValArgFrameIndexMap.clear();
205   RegFixups.clear();
206 }
207
208 /// CreateReg - Allocate a single virtual register for the given type.
209 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
210   return RegInfo->
211     createVirtualRegister(TM.getTargetLowering()->getRegClassFor(VT));
212 }
213
214 /// CreateRegs - Allocate the appropriate number of virtual registers of
215 /// the correctly promoted or expanded types.  Assign these registers
216 /// consecutive vreg numbers and return the first assigned number.
217 ///
218 /// In the case that the given value has struct or array type, this function
219 /// will assign registers for each member or element.
220 ///
221 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
222   const TargetLowering *TLI = TM.getTargetLowering();
223
224   SmallVector<EVT, 4> ValueVTs;
225   ComputeValueVTs(*TLI, Ty, ValueVTs);
226
227   unsigned FirstReg = 0;
228   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
229     EVT ValueVT = ValueVTs[Value];
230     MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
231
232     unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
233     for (unsigned i = 0; i != NumRegs; ++i) {
234       unsigned R = CreateReg(RegisterVT);
235       if (!FirstReg) FirstReg = R;
236     }
237   }
238   return FirstReg;
239 }
240
241 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
242 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
243 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
244 /// the larger bit width by zero extension. The bit width must be no smaller
245 /// than the LiveOutInfo's existing bit width.
246 const FunctionLoweringInfo::LiveOutInfo *
247 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
248   if (!LiveOutRegInfo.inBounds(Reg))
249     return NULL;
250
251   LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
252   if (!LOI->IsValid)
253     return NULL;
254
255   if (BitWidth > LOI->KnownZero.getBitWidth()) {
256     LOI->NumSignBits = 1;
257     LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
258     LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
259   }
260
261   return LOI;
262 }
263
264 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
265 /// register based on the LiveOutInfo of its operands.
266 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
267   Type *Ty = PN->getType();
268   if (!Ty->isIntegerTy() || Ty->isVectorTy())
269     return;
270
271   const TargetLowering *TLI = TM.getTargetLowering();
272
273   SmallVector<EVT, 1> ValueVTs;
274   ComputeValueVTs(*TLI, Ty, ValueVTs);
275   assert(ValueVTs.size() == 1 &&
276          "PHIs with non-vector integer types should have a single VT.");
277   EVT IntVT = ValueVTs[0];
278
279   if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
280     return;
281   IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
282   unsigned BitWidth = IntVT.getSizeInBits();
283
284   unsigned DestReg = ValueMap[PN];
285   if (!TargetRegisterInfo::isVirtualRegister(DestReg))
286     return;
287   LiveOutRegInfo.grow(DestReg);
288   LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
289
290   Value *V = PN->getIncomingValue(0);
291   if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
292     DestLOI.NumSignBits = 1;
293     APInt Zero(BitWidth, 0);
294     DestLOI.KnownZero = Zero;
295     DestLOI.KnownOne = Zero;
296     return;
297   }
298
299   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
300     APInt Val = CI->getValue().zextOrTrunc(BitWidth);
301     DestLOI.NumSignBits = Val.getNumSignBits();
302     DestLOI.KnownZero = ~Val;
303     DestLOI.KnownOne = Val;
304   } else {
305     assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
306                                 "CopyToReg node was created.");
307     unsigned SrcReg = ValueMap[V];
308     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
309       DestLOI.IsValid = false;
310       return;
311     }
312     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
313     if (!SrcLOI) {
314       DestLOI.IsValid = false;
315       return;
316     }
317     DestLOI = *SrcLOI;
318   }
319
320   assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
321          DestLOI.KnownOne.getBitWidth() == BitWidth &&
322          "Masks should have the same bit width as the type.");
323
324   for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
325     Value *V = PN->getIncomingValue(i);
326     if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
327       DestLOI.NumSignBits = 1;
328       APInt Zero(BitWidth, 0);
329       DestLOI.KnownZero = Zero;
330       DestLOI.KnownOne = Zero;
331       return;
332     }
333
334     if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
335       APInt Val = CI->getValue().zextOrTrunc(BitWidth);
336       DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
337       DestLOI.KnownZero &= ~Val;
338       DestLOI.KnownOne &= Val;
339       continue;
340     }
341
342     assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
343                                 "its CopyToReg node was created.");
344     unsigned SrcReg = ValueMap[V];
345     if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
346       DestLOI.IsValid = false;
347       return;
348     }
349     const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
350     if (!SrcLOI) {
351       DestLOI.IsValid = false;
352       return;
353     }
354     DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
355     DestLOI.KnownZero &= SrcLOI->KnownZero;
356     DestLOI.KnownOne &= SrcLOI->KnownOne;
357   }
358 }
359
360 /// setArgumentFrameIndex - Record frame index for the byval
361 /// argument. This overrides previous frame index entry for this argument,
362 /// if any.
363 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
364                                                  int FI) {
365   ByValArgFrameIndexMap[A] = FI;
366 }
367
368 /// getArgumentFrameIndex - Get frame index for the byval argument.
369 /// If the argument does not have any assigned frame index then 0 is
370 /// returned.
371 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
372   DenseMap<const Argument *, int>::iterator I =
373     ByValArgFrameIndexMap.find(A);
374   if (I != ByValArgFrameIndexMap.end())
375     return I->second;
376   DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
377   return 0;
378 }
379
380 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
381 /// being passed to this variadic function, and set the MachineModuleInfo's
382 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
383 /// reference to _fltused on Windows, which will link in MSVCRT's
384 /// floating-point support.
385 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
386                                       MachineModuleInfo *MMI)
387 {
388   FunctionType *FT = cast<FunctionType>(
389     I.getCalledValue()->getType()->getContainedType(0));
390   if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
391     for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
392       Type* T = I.getArgOperand(i)->getType();
393       for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
394            i != e; ++i) {
395         if (i->isFloatingPointTy()) {
396           MMI->setUsesVAFloatArgument(true);
397           return;
398         }
399       }
400     }
401   }
402 }
403
404 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
405 /// call, and add them to the specified machine basic block.
406 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
407                         MachineBasicBlock *MBB) {
408   // Inform the MachineModuleInfo of the personality for this landing pad.
409   const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
410   assert(CE->getOpcode() == Instruction::BitCast &&
411          isa<Function>(CE->getOperand(0)) &&
412          "Personality should be a function");
413   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
414
415   // Gather all the type infos for this landing pad and pass them along to
416   // MachineModuleInfo.
417   std::vector<const GlobalVariable *> TyInfo;
418   unsigned N = I.getNumArgOperands();
419
420   for (unsigned i = N - 1; i > 1; --i) {
421     if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
422       unsigned FilterLength = CI->getZExtValue();
423       unsigned FirstCatch = i + FilterLength + !FilterLength;
424       assert(FirstCatch <= N && "Invalid filter length");
425
426       if (FirstCatch < N) {
427         TyInfo.reserve(N - FirstCatch);
428         for (unsigned j = FirstCatch; j < N; ++j)
429           TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
430         MMI->addCatchTypeInfo(MBB, TyInfo);
431         TyInfo.clear();
432       }
433
434       if (!FilterLength) {
435         // Cleanup.
436         MMI->addCleanup(MBB);
437       } else {
438         // Filter.
439         TyInfo.reserve(FilterLength - 1);
440         for (unsigned j = i + 1; j < FirstCatch; ++j)
441           TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
442         MMI->addFilterTypeInfo(MBB, TyInfo);
443         TyInfo.clear();
444       }
445
446       N = i;
447     }
448   }
449
450   if (N > 2) {
451     TyInfo.reserve(N - 2);
452     for (unsigned j = 2; j < N; ++j)
453       TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
454     MMI->addCatchTypeInfo(MBB, TyInfo);
455   }
456 }
457
458 /// AddLandingPadInfo - Extract the exception handling information from the
459 /// landingpad instruction and add them to the specified machine module info.
460 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
461                              MachineBasicBlock *MBB) {
462   MMI.addPersonality(MBB,
463                      cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
464
465   if (I.isCleanup())
466     MMI.addCleanup(MBB);
467
468   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
469   //        but we need to do it this way because of how the DWARF EH emitter
470   //        processes the clauses.
471   for (unsigned i = I.getNumClauses(); i != 0; --i) {
472     Value *Val = I.getClause(i - 1);
473     if (I.isCatch(i - 1)) {
474       MMI.addCatchTypeInfo(MBB,
475                            dyn_cast<GlobalVariable>(Val->stripPointerCasts()));
476     } else {
477       // Add filters in a list.
478       Constant *CVal = cast<Constant>(Val);
479       SmallVector<const GlobalVariable*, 4> FilterList;
480       for (User::op_iterator
481              II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
482         FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts()));
483
484       MMI.addFilterTypeInfo(MBB, FilterList);
485     }
486   }
487 }