blob: 65a67265d7942a597b9e8466194349d3268ae0b6 [file] [log] [blame]
Dan Gohmana3624b62009-11-23 17:16:22 +00001//===-- 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
Dan Gohmane7846162010-07-07 16:01:37 +000015#include "llvm/CodeGen/FunctionLoweringInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/PostOrderIterator.h"
17#include "llvm/CodeGen/Analysis.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineInstrBuilder.h"
21#include "llvm/CodeGen/MachineModuleInfo.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
David Majnemercde33032015-03-30 22:58:10 +000023#include "llvm/CodeGen/WinEHFuncInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000025#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#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"
Dan Gohmana3624b62009-11-23 17:16:22 +000032#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/MathExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/Support/raw_ostream.h"
Hans Wennborgacb842d2014-03-05 02:43:26 +000036#include "llvm/Target/TargetFrameLowering.h"
Chandler Carruth92051402014-03-05 10:30:38 +000037#include "llvm/Target/TargetInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Target/TargetLowering.h"
39#include "llvm/Target/TargetOptions.h"
40#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Dan Gohmana3624b62009-11-23 17:16:22 +000042#include <algorithm>
43using namespace llvm;
44
Chandler Carruth1b9dde02014-04-22 02:02:50 +000045#define DEBUG_TYPE "function-lowering-info"
46
Dan Gohmana3624b62009-11-23 17:16:22 +000047/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
48/// PHI nodes or outside of the basic block that defines it, or used by a
49/// switch or atomic instruction, which may expand to multiple basic blocks.
Dan Gohman913c9982010-04-15 04:33:49 +000050static bool isUsedOutsideOfDefiningBlock(const Instruction *I) {
Dan Gohman7c845e42010-04-20 14:50:13 +000051 if (I->use_empty()) return false;
Dan Gohmana3624b62009-11-23 17:16:22 +000052 if (isa<PHINode>(I)) return true;
Dan Gohman913c9982010-04-15 04:33:49 +000053 const BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +000054 for (const User *U : I->users())
Gabor Greif52617fc2010-07-09 16:08:33 +000055 if (cast<Instruction>(U)->getParent() != BB || isa<PHINode>(U))
Dan Gohmana3624b62009-11-23 17:16:22 +000056 return true;
Chandler Carruthcdf47882014-03-09 03:16:01 +000057
Dan Gohmana3624b62009-11-23 17:16:22 +000058 return false;
59}
60
Jiangning Liuffbc6902014-09-19 05:30:35 +000061static ISD::NodeType getPreferredExtendForValue(const Value *V) {
62 // For the users of the source value being used for compare instruction, if
63 // the number of signed predicate is greater than unsigned predicate, we
64 // prefer to use SIGN_EXTEND.
65 //
66 // With this optimization, we would be able to reduce some redundant sign or
67 // zero extension instruction, and eventually more machine CSE opportunities
68 // can be exposed.
69 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
70 unsigned NumOfSigned = 0, NumOfUnsigned = 0;
71 for (const User *U : V->users()) {
72 if (const auto *CI = dyn_cast<CmpInst>(U)) {
73 NumOfSigned += CI->isSigned();
74 NumOfUnsigned += CI->isUnsigned();
75 }
76 }
77 if (NumOfSigned > NumOfUnsigned)
78 ExtendKind = ISD::SIGN_EXTEND;
79
80 return ExtendKind;
81}
82
David Majnemercde33032015-03-30 22:58:10 +000083namespace {
84struct WinEHNumbering {
85 WinEHNumbering(WinEHFuncInfo &FuncInfo) : FuncInfo(FuncInfo), NextState(0) {}
86
87 WinEHFuncInfo &FuncInfo;
88 int NextState;
89
90 SmallVector<ActionHandler *, 4> HandlerStack;
David Majnemera225a192015-03-31 22:35:44 +000091 SmallPtrSet<const Function *, 4> VisitedHandlers;
David Majnemercde33032015-03-30 22:58:10 +000092
93 int currentEHNumber() const {
94 return HandlerStack.empty() ? -1 : HandlerStack.back()->getEHState();
95 }
96
David Majnemercde33032015-03-30 22:58:10 +000097 void createUnwindMapEntry(int ToState, ActionHandler *AH);
David Majnemera225a192015-03-31 22:35:44 +000098 void createTryBlockMapEntry(int TryLow, int TryHigh,
99 ArrayRef<CatchHandler *> Handlers);
100 void processCallSite(ArrayRef<ActionHandler *> Actions, ImmutableCallSite CS);
David Majnemercde33032015-03-30 22:58:10 +0000101 void calculateStateNumbers(const Function &F);
102};
103}
104
Hans Wennborgacb842d2014-03-05 02:43:26 +0000105void FunctionLoweringInfo::set(const Function &fn, MachineFunction &mf,
106 SelectionDAG *DAG) {
Dan Gohmana3624b62009-11-23 17:16:22 +0000107 Fn = &fn;
108 MF = &mf;
Eric Christopher2ae2de72014-10-09 00:57:31 +0000109 TLI = MF->getSubtarget().getTargetLowering();
Dan Gohmana3624b62009-11-23 17:16:22 +0000110 RegInfo = &MF->getRegInfo();
David Majnemercde33032015-03-30 22:58:10 +0000111 MachineModuleInfo &MMI = MF->getMMI();
Dan Gohmana3624b62009-11-23 17:16:22 +0000112
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000113 // Check whether the function can return without sret-demotion.
114 SmallVector<ISD::OutputArg, 4> Outs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000115 GetReturnInfo(Fn->getReturnType(), Fn->getAttributes(), Outs, *TLI);
116 CanLowerReturn = TLI->CanLowerReturn(Fn->getCallingConv(), *MF,
Eric Christopher2ae2de72014-10-09 00:57:31 +0000117 Fn->isVarArg(), Outs, Fn->getContext());
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000118
Dan Gohmana3624b62009-11-23 17:16:22 +0000119 // Initialize the mapping of values to registers. This is only set up for
120 // instruction values that are used outside of the block that defines
121 // them.
Dan Gohman913c9982010-04-15 04:33:49 +0000122 Function::const_iterator BB = Fn->begin(), EB = Fn->end();
Dan Gohmana3624b62009-11-23 17:16:22 +0000123 for (; BB != EB; ++BB)
Eric Christopher219d51d2012-02-24 01:59:01 +0000124 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
125 I != E; ++I) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000126 if (const AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000127 // Static allocas can be folded into the initial stack frame adjustment.
128 if (AI->isStaticAlloca()) {
129 const ConstantInt *CUI = cast<ConstantInt>(AI->getArraySize());
130 Type *Ty = AI->getAllocatedType();
131 uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
132 unsigned Align =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000133 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
134 AI->getAlignment());
Reid Kleckner0b2bccc2014-09-02 18:42:44 +0000135
136 TySize *= CUI->getZExtValue(); // Get total allocated size.
137 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
138
139 StaticAllocaMap[AI] =
140 MF->getFrameInfo()->CreateStackObject(TySize, Align, false, AI);
141
142 } else {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000143 unsigned Align = std::max(
144 (unsigned)TLI->getDataLayout()->getPrefTypeAlignment(
145 AI->getAllocatedType()),
146 AI->getAlignment());
Eric Christopherd9134482014-08-04 21:25:23 +0000147 unsigned StackAlign =
Eric Christopher2ae2de72014-10-09 00:57:31 +0000148 MF->getSubtarget().getFrameLowering()->getStackAlignment();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000149 if (Align <= StackAlign)
150 Align = 0;
151 // Inform the Frame Information that we have variable-sized objects.
152 MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1, AI);
153 }
154 }
155
156 // Look for inline asm that clobbers the SP register.
157 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
158 ImmutableCallSite CS(I);
Hans Wennborg0c72fd22014-03-05 03:21:23 +0000159 if (isa<InlineAsm>(CS.getCalledValue())) {
Hans Wennborgacb842d2014-03-05 02:43:26 +0000160 unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
Eric Christopher11e4df72015-02-26 22:38:43 +0000161 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
Hans Wennborgacb842d2014-03-05 02:43:26 +0000162 std::vector<TargetLowering::AsmOperandInfo> Ops =
Eric Christopher11e4df72015-02-26 22:38:43 +0000163 TLI->ParseConstraints(TRI, CS);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000164 for (size_t I = 0, E = Ops.size(); I != E; ++I) {
165 TargetLowering::AsmOperandInfo &Op = Ops[I];
166 if (Op.Type == InlineAsm::isClobber) {
167 // Clobbers don't have SDValue operands, hence SDValue().
168 TLI->ComputeConstraintToUse(Op, SDValue(), DAG);
Eric Christopher2ae2de72014-10-09 00:57:31 +0000169 std::pair<unsigned, const TargetRegisterClass *> PhysReg =
Eric Christopher11e4df72015-02-26 22:38:43 +0000170 TLI->getRegForInlineAsmConstraint(TRI, Op.ConstraintCode,
171 Op.ConstraintVT);
Hans Wennborgacb842d2014-03-05 02:43:26 +0000172 if (PhysReg.first == SP)
173 MF->getFrameInfo()->setHasInlineAsmWithSPAdjust(true);
174 }
175 }
176 }
177 }
178
Reid Kleckner2d9bb652014-08-22 21:59:26 +0000179 // Look for calls to the @llvm.va_start intrinsic. We can omit some
180 // prologue boilerplate for variadic functions that don't examine their
181 // arguments.
182 if (const auto *II = dyn_cast<IntrinsicInst>(I)) {
183 if (II->getIntrinsicID() == Intrinsic::vastart)
184 MF->getFrameInfo()->setHasVAStart(true);
185 }
186
Reid Kleckner16e55412014-08-29 21:42:08 +0000187 // If we have a musttail call in a variadic funciton, we need to ensure we
188 // forward implicit register parameters.
Reid Klecknerdccd0cb2014-08-29 21:42:21 +0000189 if (const auto *CI = dyn_cast<CallInst>(I)) {
Reid Kleckner16e55412014-08-29 21:42:08 +0000190 if (CI->isMustTailCall() && Fn->isVarArg())
191 MF->getFrameInfo()->setHasMustTailInVarArgFunc(true);
192 }
193
Dan Gohman1e9362772010-07-16 17:54:27 +0000194 // Mark values used outside their block as exported, by allocating
195 // a virtual register for them.
Cameron Zwarichf8b22b32011-02-22 03:24:52 +0000196 if (isUsedOutsideOfDefiningBlock(I))
Dan Gohmana3624b62009-11-23 17:16:22 +0000197 if (!isa<AllocaInst>(I) ||
198 !StaticAllocaMap.count(cast<AllocaInst>(I)))
199 InitializeRegForValue(I);
200
Dan Gohman1e9362772010-07-16 17:54:27 +0000201 // Collect llvm.dbg.declare information. This is done now instead of
202 // during the initial isel pass through the IR so that it is done
203 // in a predictable order.
204 if (const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(I)) {
Duncan P. N. Exon Smithe686f152015-04-06 23:27:40 +0000205 DIVariable DIVar = DI->getVariable();
Duncan P. N. Exon Smith9dffcd02015-03-30 19:14:47 +0000206 if (MMI.hasDebugInfo() && DIVar && DI->getDebugLoc()) {
Dan Gohman1e9362772010-07-16 17:54:27 +0000207 // Don't handle byval struct arguments or VLAs, for example.
208 // Non-byval arguments are handled here (they refer to the stack
209 // temporary alloca at this point).
210 const Value *Address = DI->getAddress();
211 if (Address) {
212 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
213 Address = BCI->getOperand(0);
214 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
215 DenseMap<const AllocaInst *, int>::iterator SI =
216 StaticAllocaMap.find(AI);
217 if (SI != StaticAllocaMap.end()) { // Check for VLAs.
218 int FI = SI->second;
Adrian Prantl87b7eb92014-10-01 18:55:02 +0000219 MMI.setVariableDbgInfo(DI->getVariable(), DI->getExpression(),
Dan Gohman1e9362772010-07-16 17:54:27 +0000220 FI, DI->getDebugLoc());
221 }
222 }
223 }
224 }
225 }
Jiangning Liuffbc6902014-09-19 05:30:35 +0000226
227 // Decide the preferred extend type for a value.
228 PreferredExtendType[I] = getPreferredExtendForValue(I);
Dan Gohman1e9362772010-07-16 17:54:27 +0000229 }
230
Dan Gohmana3624b62009-11-23 17:16:22 +0000231 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
232 // also creates the initial PHI MachineInstrs, though none of the input
233 // operands are populated.
Dan Gohmanf57117d2010-04-14 16:30:40 +0000234 for (BB = Fn->begin(); BB != EB; ++BB) {
Dan Gohmana3624b62009-11-23 17:16:22 +0000235 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
236 MBBMap[BB] = MBB;
237 MF->push_back(MBB);
238
239 // Transfer the address-taken flag. This is necessary because there could
240 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
241 // the first one should be marked.
242 if (BB->hasAddressTaken())
243 MBB->setHasAddressTaken();
244
245 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
246 // appropriate.
Dan Gohman0f055d32010-04-20 14:46:25 +0000247 for (BasicBlock::const_iterator I = BB->begin();
248 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
249 if (PN->use_empty()) continue;
Dan Gohmana3624b62009-11-23 17:16:22 +0000250
Rafael Espindolae53b7d12011-05-13 15:18:06 +0000251 // Skip empty types
252 if (PN->getType()->isEmptyTy())
253 continue;
254
Dan Gohman7b7f0882010-04-20 14:48:02 +0000255 DebugLoc DL = PN->getDebugLoc();
Dan Gohmana3624b62009-11-23 17:16:22 +0000256 unsigned PHIReg = ValueMap[PN];
257 assert(PHIReg && "PHI node does not have an assigned virtual register!");
258
259 SmallVector<EVT, 4> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000260 ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000261 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
262 EVT VT = ValueVTs[vti];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000263 unsigned NumRegisters = TLI->getNumRegisters(Fn->getContext(), VT);
Eric Christopherfc6de422014-08-05 02:39:49 +0000264 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
Dan Gohmana3624b62009-11-23 17:16:22 +0000265 for (unsigned i = 0; i != NumRegisters; ++i)
Chris Lattnerb06015a2010-02-09 19:54:29 +0000266 BuildMI(MBB, DL, TII->get(TargetOpcode::PHI), PHIReg + i);
Dan Gohmana3624b62009-11-23 17:16:22 +0000267 PHIReg += NumRegisters;
268 }
269 }
270 }
Dan Gohman69e8e322010-04-14 16:32:56 +0000271
272 // Mark landing pad blocks.
273 for (BB = Fn->begin(); BB != EB; ++BB)
David Majnemercde33032015-03-30 22:58:10 +0000274 if (const auto *Invoke = dyn_cast<InvokeInst>(BB->getTerminator()))
Dan Gohman69e8e322010-04-14 16:32:56 +0000275 MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
David Majnemercde33032015-03-30 22:58:10 +0000276
277 // Calculate EH numbers for WinEH.
David Majnemer5c65f582015-04-10 04:56:17 +0000278 if (fn.hasFnAttribute("wineh-parent")) {
279 const Function *WinEHParentFn = MMI.getWinEHParent(&fn);
280 WinEHFuncInfo &FI = MMI.getWinEHFuncInfo(WinEHParentFn);
281 if (FI.LandingPadStateMap.empty()) {
282 WinEHNumbering Num(FI);
283 Num.calculateStateNumbers(*WinEHParentFn);
284 // Pop everything on the handler stack.
285 Num.processCallSite(None, ImmutableCallSite());
286 }
David Majnemera225a192015-03-31 22:35:44 +0000287 }
David Majnemercde33032015-03-30 22:58:10 +0000288}
289
David Majnemercde33032015-03-30 22:58:10 +0000290void WinEHNumbering::createUnwindMapEntry(int ToState, ActionHandler *AH) {
291 WinEHUnwindMapEntry UME;
292 UME.ToState = ToState;
David Majnemera225a192015-03-31 22:35:44 +0000293 if (auto *CH = dyn_cast_or_null<CleanupHandler>(AH))
David Majnemercde33032015-03-30 22:58:10 +0000294 UME.Cleanup = cast<Function>(CH->getHandlerBlockOrFunc());
295 else
296 UME.Cleanup = nullptr;
297 FuncInfo.UnwindMap.push_back(UME);
298}
299
David Majnemera225a192015-03-31 22:35:44 +0000300void WinEHNumbering::createTryBlockMapEntry(int TryLow, int TryHigh,
301 ArrayRef<CatchHandler *> Handlers) {
302 WinEHTryBlockMapEntry TBME;
303 TBME.TryLow = TryLow;
304 TBME.TryHigh = TryHigh;
David Majnemera225a192015-03-31 22:35:44 +0000305 assert(TBME.TryLow <= TBME.TryHigh);
David Majnemera225a192015-03-31 22:35:44 +0000306 for (CatchHandler *CH : Handlers) {
307 WinEHHandlerType HT;
David Majnemere8eb9e62015-04-01 05:20:42 +0000308 if (CH->getSelector()->isNullValue()) {
309 HT.Adjectives = 0x40;
310 HT.TypeDescriptor = nullptr;
311 } else {
312 auto *GV = cast<GlobalVariable>(CH->getSelector()->stripPointerCasts());
313 // Selectors are always pointers to GlobalVariables with 'struct' type.
314 // The struct has two fields, adjectives and a type descriptor.
315 auto *CS = cast<ConstantStruct>(GV->getInitializer());
316 HT.Adjectives =
317 cast<ConstantInt>(CS->getAggregateElement(0U))->getZExtValue();
318 HT.TypeDescriptor =
319 cast<GlobalVariable>(CS->getAggregateElement(1)->stripPointerCasts());
320 }
David Majnemera225a192015-03-31 22:35:44 +0000321 HT.Handler = cast<Function>(CH->getHandlerBlockOrFunc());
David Majnemer69132a72015-04-03 22:49:05 +0000322 HT.CatchObjRecoverIdx = CH->getExceptionVarIndex();
David Majnemera225a192015-03-31 22:35:44 +0000323 TBME.HandlerArray.push_back(HT);
324 }
325 FuncInfo.TryBlockMap.push_back(TBME);
326}
327
David Majnemercde33032015-03-30 22:58:10 +0000328static void print_name(const Value *V) {
David Majnemer9a555392015-03-30 23:14:45 +0000329#ifndef NDEBUG
David Majnemercde33032015-03-30 22:58:10 +0000330 if (!V) {
331 DEBUG(dbgs() << "null");
332 return;
333 }
334
335 if (const auto *F = dyn_cast<Function>(V))
336 DEBUG(dbgs() << F->getName());
337 else
338 DEBUG(V->dump());
David Majnemer9a555392015-03-30 23:14:45 +0000339#endif
David Majnemercde33032015-03-30 22:58:10 +0000340}
341
David Majnemera225a192015-03-31 22:35:44 +0000342void WinEHNumbering::processCallSite(ArrayRef<ActionHandler *> Actions,
343 ImmutableCallSite CS) {
David Majnemercde33032015-03-30 22:58:10 +0000344 int FirstMismatch = 0;
345 for (int E = std::min(HandlerStack.size(), Actions.size()); FirstMismatch < E;
346 ++FirstMismatch) {
347 if (HandlerStack[FirstMismatch]->getHandlerBlockOrFunc() !=
348 Actions[FirstMismatch]->getHandlerBlockOrFunc())
349 break;
350 delete Actions[FirstMismatch];
351 }
352
David Majnemera225a192015-03-31 22:35:44 +0000353 bool EnteringScope = (int)Actions.size() > FirstMismatch;
David Majnemera225a192015-03-31 22:35:44 +0000354
David Majnemercde33032015-03-30 22:58:10 +0000355 // Don't recurse while we are looping over the handler stack. Instead, defer
356 // the numbering of the catch handlers until we are done popping.
David Majnemera225a192015-03-31 22:35:44 +0000357 SmallVector<CatchHandler *, 4> PoppedCatches;
David Majnemercde33032015-03-30 22:58:10 +0000358 for (int I = HandlerStack.size() - 1; I >= FirstMismatch; --I) {
David Majnemera225a192015-03-31 22:35:44 +0000359 if (auto *CH = dyn_cast<CatchHandler>(HandlerStack.back())) {
360 PoppedCatches.push_back(CH);
361 } else {
362 // Delete cleanup handlers
363 delete HandlerStack.back();
364 }
David Majnemercde33032015-03-30 22:58:10 +0000365 HandlerStack.pop_back();
366 }
367
David Majnemera225a192015-03-31 22:35:44 +0000368 // We need to create a new state number if we are exiting a try scope and we
369 // will not push any more actions.
370 int TryHigh = NextState - 1;
David Majnemerd1079bf2015-03-31 22:43:56 +0000371 if (!EnteringScope && !PoppedCatches.empty()) {
David Majnemera225a192015-03-31 22:35:44 +0000372 createUnwindMapEntry(currentEHNumber(), nullptr);
373 ++NextState;
374 }
David Majnemercde33032015-03-30 22:58:10 +0000375
David Majnemera225a192015-03-31 22:35:44 +0000376 int LastTryLowIdx = 0;
377 for (int I = 0, E = PoppedCatches.size(); I != E; ++I) {
378 CatchHandler *CH = PoppedCatches[I];
379 if (I + 1 == E || CH->getEHState() != PoppedCatches[I + 1]->getEHState()) {
380 int TryLow = CH->getEHState();
381 auto Handlers =
382 makeArrayRef(&PoppedCatches[LastTryLowIdx], I - LastTryLowIdx + 1);
383 createTryBlockMapEntry(TryLow, TryHigh, Handlers);
384 LastTryLowIdx = I + 1;
385 }
386 }
387
388 for (CatchHandler *CH : PoppedCatches) {
389 if (auto *F = dyn_cast<Function>(CH->getHandlerBlockOrFunc()))
390 calculateStateNumbers(*F);
391 delete CH;
392 }
393
394 bool LastActionWasCatch = false;
David Majnemercde33032015-03-30 22:58:10 +0000395 for (size_t I = FirstMismatch; I != Actions.size(); ++I) {
David Majnemera225a192015-03-31 22:35:44 +0000396 // We can reuse eh states when pushing two catches for the same invoke.
397 bool CurrActionIsCatch = isa<CatchHandler>(Actions[I]);
398 // FIXME: Reenable this optimization!
399 if (CurrActionIsCatch && LastActionWasCatch && false) {
400 Actions[I]->setEHState(currentEHNumber());
401 } else {
402 createUnwindMapEntry(currentEHNumber(), Actions[I]);
403 Actions[I]->setEHState(NextState);
404 NextState++;
405 DEBUG(dbgs() << "Creating unwind map entry for: (");
406 print_name(Actions[I]->getHandlerBlockOrFunc());
407 DEBUG(dbgs() << ", " << currentEHNumber() << ")\n");
408 }
David Majnemercde33032015-03-30 22:58:10 +0000409 HandlerStack.push_back(Actions[I]);
David Majnemera225a192015-03-31 22:35:44 +0000410 LastActionWasCatch = CurrActionIsCatch;
David Majnemercde33032015-03-30 22:58:10 +0000411 }
412
413 DEBUG(dbgs() << "In EHState " << currentEHNumber() << " for CallSite: ");
414 print_name(CS ? CS.getCalledValue() : nullptr);
415 DEBUG(dbgs() << '\n');
416}
417
418void WinEHNumbering::calculateStateNumbers(const Function &F) {
David Majnemera225a192015-03-31 22:35:44 +0000419 auto I = VisitedHandlers.insert(&F);
420 if (!I.second)
421 return; // We've already visited this handler, don't renumber it.
422
David Majnemercde33032015-03-30 22:58:10 +0000423 DEBUG(dbgs() << "Calculating state numbers for: " << F.getName() << '\n');
424 SmallVector<ActionHandler *, 4> ActionList;
425 for (const BasicBlock &BB : F) {
426 for (const Instruction &I : BB) {
427 const auto *CI = dyn_cast<CallInst>(&I);
428 if (!CI || CI->doesNotThrow())
429 continue;
David Majnemera225a192015-03-31 22:35:44 +0000430 processCallSite(None, CI);
David Majnemercde33032015-03-30 22:58:10 +0000431 }
432 const auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
433 if (!II)
434 continue;
435 const LandingPadInst *LPI = II->getLandingPadInst();
David Majnemera225a192015-03-31 22:35:44 +0000436 auto *ActionsCall = dyn_cast<IntrinsicInst>(LPI->getNextNode());
437 if (!ActionsCall)
438 continue;
439 assert(ActionsCall->getIntrinsicID() == Intrinsic::eh_actions);
440 parseEHActions(ActionsCall, ActionList);
441 processCallSite(ActionList, II);
442 ActionList.clear();
443 FuncInfo.LandingPadStateMap[LPI] = currentEHNumber();
David Majnemercde33032015-03-30 22:58:10 +0000444 }
David Majnemer7f5e7142015-04-03 23:37:34 +0000445
446 FuncInfo.CatchHandlerMaxState[&F] = NextState - 1;
Dan Gohmana3624b62009-11-23 17:16:22 +0000447}
448
449/// clear - Clear out all the function-specific state. This returns this
450/// FunctionLoweringInfo to an empty state, ready to be used for a
451/// different function.
452void FunctionLoweringInfo::clear() {
Dan Gohmanad0b3ea2010-04-14 17:11:23 +0000453 assert(CatchInfoFound.size() == CatchInfoLost.size() &&
454 "Not all catch info was assigned to a landing pad!");
455
Dan Gohmana3624b62009-11-23 17:16:22 +0000456 MBBMap.clear();
457 ValueMap.clear();
458 StaticAllocaMap.clear();
459#ifndef NDEBUG
460 CatchInfoLost.clear();
461 CatchInfoFound.clear();
462#endif
463 LiveOutRegInfo.clear();
Cameron Zwarich988faf92011-02-24 10:00:13 +0000464 VisitedBBs.clear();
Evan Cheng6e822452010-04-28 23:08:54 +0000465 ArgDbgValues.clear();
Devang Patel86ec8b32010-08-31 22:22:42 +0000466 ByValArgFrameIndexMap.clear();
Dan Gohmand7b5ce32010-07-10 09:00:22 +0000467 RegFixups.clear();
Philip Reames1a1bdb22014-12-02 18:50:36 +0000468 StatepointStackSlots.clear();
Jiangning Liu3b096172014-09-24 03:22:56 +0000469 PreferredExtendType.clear();
Dan Gohmana3624b62009-11-23 17:16:22 +0000470}
471
Dan Gohman93f59202010-07-02 00:10:16 +0000472/// CreateReg - Allocate a single virtual register for the given type.
Patrik Hagglund5e6c3612012-12-13 06:34:11 +0000473unsigned FunctionLoweringInfo::CreateReg(MVT VT) {
Eric Christopherd9134482014-08-04 21:25:23 +0000474 return RegInfo->createVirtualRegister(
Eric Christopher2ae2de72014-10-09 00:57:31 +0000475 MF->getSubtarget().getTargetLowering()->getRegClassFor(VT));
Dan Gohmana3624b62009-11-23 17:16:22 +0000476}
477
Dan Gohman93f59202010-07-02 00:10:16 +0000478/// CreateRegs - Allocate the appropriate number of virtual registers of
Dan Gohmana3624b62009-11-23 17:16:22 +0000479/// the correctly promoted or expanded types. Assign these registers
480/// consecutive vreg numbers and return the first assigned number.
481///
482/// In the case that the given value has struct or array type, this function
483/// will assign registers for each member or element.
484///
Chris Lattner229907c2011-07-18 04:54:35 +0000485unsigned FunctionLoweringInfo::CreateRegs(Type *Ty) {
Eric Christopher2ae2de72014-10-09 00:57:31 +0000486 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
Bill Wendling0ccf3102013-06-19 20:32:16 +0000487
Dan Gohmana3624b62009-11-23 17:16:22 +0000488 SmallVector<EVT, 4> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000489 ComputeValueVTs(*TLI, Ty, ValueVTs);
Dan Gohmana3624b62009-11-23 17:16:22 +0000490
491 unsigned FirstReg = 0;
492 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
493 EVT ValueVT = ValueVTs[Value];
Bill Wendling8db01cb2013-06-06 00:11:39 +0000494 MVT RegisterVT = TLI->getRegisterType(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000495
Bill Wendling8db01cb2013-06-06 00:11:39 +0000496 unsigned NumRegs = TLI->getNumRegisters(Ty->getContext(), ValueVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000497 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman93f59202010-07-02 00:10:16 +0000498 unsigned R = CreateReg(RegisterVT);
Dan Gohmana3624b62009-11-23 17:16:22 +0000499 if (!FirstReg) FirstReg = R;
500 }
501 }
502 return FirstReg;
503}
Dan Gohmanad97b3d2009-11-23 17:42:46 +0000504
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000505/// GetLiveOutRegInfo - Gets LiveOutInfo for a register, returning NULL if the
506/// register is a PHI destination and the PHI's LiveOutInfo is not valid. If
507/// the register's LiveOutInfo is for a smaller bit width, it is extended to
508/// the larger bit width by zero extension. The bit width must be no smaller
509/// than the LiveOutInfo's existing bit width.
510const FunctionLoweringInfo::LiveOutInfo *
511FunctionLoweringInfo::GetLiveOutRegInfo(unsigned Reg, unsigned BitWidth) {
512 if (!LiveOutRegInfo.inBounds(Reg))
Craig Topperc0196b12014-04-14 00:51:57 +0000513 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000514
515 LiveOutInfo *LOI = &LiveOutRegInfo[Reg];
516 if (!LOI->IsValid)
Craig Topperc0196b12014-04-14 00:51:57 +0000517 return nullptr;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000518
Cameron Zwarichd2f30412011-02-25 01:10:55 +0000519 if (BitWidth > LOI->KnownZero.getBitWidth()) {
Cameron Zwarich4c82cd22011-02-25 01:11:01 +0000520 LOI->NumSignBits = 1;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000521 LOI->KnownZero = LOI->KnownZero.zextOrTrunc(BitWidth);
522 LOI->KnownOne = LOI->KnownOne.zextOrTrunc(BitWidth);
523 }
524
525 return LOI;
526}
527
528/// ComputePHILiveOutRegInfo - Compute LiveOutInfo for a PHI's destination
529/// register based on the LiveOutInfo of its operands.
530void FunctionLoweringInfo::ComputePHILiveOutRegInfo(const PHINode *PN) {
Chris Lattner229907c2011-07-18 04:54:35 +0000531 Type *Ty = PN->getType();
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000532 if (!Ty->isIntegerTy() || Ty->isVectorTy())
533 return;
534
535 SmallVector<EVT, 1> ValueVTs;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000536 ComputeValueVTs(*TLI, Ty, ValueVTs);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000537 assert(ValueVTs.size() == 1 &&
538 "PHIs with non-vector integer types should have a single VT.");
539 EVT IntVT = ValueVTs[0];
540
Bill Wendling8db01cb2013-06-06 00:11:39 +0000541 if (TLI->getNumRegisters(PN->getContext(), IntVT) != 1)
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000542 return;
Bill Wendling8db01cb2013-06-06 00:11:39 +0000543 IntVT = TLI->getTypeToTransformTo(PN->getContext(), IntVT);
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000544 unsigned BitWidth = IntVT.getSizeInBits();
545
546 unsigned DestReg = ValueMap[PN];
547 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
548 return;
549 LiveOutRegInfo.grow(DestReg);
550 LiveOutInfo &DestLOI = LiveOutRegInfo[DestReg];
551
552 Value *V = PN->getIncomingValue(0);
553 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
554 DestLOI.NumSignBits = 1;
555 APInt Zero(BitWidth, 0);
556 DestLOI.KnownZero = Zero;
557 DestLOI.KnownOne = Zero;
558 return;
559 }
560
561 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
562 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
563 DestLOI.NumSignBits = Val.getNumSignBits();
564 DestLOI.KnownZero = ~Val;
565 DestLOI.KnownOne = Val;
566 } else {
567 assert(ValueMap.count(V) && "V should have been placed in ValueMap when its"
568 "CopyToReg node was created.");
569 unsigned SrcReg = ValueMap[V];
570 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
571 DestLOI.IsValid = false;
572 return;
573 }
574 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
575 if (!SrcLOI) {
576 DestLOI.IsValid = false;
577 return;
578 }
579 DestLOI = *SrcLOI;
580 }
581
582 assert(DestLOI.KnownZero.getBitWidth() == BitWidth &&
583 DestLOI.KnownOne.getBitWidth() == BitWidth &&
584 "Masks should have the same bit width as the type.");
585
586 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) {
587 Value *V = PN->getIncomingValue(i);
588 if (isa<UndefValue>(V) || isa<ConstantExpr>(V)) {
589 DestLOI.NumSignBits = 1;
590 APInt Zero(BitWidth, 0);
591 DestLOI.KnownZero = Zero;
592 DestLOI.KnownOne = Zero;
Eric Christopher0713a9d2011-06-08 23:55:35 +0000593 return;
Cameron Zwaricha62fc892011-02-24 10:00:25 +0000594 }
595
596 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
597 APInt Val = CI->getValue().zextOrTrunc(BitWidth);
598 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, Val.getNumSignBits());
599 DestLOI.KnownZero &= ~Val;
600 DestLOI.KnownOne &= Val;
601 continue;
602 }
603
604 assert(ValueMap.count(V) && "V should have been placed in ValueMap when "
605 "its CopyToReg node was created.");
606 unsigned SrcReg = ValueMap[V];
607 if (!TargetRegisterInfo::isVirtualRegister(SrcReg)) {
608 DestLOI.IsValid = false;
609 return;
610 }
611 const LiveOutInfo *SrcLOI = GetLiveOutRegInfo(SrcReg, BitWidth);
612 if (!SrcLOI) {
613 DestLOI.IsValid = false;
614 return;
615 }
616 DestLOI.NumSignBits = std::min(DestLOI.NumSignBits, SrcLOI->NumSignBits);
617 DestLOI.KnownZero &= SrcLOI->KnownZero;
618 DestLOI.KnownOne &= SrcLOI->KnownOne;
619 }
620}
621
Devang Patel9d904e12011-09-08 22:59:09 +0000622/// setArgumentFrameIndex - Record frame index for the byval
Devang Patel86ec8b32010-08-31 22:22:42 +0000623/// argument. This overrides previous frame index entry for this argument,
624/// if any.
Devang Patel9d904e12011-09-08 22:59:09 +0000625void FunctionLoweringInfo::setArgumentFrameIndex(const Argument *A,
Eric Christopher219d51d2012-02-24 01:59:01 +0000626 int FI) {
Devang Patel86ec8b32010-08-31 22:22:42 +0000627 ByValArgFrameIndexMap[A] = FI;
628}
Eric Christopher0713a9d2011-06-08 23:55:35 +0000629
Devang Patel9d904e12011-09-08 22:59:09 +0000630/// getArgumentFrameIndex - Get frame index for the byval argument.
Devang Patel86ec8b32010-08-31 22:22:42 +0000631/// If the argument does not have any assigned frame index then 0 is
632/// returned.
Devang Patel9d904e12011-09-08 22:59:09 +0000633int FunctionLoweringInfo::getArgumentFrameIndex(const Argument *A) {
Eric Christopher0713a9d2011-06-08 23:55:35 +0000634 DenseMap<const Argument *, int>::iterator I =
Devang Patel86ec8b32010-08-31 22:22:42 +0000635 ByValArgFrameIndexMap.find(A);
636 if (I != ByValArgFrameIndexMap.end())
637 return I->second;
Eric Christopher18c6be72012-02-23 03:39:43 +0000638 DEBUG(dbgs() << "Argument does not have assigned frame index!\n");
Devang Patel86ec8b32010-08-31 22:22:42 +0000639 return 0;
640}
641
Michael J. Spencer8b98bf22012-02-22 19:06:13 +0000642/// ComputeUsesVAFloatArgument - Determine if any floating-point values are
643/// being passed to this variadic function, and set the MachineModuleInfo's
644/// usesVAFloatArgument flag if so. This flag is used to emit an undefined
645/// reference to _fltused on Windows, which will link in MSVCRT's
646/// floating-point support.
647void llvm::ComputeUsesVAFloatArgument(const CallInst &I,
648 MachineModuleInfo *MMI)
649{
650 FunctionType *FT = cast<FunctionType>(
651 I.getCalledValue()->getType()->getContainedType(0));
652 if (FT->isVarArg() && !MMI->usesVAFloatArgument()) {
653 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
654 Type* T = I.getArgOperand(i)->getType();
655 for (po_iterator<Type*> i = po_begin(T), e = po_end(T);
656 i != e; ++i) {
657 if (i->isFloatingPointTy()) {
658 MMI->setUsesVAFloatArgument(true);
659 return;
660 }
661 }
662 }
663 }
664}
665
Bill Wendling247fd3b2011-08-17 21:56:44 +0000666/// AddLandingPadInfo - Extract the exception handling information from the
667/// landingpad instruction and add them to the specified machine module info.
668void llvm::AddLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI,
669 MachineBasicBlock *MBB) {
670 MMI.addPersonality(MBB,
671 cast<Function>(I.getPersonalityFn()->stripPointerCasts()));
672
673 if (I.isCleanup())
674 MMI.addCleanup(MBB);
675
676 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
677 // but we need to do it this way because of how the DWARF EH emitter
678 // processes the clauses.
679 for (unsigned i = I.getNumClauses(); i != 0; --i) {
680 Value *Val = I.getClause(i - 1);
681 if (I.isCatch(i - 1)) {
682 MMI.addCatchTypeInfo(MBB,
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000683 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000684 } else {
685 // Add filters in a list.
686 Constant *CVal = cast<Constant>(Val);
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000687 SmallVector<const GlobalValue*, 4> FilterList;
Bill Wendling247fd3b2011-08-17 21:56:44 +0000688 for (User::op_iterator
689 II = CVal->op_begin(), IE = CVal->op_end(); II != IE; ++II)
Reid Kleckner283bc2e2014-11-14 00:35:50 +0000690 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
Bill Wendling247fd3b2011-08-17 21:56:44 +0000691
692 MMI.addFilterTypeInfo(MBB, FilterList);
693 }
694 }
695}