1 //===-- FunctionLoweringInfo.cpp ------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating functions from LLVM IR into
13 //===----------------------------------------------------------------------===//
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"
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();
52 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
58 void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf) {
59 const TargetLowering *TLI = TM.getTargetLowering();
63 RegInfo = &MF->getRegInfo();
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,
70 Outs, Fn->getContext());
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
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 if (const ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
79 Type *Ty = AI->getAllocatedType();
80 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
82 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
85 TySize *= CUI->getZExtValue(); // Get total allocated size.
86 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
88 // The object may need to be placed onto the stack near the stack
89 // protector if one exists. Determine here if this object is a suitable
90 // candidate. I.e., it would trigger the creation of a stack protector.
92 (AI->isArrayAllocation() ||
93 (TySize >= 8 && isa<ArrayType>(Ty) &&
94 cast<ArrayType>(Ty)->getElementType()->isIntegerTy(8)));
96 MF->getFrameInfo()->CreateStackObject(TySize, Align, false,
100 for (; BB != EB; ++BB)
101 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
103 // Mark values used outside their block as exported, by allocating
104 // a virtual register for them.
105 if (isUsedOutsideOfDefiningBlock(I))
106 if (!isa<AllocaInst>(I) ||
107 !StaticAllocaMap.count(cast<AllocaInst>(I)))
108 InitializeRegForValue(I);
110 // Collect llvm.dbg.declare information. This is done now instead of
111 // during the initial isel pass through the IR so that it is done
112 // in a predictable order.
113 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
114 MachineModuleInfo &MMI = MF->getMMI();
115 if (MMI.hasDebugInfo() &&
116 DIVariable(DI->getVariable()).Verify() &&
117 !DI->getDebugLoc().isUnknown()) {
118 // Don't handle byval struct arguments or VLAs, for example.
119 // Non-byval arguments are handled here (they refer to the stack
120 // temporary alloca at this point).
121 const Value *Address = DI->getAddress();
123 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
124 Address = BCI->getOperand(0);
125 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
126 DenseMap<const AllocaInst *, int>::iterator SI =
127 StaticAllocaMap.find(AI);
128 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
130 MMI.setVariableDbgInfo(DI->getVariable(),
131 FI, DI->getDebugLoc());
139 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
140 // also creates the initial PHI MachineInstrs, though none of the input
141 // operands are populated.
142 for (BB = Fn->begin(); BB != EB; ++BB) {
143 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
147 // Transfer the address-taken flag. This is necessary because there could
148 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
149 // the first one should be marked.
150 if (BB->hasAddressTaken())
151 MBB->setHasAddressTaken();
153 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
155 for (BasicBlock::const_iterator I = BB->begin();
156 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
157 if (PN->use_empty()) continue;
160 if (PN->getType()->isEmptyTy())
163 DebugLoc DL = PN->getDebugLoc();
164 unsigned PHIReg = ValueMap[PN];
165 assert(PHIReg && "PHI node does not have an assigned virtual register!");
167 SmallVector<EVT, 4> ValueVTs;
168 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
169 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
170 EVT VT = ValueVTs[vti];
171 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
172 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
173 for (unsigned i = 0; i != NumRegisters; ++i)
174 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
175 PHIReg += NumRegisters;
180 // Mark landing pad blocks.
181 for (BB = Fn->begin(); BB != EB; ++BB)
182 if (const InvokeInst *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
183 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
186 /// clear - Clear out all the function-specific state. This returns this
187 /// FunctionLoweringInfo to an empty state, ready to be used for a
188 /// different function.
189 void FunctionLoweringInfo::clear() {
190 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
191 "Not all catch info was assigned to a landing pad!");
195 StaticAllocaMap.clear();
197 CatchInfoLost.clear();
198 CatchInfoFound.clear();
200 LiveOutRegInfo.clear();
202 ArgDbgValues.clear();
203 ByValArgFrameIndexMap.clear();
207 /// CreateReg - Allocate a single virtual register for the given type.
208 unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
210 createVirtualRegister(TM.getTargetLowering()->getRegClassFor(VT));
213 /// CreateRegs - Allocate the appropriate number of virtual registers of
214 /// the correctly promoted or expanded types. Assign these registers
215 /// consecutive vreg numbers and return the first assigned number.
217 /// In the case that the given value has struct or array type, this function
218 /// will assign registers for each member or element.
220 unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
221 const TargetLowering *TLI = TM.getTargetLowering();
223 SmallVector<EVT, 4> ValueVTs;
224 ComputeValueVTs(*TLI, Ty, ValueVTs);
226 unsigned FirstReg = 0;
227 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
228 EVT ValueVT = ValueVTs[Value];
229 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
231 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
232 for (unsigned i = 0; i != NumRegs; ++i) {
233 unsigned R = CreateReg(RegisterVT);
234 if (!FirstReg) FirstReg = R;
240 /// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
241 /// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
242 /// the register's LiveOutInfo is for a smaller bit width, it is extended to
243 /// the larger bit width by zero extension. The bit width must be no smaller
244 /// than the LiveOutInfo's existing bit width.
245 const FunctionLoweringInfo::LiveOutInfo *
246 FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
247 if (!LiveOutRegInfo.inBounds(Reg))
250 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
254 if (BitWidth > LOI->KnownZero.getBitWidth()) {
255 LOI->NumSignBits = 1;
256 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
257 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
263 /// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
264 /// register based on the LiveOutInfo of its operands.
265 void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
266 Type *Ty = PN->getType();
267 if (!Ty->isIntegerTy() || Ty->isVectorTy())
270 const TargetLowering *TLI = TM.getTargetLowering();
272 SmallVector<EVT, 1> ValueVTs;
273 ComputeValueVTs(*TLI, Ty, ValueVTs);
274 assert(ValueVTs.size() == 1 &&
275 "PHIs with non-vector integer types should have a single VT.");
276 EVT IntVT = ValueVTs[0];
278 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
280 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
281 unsigned BitWidth = IntVT.getSizeInBits();
283 unsigned DestReg = ValueMap[PN];
284 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
286 LiveOutRegInfo.grow(DestReg);
287 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
289 Value *V = PN->getIncomingValue(0);
290 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
291 DestLOI.NumSignBits = 1;
292 APInt Zero(BitWidth, 0);
293 DestLOI.KnownZero = Zero;
294 DestLOI.KnownOne = Zero;
298 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
299 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
300 DestLOI.NumSignBits = Val.getNumSignBits();
301 DestLOI.KnownZero = ~Val;
302 DestLOI.KnownOne = Val;
304 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
305 "CopyToReg node was created.");
306 unsigned SrcReg = ValueMap[V];
307 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
308 DestLOI.IsValid = false;
311 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
313 DestLOI.IsValid = false;
319 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
320 DestLOI.KnownOne.getBitWidth() == BitWidth &&
321 "Masks should have the same bit width as the type.");
323 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
324 Value *V = PN->getIncomingValue(i);
325 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
326 DestLOI.NumSignBits = 1;
327 APInt Zero(BitWidth, 0);
328 DestLOI.KnownZero = Zero;
329 DestLOI.KnownOne = Zero;
333 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
334 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
335 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
336 DestLOI.KnownZero &= ~Val;
337 DestLOI.KnownOne &= Val;
341 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
342 "its CopyToReg node was created.");
343 unsigned SrcReg = ValueMap[V];
344 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
345 DestLOI.IsValid = false;
348 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
350 DestLOI.IsValid = false;
353 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
354 DestLOI.KnownZero &= SrcLOI->KnownZero;
355 DestLOI.KnownOne &= SrcLOI->KnownOne;
359 /// setArgumentFrameIndex - Record frame index for the byval
360 /// argument. This overrides previous frame index entry for this argument,
362 void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
364 ByValArgFrameIndexMap[A] = FI;
367 /// getArgumentFrameIndex - Get frame index for the byval argument.
368 /// If the argument does not have any assigned frame index then 0 is
370 int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
371 DenseMap<const Argument *, int>::iterator I =
372 ByValArgFrameIndexMap.find(A);
373 if (I != ByValArgFrameIndexMap.end())
375 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
379 /// ComputeUsesVAFloatArgument - Determine if any floating-point values are
380 /// being passed to this variadic function, and set the MachineModuleInfo's
381 /// usesVAFloatArgument flag if so. This flag is used to emit an undefined
382 /// reference to _fltused on Windows, which will link in MSVCRT's
383 /// floating-point support.
384 void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
385 MachineModuleInfo *MMI)
387 FunctionType *FT = cast<FunctionType>(
388 I.getCalledValue()->getType()->getContainedType(0));
389 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
390 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
391 Type* T = I.getArgOperand(i)->getType();
392 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
394 if (i->isFloatingPointTy()) {
395 MMI->setUsesVAFloatArgument(true);
403 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
404 /// call, and add them to the specified machine basic block.
405 void llvm::AddCatchInfo(const CallInst &I, MachineModuleInfo *MMI,
406 MachineBasicBlock *MBB) {
407 // Inform the MachineModuleInfo of the personality for this landing pad.
408 const ConstantExpr *CE = cast<ConstantExpr>(I.getArgOperand(1));
409 assert(CE->getOpcode() == Instruction::BitCast &&
410 isa<Function>(CE->getOperand(0)) &&
411 "Personality should be a function");
412 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
414 // Gather all the type infos for this landing pad and pass them along to
415 // MachineModuleInfo.
416 std::vector<const GlobalVariable *> TyInfo;
417 unsigned N = I.getNumArgOperands();
419 for (unsigned i = N - 1; i > 1; --i) {
420 if (const ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(i))) {
421 unsigned FilterLength = CI->getZExtValue();
422 unsigned FirstCatch = i + FilterLength + !FilterLength;
423 assert(FirstCatch <= N && "Invalid filter length");
425 if (FirstCatch < N) {
426 TyInfo.reserve(N - FirstCatch);
427 for (unsigned j = FirstCatch; j < N; ++j)
428 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
429 MMI->addCatchTypeInfo(MBB, TyInfo);
435 MMI->addCleanup(MBB);
438 TyInfo.reserve(FilterLength - 1);
439 for (unsigned j = i + 1; j < FirstCatch; ++j)
440 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
441 MMI->addFilterTypeInfo(MBB, TyInfo);
450 TyInfo.reserve(N - 2);
451 for (unsigned j = 2; j < N; ++j)
452 TyInfo.push_back(ExtractTypeInfo(I.getArgOperand(j)));
453 MMI->addCatchTypeInfo(MBB, TyInfo);
457 /// AddLandingPadInfo - Extract the exception handling information from the
458 /// landingpad instruction and add them to the specified machine module info.
459 void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
460 MachineBasicBlock *MBB) {
461 MMI.addPersonality(MBB,
462 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
467 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
468 // but we need to do it this way because of how the DWARF EH emitter
469 // processes the clauses.
470 for (unsigned i = I.getNumClauses(); i != 0; --i) {
471 Value *Val = I.getClause(i - 1);
472 if (I.isCatch(i - 1)) {
473 MMI.addCatchTypeInfo(MBB,
474 dyn_cast<GlobalVariable>(Val->stripPointerCasts()));
476 // Add filters in a list.
477 Constant *CVal = cast<Constant>(Val);
478 SmallVector<const GlobalVariable*, 4> FilterList;
479 for (User::op_iterator
480 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
481 FilterList.push_back(cast<GlobalVariable>((*II)->stripPointerCasts()));
483 MMI.addFilterTypeInfo(MBB, FilterList);