blob: 3069465800cbef94d5c30ea4f4318b4ee3406751 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskeyb2efb852006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner7944d9d2005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner4e4b5762006-02-01 18:59:47 +000043#include <set>
Chris Lattner1c08c712005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen7e881032006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattnerda8abb02005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000055#else
Evan Chenga9c20912006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#endif
59
Evan Cheng4ef10862006-01-23 07:01:07 +000060namespace {
61 cl::opt<SchedHeuristics>
62 ISHeuristic(
63 "sched",
64 cl::desc("Choose scheduling style"),
Evan Cheng3f239522006-01-25 09:12:57 +000065 cl::init(defaultScheduling),
Evan Cheng4ef10862006-01-23 07:01:07 +000066 cl::values(
Evan Cheng3f239522006-01-25 09:12:57 +000067 clEnumValN(defaultScheduling, "default",
68 "Target preferred scheduling style"),
Evan Cheng4ef10862006-01-23 07:01:07 +000069 clEnumValN(noScheduling, "none",
Jim Laskey17d52f72006-01-23 13:34:04 +000070 "No scheduling: breadth first sequencing"),
Evan Cheng4ef10862006-01-23 07:01:07 +000071 clEnumValN(simpleScheduling, "simple",
72 "Simple two pass scheduling: minimize critical path "
73 "and maximize processor utilization"),
74 clEnumValN(simpleNoItinScheduling, "simple-noitin",
75 "Simple two pass scheduling: Same as simple "
76 "except using generic latency"),
Evan Cheng3f239522006-01-25 09:12:57 +000077 clEnumValN(listSchedulingBURR, "list-burr",
Evan Chengf0f9c902006-01-23 08:26:10 +000078 "Bottom up register reduction list scheduling"),
Evan Cheng4ef10862006-01-23 07:01:07 +000079 clEnumValEnd));
80} // namespace
81
Chris Lattner864635a2006-02-22 22:37:12 +000082namespace {
83 /// RegsForValue - This struct represents the physical registers that a
84 /// particular value is assigned and the type information about the value.
85 /// This is needed because values can be promoted into larger registers and
86 /// expanded into multiple smaller registers than the value.
87 struct RegsForValue {
88 /// Regs - This list hold the register (for legal and promoted values)
89 /// or register set (for expanded values) that the value should be assigned
90 /// to.
91 std::vector<unsigned> Regs;
92
93 /// RegVT - The value type of each register.
94 ///
95 MVT::ValueType RegVT;
96
97 /// ValueVT - The value type of the LLVM value, which may be promoted from
98 /// RegVT or made from merging the two expanded parts.
99 MVT::ValueType ValueVT;
100
101 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
102
103 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
104 : RegVT(regvt), ValueVT(valuevt) {
105 Regs.push_back(Reg);
106 }
107 RegsForValue(const std::vector<unsigned> &regs,
108 MVT::ValueType regvt, MVT::ValueType valuevt)
109 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
110 }
111
112 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
113 /// this value and returns the result as a ValueVT value. This uses
114 /// Chain/Flag as the input and updates them for the output Chain/Flag.
115 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000116 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000117
118 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
119 /// specified value into the registers specified by this object. This uses
120 /// Chain/Flag as the input and updates them for the output Chain/Flag.
121 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000122 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000123
124 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
125 /// operand list. This adds the code marker and includes the number of
126 /// values added into it.
127 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000128 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000129 };
130}
Evan Cheng4ef10862006-01-23 07:01:07 +0000131
Chris Lattner1c08c712005-01-07 07:47:53 +0000132namespace llvm {
133 //===--------------------------------------------------------------------===//
134 /// FunctionLoweringInfo - This contains information that is global to a
135 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000136 class FunctionLoweringInfo {
137 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000138 TargetLowering &TLI;
139 Function &Fn;
140 MachineFunction &MF;
141 SSARegMap *RegMap;
142
143 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
144
145 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
146 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
147
148 /// ValueMap - Since we emit code for the function a basic block at a time,
149 /// we must remember which virtual registers hold the values for
150 /// cross-basic-block values.
151 std::map<const Value*, unsigned> ValueMap;
152
153 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
154 /// the entry block. This allows the allocas to be efficiently referenced
155 /// anywhere in the function.
156 std::map<const AllocaInst*, int> StaticAllocaMap;
157
158 unsigned MakeReg(MVT::ValueType VT) {
159 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
160 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000161
Chris Lattner1c08c712005-01-07 07:47:53 +0000162 unsigned CreateRegForValue(const Value *V) {
163 MVT::ValueType VT = TLI.getValueType(V->getType());
164 // The common case is that we will only create one register for this
165 // value. If we have that case, create and return the virtual register.
166 unsigned NV = TLI.getNumElements(VT);
Chris Lattnerfb849802005-01-16 00:37:38 +0000167 if (NV == 1) {
168 // If we are promoting this value, pick the next largest supported type.
Chris Lattner98e5c0e2005-01-16 01:11:19 +0000169 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnerfb849802005-01-16 00:37:38 +0000170 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000171
Chris Lattner1c08c712005-01-07 07:47:53 +0000172 // If this value is represented with multiple target registers, make sure
Chris Lattner864635a2006-02-22 22:37:12 +0000173 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner1c08c712005-01-07 07:47:53 +0000174 unsigned NT = VT-1; // Find the type to use.
175 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
176 --NT;
Misha Brukmanedf128a2005-04-21 22:36:52 +0000177
Chris Lattner1c08c712005-01-07 07:47:53 +0000178 unsigned R = MakeReg((MVT::ValueType)NT);
179 for (unsigned i = 1; i != NV; ++i)
180 MakeReg((MVT::ValueType)NT);
181 return R;
182 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000183
Chris Lattner1c08c712005-01-07 07:47:53 +0000184 unsigned InitializeRegForValue(const Value *V) {
185 unsigned &R = ValueMap[V];
186 assert(R == 0 && "Already initialized this value register!");
187 return R = CreateRegForValue(V);
188 }
189 };
190}
191
192/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
193/// PHI nodes or outside of the basic block that defines it.
194static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
195 if (isa<PHINode>(I)) return true;
196 BasicBlock *BB = I->getParent();
197 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
198 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
199 return true;
200 return false;
201}
202
Chris Lattnerbf209482005-10-30 19:42:35 +0000203/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
204/// entry block, return true.
205static bool isOnlyUsedInEntryBlock(Argument *A) {
206 BasicBlock *Entry = A->getParent()->begin();
207 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
208 if (cast<Instruction>(*UI)->getParent() != Entry)
209 return false; // Use not in entry block.
210 return true;
211}
212
Chris Lattner1c08c712005-01-07 07:47:53 +0000213FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000214 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000215 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
216
Chris Lattnerbf209482005-10-30 19:42:35 +0000217 // Create a vreg for each argument register that is not dead and is used
218 // outside of the entry block for the function.
219 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
220 AI != E; ++AI)
221 if (!isOnlyUsedInEntryBlock(AI))
222 InitializeRegForValue(AI);
223
Chris Lattner1c08c712005-01-07 07:47:53 +0000224 // Initialize the mapping of values to registers. This is only set up for
225 // instruction values that are used outside of the block that defines
226 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000227 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
229 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
230 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
231 const Type *Ty = AI->getAllocatedType();
232 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000233 unsigned Align =
234 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
235 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000236
237 // If the alignment of the value is smaller than the size of the value,
238 // and if the size of the value is particularly small (<= 8 bytes),
239 // round up to the size of the value for potentially better performance.
240 //
241 // FIXME: This could be made better with a preferred alignment hook in
242 // TargetData. It serves primarily to 8-byte align doubles for X86.
243 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner2dfa8192005-10-18 22:11:42 +0000244 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000245 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000246 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000247 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000248 }
249
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000250 for (; BB != EB; ++BB)
251 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000252 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
253 if (!isa<AllocaInst>(I) ||
254 !StaticAllocaMap.count(cast<AllocaInst>(I)))
255 InitializeRegForValue(I);
256
257 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
258 // also creates the initial PHI MachineInstrs, though none of the input
259 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000260 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000261 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
262 MBBMap[BB] = MBB;
263 MF.getBasicBlockList().push_back(MBB);
264
265 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
266 // appropriate.
267 PHINode *PN;
268 for (BasicBlock::iterator I = BB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +0000269 (PN = dyn_cast<PHINode>(I)); ++I)
270 if (!PN->use_empty()) {
271 unsigned NumElements =
272 TLI.getNumElements(TLI.getValueType(PN->getType()));
273 unsigned PHIReg = ValueMap[PN];
274 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
275 for (unsigned i = 0; i != NumElements; ++i)
276 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
277 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000278 }
279}
280
281
282
283//===----------------------------------------------------------------------===//
284/// SelectionDAGLowering - This is the common target-independent lowering
285/// implementation that is parameterized by a TargetLowering object.
286/// Also, targets can overload any lowering method.
287///
288namespace llvm {
289class SelectionDAGLowering {
290 MachineBasicBlock *CurMBB;
291
292 std::map<const Value*, SDOperand> NodeMap;
293
Chris Lattnerd3948112005-01-17 22:19:26 +0000294 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
295 /// them up and then emit token factor nodes when possible. This allows us to
296 /// get simple disambiguation between loads without worrying about alias
297 /// analysis.
298 std::vector<SDOperand> PendingLoads;
299
Chris Lattner1c08c712005-01-07 07:47:53 +0000300public:
301 // TLI - This is information that describes the available target features we
302 // need for lowering. This indicates when operations are unavailable,
303 // implemented with a libcall, etc.
304 TargetLowering &TLI;
305 SelectionDAG &DAG;
306 const TargetData &TD;
307
308 /// FuncInfo - Information about the function as a whole.
309 ///
310 FunctionLoweringInfo &FuncInfo;
311
312 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000313 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000314 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
315 FuncInfo(funcinfo) {
316 }
317
Chris Lattnera651cf62005-01-17 19:43:36 +0000318 /// getRoot - Return the current virtual root of the Selection DAG.
319 ///
320 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000321 if (PendingLoads.empty())
322 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000323
Chris Lattnerd3948112005-01-17 22:19:26 +0000324 if (PendingLoads.size() == 1) {
325 SDOperand Root = PendingLoads[0];
326 DAG.setRoot(Root);
327 PendingLoads.clear();
328 return Root;
329 }
330
331 // Otherwise, we have to make a token factor node.
332 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
333 PendingLoads.clear();
334 DAG.setRoot(Root);
335 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000336 }
337
Chris Lattner1c08c712005-01-07 07:47:53 +0000338 void visit(Instruction &I) { visit(I.getOpcode(), I); }
339
340 void visit(unsigned Opcode, User &I) {
341 switch (Opcode) {
342 default: assert(0 && "Unknown instruction type encountered!");
343 abort();
344 // Build the switch statement using the Instruction.def file.
345#define HANDLE_INST(NUM, OPCODE, CLASS) \
346 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
347#include "llvm/Instruction.def"
348 }
349 }
350
351 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
352
353
354 SDOperand getIntPtrConstant(uint64_t Val) {
355 return DAG.getConstant(Val, TLI.getPointerTy());
356 }
357
358 SDOperand getValue(const Value *V) {
359 SDOperand &N = NodeMap[V];
360 if (N.Val) return N;
361
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000362 const Type *VTy = V->getType();
363 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner1c08c712005-01-07 07:47:53 +0000364 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
365 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
366 visit(CE->getOpcode(), *CE);
367 assert(N.Val && "visit didn't populate the ValueMap!");
368 return N;
369 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
370 return N = DAG.getGlobalAddress(GV, VT);
371 } else if (isa<ConstantPointerNull>(C)) {
372 return N = DAG.getConstant(0, TLI.getPointerTy());
373 } else if (isa<UndefValue>(C)) {
Nate Begemanb8827522005-04-12 23:12:17 +0000374 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner1c08c712005-01-07 07:47:53 +0000375 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
376 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000377 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
378 unsigned NumElements = PTy->getNumElements();
379 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
380 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
381
382 // Now that we know the number and type of the elements, push a
383 // Constant or ConstantFP node onto the ops list for each element of
384 // the packed constant.
385 std::vector<SDOperand> Ops;
Chris Lattner3b841e92005-12-21 02:43:26 +0000386 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
387 if (MVT::isFloatingPoint(PVT)) {
388 for (unsigned i = 0; i != NumElements; ++i) {
389 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
390 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
391 }
392 } else {
393 for (unsigned i = 0; i != NumElements; ++i) {
394 const ConstantIntegral *El =
395 cast<ConstantIntegral>(CP->getOperand(i));
396 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
397 }
398 }
399 } else {
400 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
401 SDOperand Op;
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000402 if (MVT::isFloatingPoint(PVT))
Chris Lattner3b841e92005-12-21 02:43:26 +0000403 Op = DAG.getConstantFP(0, PVT);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000404 else
Chris Lattner3b841e92005-12-21 02:43:26 +0000405 Op = DAG.getConstant(0, PVT);
406 Ops.assign(NumElements, Op);
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000407 }
Chris Lattner3b841e92005-12-21 02:43:26 +0000408
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000409 // Handle the case where we have a 1-element vector, in which
410 // case we want to immediately turn it into a scalar constant.
Nate Begemancc827e62005-12-07 19:48:11 +0000411 if (Ops.size() == 1) {
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000412 return N = Ops[0];
Nate Begemancc827e62005-12-07 19:48:11 +0000413 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
414 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
415 } else {
416 // If the packed type isn't legal, then create a ConstantVec node with
417 // generic Vector type instead.
Evan Cheng860771d2006-03-01 01:09:54 +0000418 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
419 SDOperand Typ = DAG.getValueType(PVT);
420 Ops.insert(Ops.begin(), Typ);
421 Ops.insert(Ops.begin(), Num);
422 return N = DAG.getNode(ISD::VConstant, MVT::Vector, Ops);
Nate Begemancc827e62005-12-07 19:48:11 +0000423 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000424 } else {
425 // Canonicalize all constant ints to be unsigned.
426 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
427 }
428
429 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
430 std::map<const AllocaInst*, int>::iterator SI =
431 FuncInfo.StaticAllocaMap.find(AI);
432 if (SI != FuncInfo.StaticAllocaMap.end())
433 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
434 }
435
436 std::map<const Value*, unsigned>::const_iterator VMI =
437 FuncInfo.ValueMap.find(V);
438 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattnerc8ea3c42005-01-16 02:23:07 +0000439
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +0000440 unsigned InReg = VMI->second;
441
442 // If this type is not legal, make it so now.
443 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
444
445 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
446 if (DestVT < VT) {
447 // Source must be expanded. This input value is actually coming from the
448 // register pair VMI->second and VMI->second+1.
449 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
450 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
451 } else {
452 if (DestVT > VT) { // Promotion case
453 if (MVT::isFloatingPoint(VT))
454 N = DAG.getNode(ISD::FP_ROUND, VT, N);
455 else
456 N = DAG.getNode(ISD::TRUNCATE, VT, N);
457 }
458 }
459
460 return N;
Chris Lattner1c08c712005-01-07 07:47:53 +0000461 }
462
463 const SDOperand &setValue(const Value *V, SDOperand NewN) {
464 SDOperand &N = NodeMap[V];
465 assert(N.Val == 0 && "Already set a value for this node!");
466 return N = NewN;
467 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000468
Chris Lattner864635a2006-02-22 22:37:12 +0000469 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
470 MVT::ValueType VT,
471 bool OutReg, bool InReg,
472 std::set<unsigned> &OutputRegs,
473 std::set<unsigned> &InputRegs);
474
Chris Lattner1c08c712005-01-07 07:47:53 +0000475 // Terminator instructions.
476 void visitRet(ReturnInst &I);
477 void visitBr(BranchInst &I);
478 void visitUnreachable(UnreachableInst &I) { /* noop */ }
479
480 // These all get lowered before this pass.
Robert Bocchinoc0f4cd92006-01-10 19:04:57 +0000481 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino4eb2e3a2006-01-17 20:06:42 +0000482 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner1c08c712005-01-07 07:47:53 +0000483 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
484 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
485 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
486
487 //
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000488 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000489 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000490 void visitAdd(User &I) {
491 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000492 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000493 void visitSub(User &I);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000494 void visitMul(User &I) {
495 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000496 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000497 void visitDiv(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000498 const Type *Ty = I.getType();
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000499 visitBinary(I,
500 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
501 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
Chris Lattner1c08c712005-01-07 07:47:53 +0000502 }
503 void visitRem(User &I) {
Chris Lattner01b3d732005-09-28 22:28:18 +0000504 const Type *Ty = I.getType();
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000505 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner1c08c712005-01-07 07:47:53 +0000506 }
Evan Cheng3e1ce5a2006-03-03 07:01:07 +0000507 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
508 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, ISD::VOR); }
509 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
Nate Begemane21ea612005-11-18 07:42:56 +0000510 void visitShl(User &I) { visitShift(I, ISD::SHL); }
511 void visitShr(User &I) {
512 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner1c08c712005-01-07 07:47:53 +0000513 }
514
515 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
516 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
517 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
518 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
519 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
520 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
521 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
522
523 void visitGetElementPtr(User &I);
524 void visitCast(User &I);
525 void visitSelect(User &I);
526 //
527
528 void visitMalloc(MallocInst &I);
529 void visitFree(FreeInst &I);
530 void visitAlloca(AllocaInst &I);
531 void visitLoad(LoadInst &I);
532 void visitStore(StoreInst &I);
533 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
534 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000535 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000536 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000537
Chris Lattner1c08c712005-01-07 07:47:53 +0000538 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000539 void visitVAArg(VAArgInst &I);
540 void visitVAEnd(CallInst &I);
541 void visitVACopy(CallInst &I);
Chris Lattner39ae3622005-01-09 00:00:49 +0000542 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner1c08c712005-01-07 07:47:53 +0000543
Chris Lattner7041ee32005-01-11 05:56:49 +0000544 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000545
546 void visitUserOp1(Instruction &I) {
547 assert(0 && "UserOp1 should not exist at instruction selection time!");
548 abort();
549 }
550 void visitUserOp2(Instruction &I) {
551 assert(0 && "UserOp2 should not exist at instruction selection time!");
552 abort();
553 }
554};
555} // end namespace llvm
556
557void SelectionDAGLowering::visitRet(ReturnInst &I) {
558 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000559 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000560 return;
561 }
Nate Begemanee625572006-01-27 21:09:22 +0000562 std::vector<SDOperand> NewValues;
563 NewValues.push_back(getRoot());
564 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
565 SDOperand RetOp = getValue(I.getOperand(i));
566
567 // If this is an integer return value, we need to promote it ourselves to
568 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
569 // than sign/zero.
570 if (MVT::isInteger(RetOp.getValueType()) &&
571 RetOp.getValueType() < MVT::i64) {
572 MVT::ValueType TmpVT;
573 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
574 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
575 else
576 TmpVT = MVT::i32;
Chris Lattner1c08c712005-01-07 07:47:53 +0000577
Nate Begemanee625572006-01-27 21:09:22 +0000578 if (I.getOperand(i)->getType()->isSigned())
579 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
580 else
581 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
582 }
583 NewValues.push_back(RetOp);
Chris Lattner1c08c712005-01-07 07:47:53 +0000584 }
Nate Begemanee625572006-01-27 21:09:22 +0000585 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner1c08c712005-01-07 07:47:53 +0000586}
587
588void SelectionDAGLowering::visitBr(BranchInst &I) {
589 // Update machine-CFG edges.
590 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000591
592 // Figure out which block is immediately after the current one.
593 MachineBasicBlock *NextBlock = 0;
594 MachineFunction::iterator BBI = CurMBB;
595 if (++BBI != CurMBB->getParent()->end())
596 NextBlock = BBI;
597
598 if (I.isUnconditional()) {
599 // If this is not a fall-through branch, emit the branch.
600 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000601 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000602 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000603 } else {
604 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000605
606 SDOperand Cond = getValue(I.getCondition());
Chris Lattner1c08c712005-01-07 07:47:53 +0000607 if (Succ1MBB == NextBlock) {
608 // If the condition is false, fall through. This means we should branch
609 // if the condition is true to Succ #0.
Chris Lattnera651cf62005-01-17 19:43:36 +0000610 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000611 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000612 } else if (Succ0MBB == NextBlock) {
613 // If the condition is true, fall through. This means we should branch if
614 // the condition is false to Succ #1. Invert the condition first.
615 SDOperand True = DAG.getConstant(1, Cond.getValueType());
616 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattnera651cf62005-01-17 19:43:36 +0000617 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000618 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000619 } else {
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000620 std::vector<SDOperand> Ops;
621 Ops.push_back(getRoot());
Evan Cheng298ebf22006-02-16 08:27:56 +0000622 // If the false case is the current basic block, then this is a self
623 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
624 // adds an extra instruction in the loop. Instead, invert the
625 // condition and emit "Loop: ... br!cond Loop; br Out.
626 if (CurMBB == Succ1MBB) {
627 std::swap(Succ0MBB, Succ1MBB);
628 SDOperand True = DAG.getConstant(1, Cond.getValueType());
629 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
630 }
Chris Lattnere7ccd4a2005-04-09 03:30:29 +0000631 Ops.push_back(Cond);
632 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
633 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
634 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +0000635 }
636 }
637}
638
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000639void SelectionDAGLowering::visitSub(User &I) {
640 // -0.0 - X --> fneg
Chris Lattner01b3d732005-09-28 22:28:18 +0000641 if (I.getType()->isFloatingPoint()) {
642 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
643 if (CFP->isExactlyValue(-0.0)) {
644 SDOperand Op2 = getValue(I.getOperand(1));
645 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
646 return;
647 }
Chris Lattner01b3d732005-09-28 22:28:18 +0000648 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000649 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000650}
651
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000652void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
653 unsigned VecOp) {
654 const Type *Ty = I.getType();
Chris Lattner1c08c712005-01-07 07:47:53 +0000655 SDOperand Op1 = getValue(I.getOperand(0));
656 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner2c49f272005-01-19 22:31:21 +0000657
Chris Lattnerb67eb912005-11-19 18:40:42 +0000658 if (Ty->isIntegral()) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000659 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
660 } else if (Ty->isFloatingPoint()) {
661 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
662 } else {
663 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000664 unsigned NumElements = PTy->getNumElements();
665 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000666 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000667
668 // Immediately scalarize packed types containing only one element, so that
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000669 // the Legalize pass does not have to deal with them. Similarly, if the
670 // abstract vector is going to turn into one that the target natively
671 // supports, generate that type now so that Legalize doesn't have to deal
672 // with that either. These steps ensure that Legalize only has to handle
673 // vector types in its Expand case.
674 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman4ef3b812005-11-22 01:29:36 +0000675 if (NumElements == 1) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000676 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Evan Cheng860771d2006-03-01 01:09:54 +0000677 } else if (TVT != MVT::Other &&
678 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(Opc, TVT)) {
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000679 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000680 } else {
681 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
682 SDOperand Typ = DAG.getValueType(PVT);
Evan Cheng860771d2006-03-01 01:09:54 +0000683 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Num, Typ, Op1, Op2));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000684 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000685 }
Nate Begemane21ea612005-11-18 07:42:56 +0000686}
Chris Lattner2c49f272005-01-19 22:31:21 +0000687
Nate Begemane21ea612005-11-18 07:42:56 +0000688void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
689 SDOperand Op1 = getValue(I.getOperand(0));
690 SDOperand Op2 = getValue(I.getOperand(1));
691
692 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
693
Chris Lattner1c08c712005-01-07 07:47:53 +0000694 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
695}
696
697void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
698 ISD::CondCode UnsignedOpcode) {
699 SDOperand Op1 = getValue(I.getOperand(0));
700 SDOperand Op2 = getValue(I.getOperand(1));
701 ISD::CondCode Opcode = SignedOpcode;
702 if (I.getOperand(0)->getType()->isUnsigned())
703 Opcode = UnsignedOpcode;
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000704 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner1c08c712005-01-07 07:47:53 +0000705}
706
707void SelectionDAGLowering::visitSelect(User &I) {
708 SDOperand Cond = getValue(I.getOperand(0));
709 SDOperand TrueVal = getValue(I.getOperand(1));
710 SDOperand FalseVal = getValue(I.getOperand(2));
711 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
712 TrueVal, FalseVal));
713}
714
715void SelectionDAGLowering::visitCast(User &I) {
716 SDOperand N = getValue(I.getOperand(0));
717 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
718 MVT::ValueType DestTy = TLI.getValueType(I.getType());
719
720 if (N.getValueType() == DestTy) {
721 setValue(&I, N); // noop cast.
Chris Lattneref311aa2005-05-09 22:17:13 +0000722 } else if (DestTy == MVT::i1) {
723 // Cast to bool is a comparison against zero, not truncation to zero.
724 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
725 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattner7cf7e3f2005-08-09 20:20:18 +0000726 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000727 } else if (isInteger(SrcTy)) {
728 if (isInteger(DestTy)) { // Int -> Int cast
729 if (DestTy < SrcTy) // Truncating cast?
730 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
731 else if (I.getOperand(0)->getType()->isSigned())
732 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
733 else
734 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
735 } else { // Int -> FP cast
736 if (I.getOperand(0)->getType()->isSigned())
737 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
738 else
739 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
740 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000741 } else {
Chris Lattnerae0aacb2005-01-08 08:08:56 +0000742 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
743 if (isFloatingPoint(DestTy)) { // FP -> FP cast
744 if (DestTy < SrcTy) // Rounding cast?
745 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
746 else
747 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
748 } else { // FP -> Int cast.
749 if (I.getType()->isSigned())
750 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
751 else
752 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
753 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000754 }
755}
756
757void SelectionDAGLowering::visitGetElementPtr(User &I) {
758 SDOperand N = getValue(I.getOperand(0));
759 const Type *Ty = I.getOperand(0)->getType();
760 const Type *UIntPtrTy = TD.getIntPtrType();
761
762 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
763 OI != E; ++OI) {
764 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +0000765 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000766 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
767 if (Field) {
768 // N = N + Offset
769 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
770 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000771 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +0000772 }
773 Ty = StTy->getElementType(Field);
774 } else {
775 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +0000776
Chris Lattner7c0104b2005-11-09 04:45:33 +0000777 // If this is a constant subscript, handle it quickly.
778 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
779 if (CI->getRawValue() == 0) continue;
Chris Lattner7cc47772005-01-07 21:56:57 +0000780
Chris Lattner7c0104b2005-11-09 04:45:33 +0000781 uint64_t Offs;
782 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
783 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
784 else
785 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
786 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
787 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +0000788 }
Chris Lattner7c0104b2005-11-09 04:45:33 +0000789
790 // N = N + Idx * ElementSize;
791 uint64_t ElementSize = TD.getTypeSize(Ty);
792 SDOperand IdxN = getValue(Idx);
793
794 // If the index is smaller or larger than intptr_t, truncate or extend
795 // it.
796 if (IdxN.getValueType() < N.getValueType()) {
797 if (Idx->getType()->isSigned())
798 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
799 else
800 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
801 } else if (IdxN.getValueType() > N.getValueType())
802 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
803
804 // If this is a multiply by a power of two, turn it into a shl
805 // immediately. This is a very common case.
806 if (isPowerOf2_64(ElementSize)) {
807 unsigned Amt = Log2_64(ElementSize);
808 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +0000809 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +0000810 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
811 continue;
812 }
813
814 SDOperand Scale = getIntPtrConstant(ElementSize);
815 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
816 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +0000817 }
818 }
819 setValue(&I, N);
820}
821
822void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
823 // If this is a fixed sized alloca in the entry block of the function,
824 // allocate it statically on the stack.
825 if (FuncInfo.StaticAllocaMap.count(&I))
826 return; // getValue will auto-populate this.
827
828 const Type *Ty = I.getAllocatedType();
829 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000830 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
831 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +0000832
833 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +0000834 MVT::ValueType IntPtr = TLI.getPointerTy();
835 if (IntPtr < AllocSize.getValueType())
836 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
837 else if (IntPtr > AllocSize.getValueType())
838 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +0000839
Chris Lattner68cd65e2005-01-22 23:04:37 +0000840 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +0000841 getIntPtrConstant(TySize));
842
843 // Handle alignment. If the requested alignment is less than or equal to the
844 // stack alignment, ignore it and round the size of the allocation up to the
845 // stack alignment size. If the size is greater than the stack alignment, we
846 // note this in the DYNAMIC_STACKALLOC node.
847 unsigned StackAlign =
848 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
849 if (Align <= StackAlign) {
850 Align = 0;
851 // Add SA-1 to the size.
852 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
853 getIntPtrConstant(StackAlign-1));
854 // Mask out the low bits for alignment purposes.
855 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
856 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
857 }
858
Chris Lattneradf6c2a2005-05-14 07:29:57 +0000859 std::vector<MVT::ValueType> VTs;
860 VTs.push_back(AllocSize.getValueType());
861 VTs.push_back(MVT::Other);
862 std::vector<SDOperand> Ops;
863 Ops.push_back(getRoot());
864 Ops.push_back(AllocSize);
865 Ops.push_back(getIntPtrConstant(Align));
866 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner1c08c712005-01-07 07:47:53 +0000867 DAG.setRoot(setValue(&I, DSA).getValue(1));
868
869 // Inform the Frame Information that we have just allocated a variable-sized
870 // object.
871 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
872}
873
Chris Lattner36ce6912005-11-29 06:21:05 +0000874/// getStringValue - Turn an LLVM constant pointer that eventually points to a
875/// global into a string value. Return an empty string if we can't do it.
876///
Evan Cheng74d0aa92006-02-15 21:59:04 +0000877static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
878 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
879 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
880 if (Init->isString()) {
881 std::string Result = Init->getAsString();
882 if (Offset < Result.size()) {
883 // If we are pointing INTO The string, erase the beginning...
884 Result.erase(Result.begin(), Result.begin()+Offset);
885 return Result;
Chris Lattner36ce6912005-11-29 06:21:05 +0000886 }
887 }
888 }
889 return "";
890}
Chris Lattner1c08c712005-01-07 07:47:53 +0000891
892void SelectionDAGLowering::visitLoad(LoadInst &I) {
893 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +0000894
Chris Lattnerd3948112005-01-17 22:19:26 +0000895 SDOperand Root;
896 if (I.isVolatile())
897 Root = getRoot();
898 else {
899 // Do not serialize non-volatile loads against each other.
900 Root = DAG.getRoot();
901 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000902
903 const Type *Ty = I.getType();
904 SDOperand L;
905
Nate Begeman8cfa57b2005-12-06 06:18:55 +0000906 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +0000907 unsigned NumElements = PTy->getNumElements();
908 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000909 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman4ef3b812005-11-22 01:29:36 +0000910
911 // Immediately scalarize packed types containing only one element, so that
912 // the Legalize pass does not have to deal with them.
913 if (NumElements == 1) {
914 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Evan Cheng860771d2006-03-01 01:09:54 +0000915 } else if (TVT != MVT::Other &&
916 TLI.isTypeLegal(TVT) && TLI.isOperationLegal(ISD::LOAD, TVT)) {
Nate Begemanf43a3ca2005-11-30 08:22:07 +0000917 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman4ef3b812005-11-22 01:29:36 +0000918 } else {
919 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
920 DAG.getSrcValue(I.getOperand(0)));
921 }
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000922 } else {
923 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
924 DAG.getSrcValue(I.getOperand(0)));
925 }
Chris Lattnerd3948112005-01-17 22:19:26 +0000926 setValue(&I, L);
927
928 if (I.isVolatile())
929 DAG.setRoot(L.getValue(1));
930 else
931 PendingLoads.push_back(L.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +0000932}
933
934
935void SelectionDAGLowering::visitStore(StoreInst &I) {
936 Value *SrcV = I.getOperand(0);
937 SDOperand Src = getValue(SrcV);
938 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattner369e6db2005-05-09 04:08:33 +0000939 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth06ef8842005-06-29 18:54:02 +0000940 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +0000941}
942
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000943/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
944/// we want to emit this as a call to a named external function, return the name
945/// otherwise lower it and return null.
946const char *
947SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
948 switch (Intrinsic) {
949 case Intrinsic::vastart: visitVAStart(I); return 0;
950 case Intrinsic::vaend: visitVAEnd(I); return 0;
951 case Intrinsic::vacopy: visitVACopy(I); return 0;
952 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
953 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
954 case Intrinsic::setjmp:
955 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
956 break;
957 case Intrinsic::longjmp:
958 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
959 break;
Chris Lattner03dd4652006-03-03 00:00:25 +0000960 case Intrinsic::memcpy_i32:
961 case Intrinsic::memcpy_i64:
962 visitMemIntrinsic(I, ISD::MEMCPY);
963 return 0;
964 case Intrinsic::memset_i32:
965 case Intrinsic::memset_i64:
966 visitMemIntrinsic(I, ISD::MEMSET);
967 return 0;
968 case Intrinsic::memmove_i32:
969 case Intrinsic::memmove_i64:
970 visitMemIntrinsic(I, ISD::MEMMOVE);
971 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000972
Chris Lattner86cb6432005-12-13 17:40:33 +0000973 case Intrinsic::dbg_stoppoint: {
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +0000974 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
975 return "llvm_debugger_stop";
Chris Lattner36ce6912005-11-29 06:21:05 +0000976
Jim Laskeyce72b172006-02-11 01:01:30 +0000977 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
978 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
979 std::vector<SDOperand> Ops;
Chris Lattner36ce6912005-11-29 06:21:05 +0000980
Jim Laskeyce72b172006-02-11 01:01:30 +0000981 // Input Chain
982 Ops.push_back(getRoot());
983
984 // line number
985 Ops.push_back(getValue(I.getOperand(2)));
986
987 // column
988 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner36ce6912005-11-29 06:21:05 +0000989
Jim Laskeyd96185a2006-02-13 12:50:39 +0000990 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskeyce72b172006-02-11 01:01:30 +0000991 assert(DD && "Not a debug information descriptor");
992 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
993 assert(CompileUnit && "Not a compile unit");
994 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
995 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
996
997 if (Ops.size() == 5) // Found filename/workingdir.
998 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner86cb6432005-12-13 17:40:33 +0000999 }
1000
Chris Lattnerd67b3a82005-12-03 18:50:48 +00001001 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001002 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00001003 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001004 case Intrinsic::dbg_region_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001005 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1006 return "llvm_dbg_region_start";
1007 if (I.getType() != Type::VoidTy)
1008 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1009 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001010 case Intrinsic::dbg_region_end:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001011 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1012 return "llvm_dbg_region_end";
1013 if (I.getType() != Type::VoidTy)
1014 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1015 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001016 case Intrinsic::dbg_func_start:
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00001017 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1018 return "llvm_dbg_subprogram";
1019 if (I.getType() != Type::VoidTy)
1020 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1021 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001022 case Intrinsic::dbg_declare:
1023 if (I.getType() != Type::VoidTy)
1024 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1025 return 0;
1026
Reid Spencer0b118202006-01-16 21:12:35 +00001027 case Intrinsic::isunordered_f32:
1028 case Intrinsic::isunordered_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001029 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1030 getValue(I.getOperand(2)), ISD::SETUO));
1031 return 0;
1032
Reid Spencer0b118202006-01-16 21:12:35 +00001033 case Intrinsic::sqrt_f32:
1034 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001035 setValue(&I, DAG.getNode(ISD::FSQRT,
1036 getValue(I.getOperand(1)).getValueType(),
1037 getValue(I.getOperand(1))));
1038 return 0;
1039 case Intrinsic::pcmarker: {
1040 SDOperand Tmp = getValue(I.getOperand(1));
1041 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1042 return 0;
1043 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001044 case Intrinsic::readcyclecounter: {
1045 std::vector<MVT::ValueType> VTs;
1046 VTs.push_back(MVT::i64);
1047 VTs.push_back(MVT::Other);
1048 std::vector<SDOperand> Ops;
1049 Ops.push_back(getRoot());
1050 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1051 setValue(&I, Tmp);
1052 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00001053 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00001054 }
Nate Begemand88fc032006-01-14 03:14:10 +00001055 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00001056 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00001057 case Intrinsic::bswap_i64:
1058 setValue(&I, DAG.getNode(ISD::BSWAP,
1059 getValue(I.getOperand(1)).getValueType(),
1060 getValue(I.getOperand(1))));
1061 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001062 case Intrinsic::cttz_i8:
1063 case Intrinsic::cttz_i16:
1064 case Intrinsic::cttz_i32:
1065 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001066 setValue(&I, DAG.getNode(ISD::CTTZ,
1067 getValue(I.getOperand(1)).getValueType(),
1068 getValue(I.getOperand(1))));
1069 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001070 case Intrinsic::ctlz_i8:
1071 case Intrinsic::ctlz_i16:
1072 case Intrinsic::ctlz_i32:
1073 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001074 setValue(&I, DAG.getNode(ISD::CTLZ,
1075 getValue(I.getOperand(1)).getValueType(),
1076 getValue(I.getOperand(1))));
1077 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00001078 case Intrinsic::ctpop_i8:
1079 case Intrinsic::ctpop_i16:
1080 case Intrinsic::ctpop_i32:
1081 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001082 setValue(&I, DAG.getNode(ISD::CTPOP,
1083 getValue(I.getOperand(1)).getValueType(),
1084 getValue(I.getOperand(1))));
1085 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00001086 case Intrinsic::stacksave: {
1087 std::vector<MVT::ValueType> VTs;
1088 VTs.push_back(TLI.getPointerTy());
1089 VTs.push_back(MVT::Other);
1090 std::vector<SDOperand> Ops;
1091 Ops.push_back(getRoot());
1092 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1093 setValue(&I, Tmp);
1094 DAG.setRoot(Tmp.getValue(1));
1095 return 0;
1096 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00001097 case Intrinsic::stackrestore: {
1098 SDOperand Tmp = getValue(I.getOperand(1));
1099 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00001100 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00001101 }
Chris Lattnerac22c832005-12-12 22:51:16 +00001102 case Intrinsic::prefetch:
1103 // FIXME: Currently discarding prefetches.
1104 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001105 default:
1106 std::cerr << I;
1107 assert(0 && "This intrinsic is not implemented yet!");
1108 return 0;
1109 }
1110}
1111
1112
Chris Lattner1c08c712005-01-07 07:47:53 +00001113void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00001114 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001115 if (Function *F = I.getCalledFunction()) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001116 if (F->isExternal())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001117 if (unsigned IID = F->getIntrinsicID()) {
1118 RenameFn = visitIntrinsicCall(I, IID);
1119 if (!RenameFn)
1120 return;
1121 } else { // Not an LLVM intrinsic.
1122 const std::string &Name = F->getName();
1123 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00001124 if (I.getNumOperands() == 2 && // Basic sanity checks.
1125 I.getOperand(1)->getType()->isFloatingPoint() &&
1126 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001127 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00001128 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1129 return;
1130 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001131 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001132 if (I.getNumOperands() == 2 && // Basic sanity checks.
1133 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001134 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001135 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001136 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1137 return;
1138 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001139 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001140 if (I.getNumOperands() == 2 && // Basic sanity checks.
1141 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00001142 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001143 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00001144 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1145 return;
1146 }
1147 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00001148 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001149 } else if (isa<InlineAsm>(I.getOperand(0))) {
1150 visitInlineAsm(I);
1151 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001152 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001153
Chris Lattner64e14b12005-01-08 22:48:57 +00001154 SDOperand Callee;
1155 if (!RenameFn)
1156 Callee = getValue(I.getOperand(0));
1157 else
1158 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner1c08c712005-01-07 07:47:53 +00001159 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001160 Args.reserve(I.getNumOperands());
Chris Lattner1c08c712005-01-07 07:47:53 +00001161 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1162 Value *Arg = I.getOperand(i);
1163 SDOperand ArgNode = getValue(Arg);
1164 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1165 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00001166
Nate Begeman8e21e712005-03-26 01:29:23 +00001167 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1168 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukmanedf128a2005-04-21 22:36:52 +00001169
Chris Lattnercf5734d2005-01-08 19:26:18 +00001170 std::pair<SDOperand,SDOperand> Result =
Chris Lattner9092fa32005-05-12 19:56:57 +00001171 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattneradf6a962005-05-13 18:50:42 +00001172 I.isTailCall(), Callee, Args, DAG);
Chris Lattner1c08c712005-01-07 07:47:53 +00001173 if (I.getType() != Type::VoidTy)
Chris Lattnercf5734d2005-01-08 19:26:18 +00001174 setValue(&I, Result.first);
1175 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001176}
1177
Chris Lattner864635a2006-02-22 22:37:12 +00001178SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001179 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00001180 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1181 Chain = Val.getValue(1);
1182 Flag = Val.getValue(2);
1183
1184 // If the result was expanded, copy from the top part.
1185 if (Regs.size() > 1) {
1186 assert(Regs.size() == 2 &&
1187 "Cannot expand to more than 2 elts yet!");
1188 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1189 Chain = Val.getValue(1);
1190 Flag = Val.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00001191 if (DAG.getTargetLoweringInfo().isLittleEndian())
1192 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1193 else
1194 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00001195 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00001196
Chris Lattner864635a2006-02-22 22:37:12 +00001197 // Otherwise, if the return value was promoted, truncate it to the
1198 // appropriate type.
1199 if (RegVT == ValueVT)
1200 return Val;
1201
1202 if (MVT::isInteger(RegVT))
1203 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1204 else
1205 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1206}
1207
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001208/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1209/// specified value into the registers specified by this object. This uses
1210/// Chain/Flag as the input and updates them for the output Chain/Flag.
1211void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001212 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001213 if (Regs.size() == 1) {
1214 // If there is a single register and the types differ, this must be
1215 // a promotion.
1216 if (RegVT != ValueVT) {
1217 if (MVT::isInteger(RegVT))
1218 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1219 else
1220 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1221 }
1222 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1223 Flag = Chain.getValue(1);
1224 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00001225 std::vector<unsigned> R(Regs);
1226 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1227 std::reverse(R.begin(), R.end());
1228
1229 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001230 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1231 DAG.getConstant(i, MVT::i32));
Chris Lattner9f6637d2006-02-23 20:06:57 +00001232 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001233 Flag = Chain.getValue(1);
1234 }
1235 }
1236}
Chris Lattner864635a2006-02-22 22:37:12 +00001237
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001238/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1239/// operand list. This adds the code marker and includes the number of
1240/// values added into it.
1241void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00001242 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001243 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1244 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1245 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1246}
Chris Lattner864635a2006-02-22 22:37:12 +00001247
1248/// isAllocatableRegister - If the specified register is safe to allocate,
1249/// i.e. it isn't a stack pointer or some other special register, return the
1250/// register class for the register. Otherwise, return null.
1251static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001252isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1253 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1254 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1255 E = MRI->regclass_end(); RCI != E; ++RCI) {
1256 const TargetRegisterClass *RC = *RCI;
1257 // If none of the the value types for this register class are valid, we
1258 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1259 bool isLegal = false;
1260 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1261 I != E; ++I) {
1262 if (TLI.isTypeLegal(*I)) {
1263 isLegal = true;
1264 break;
1265 }
1266 }
1267
1268 if (!isLegal) continue;
1269
Chris Lattner864635a2006-02-22 22:37:12 +00001270 // NOTE: This isn't ideal. In particular, this might allocate the
1271 // frame pointer in functions that need it (due to them not being taken
1272 // out of allocation, because a variable sized allocation hasn't been seen
1273 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001274 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1275 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner864635a2006-02-22 22:37:12 +00001276 if (*I == Reg)
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001277 return RC;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001278 }
1279 return 0;
Chris Lattner864635a2006-02-22 22:37:12 +00001280}
1281
1282RegsForValue SelectionDAGLowering::
1283GetRegistersForValue(const std::string &ConstrCode,
1284 MVT::ValueType VT, bool isOutReg, bool isInReg,
1285 std::set<unsigned> &OutputRegs,
1286 std::set<unsigned> &InputRegs) {
1287 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1288 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1289 std::vector<unsigned> Regs;
1290
1291 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1292 MVT::ValueType RegVT;
1293 MVT::ValueType ValueVT = VT;
1294
1295 if (PhysReg.first) {
1296 if (VT == MVT::Other)
1297 ValueVT = *PhysReg.second->vt_begin();
1298 RegVT = VT;
1299
1300 // This is a explicit reference to a physical register.
1301 Regs.push_back(PhysReg.first);
1302
1303 // If this is an expanded reference, add the rest of the regs to Regs.
1304 if (NumRegs != 1) {
1305 RegVT = *PhysReg.second->vt_begin();
1306 TargetRegisterClass::iterator I = PhysReg.second->begin();
1307 TargetRegisterClass::iterator E = PhysReg.second->end();
1308 for (; *I != PhysReg.first; ++I)
1309 assert(I != E && "Didn't find reg!");
1310
1311 // Already added the first reg.
1312 --NumRegs; ++I;
1313 for (; NumRegs; --NumRegs, ++I) {
1314 assert(I != E && "Ran out of registers to allocate!");
1315 Regs.push_back(*I);
1316 }
1317 }
1318 return RegsForValue(Regs, RegVT, ValueVT);
1319 }
1320
1321 // This is a reference to a register class. Allocate NumRegs consecutive,
1322 // available, registers from the class.
1323 std::vector<unsigned> RegClassRegs =
1324 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1325
1326 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1327 MachineFunction &MF = *CurMBB->getParent();
1328 unsigned NumAllocated = 0;
1329 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1330 unsigned Reg = RegClassRegs[i];
1331 // See if this register is available.
1332 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1333 (isInReg && InputRegs.count(Reg))) { // Already used.
1334 // Make sure we find consecutive registers.
1335 NumAllocated = 0;
1336 continue;
1337 }
1338
1339 // Check to see if this register is allocatable (i.e. don't give out the
1340 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00001341 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00001342 if (!RC) {
1343 // Make sure we find consecutive registers.
1344 NumAllocated = 0;
1345 continue;
1346 }
1347
1348 // Okay, this register is good, we can use it.
1349 ++NumAllocated;
1350
1351 // If we allocated enough consecutive
1352 if (NumAllocated == NumRegs) {
1353 unsigned RegStart = (i-NumAllocated)+1;
1354 unsigned RegEnd = i+1;
1355 // Mark all of the allocated registers used.
1356 for (unsigned i = RegStart; i != RegEnd; ++i) {
1357 unsigned Reg = RegClassRegs[i];
1358 Regs.push_back(Reg);
1359 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1360 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1361 }
1362
1363 return RegsForValue(Regs, *RC->vt_begin(), VT);
1364 }
1365 }
1366
1367 // Otherwise, we couldn't allocate enough registers for this.
1368 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00001369}
1370
Chris Lattner864635a2006-02-22 22:37:12 +00001371
Chris Lattnerce7518c2006-01-26 22:24:51 +00001372/// visitInlineAsm - Handle a call to an InlineAsm object.
1373///
1374void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1375 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1376
1377 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1378 MVT::Other);
1379
1380 // Note, we treat inline asms both with and without side-effects as the same.
1381 // If an inline asm doesn't have side effects and doesn't access memory, we
1382 // could not choose to not chain it.
1383 bool hasSideEffects = IA->hasSideEffects();
1384
Chris Lattner2cc2f662006-02-01 01:28:23 +00001385 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001386 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00001387
1388 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1389 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1390 /// if it is a def of that register.
1391 std::vector<SDOperand> AsmNodeOperands;
1392 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1393 AsmNodeOperands.push_back(AsmStr);
1394
1395 SDOperand Chain = getRoot();
1396 SDOperand Flag;
1397
Chris Lattner4e4b5762006-02-01 18:59:47 +00001398 // We fully assign registers here at isel time. This is not optimal, but
1399 // should work. For register classes that correspond to LLVM classes, we
1400 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1401 // over the constraints, collecting fixed registers that we know we can't use.
1402 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001403 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001404 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1405 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1406 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner2223aea2006-02-02 00:25:23 +00001407
Chris Lattner1efa40f2006-02-22 00:56:39 +00001408 MVT::ValueType OpVT;
1409
1410 // Compute the value type for each operand and add it to ConstraintVTs.
1411 switch (Constraints[i].Type) {
1412 case InlineAsm::isOutput:
1413 if (!Constraints[i].isIndirectOutput) {
1414 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1415 OpVT = TLI.getValueType(I.getType());
1416 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001417 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00001418 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1419 OpNum++; // Consumes a call operand.
1420 }
1421 break;
1422 case InlineAsm::isInput:
1423 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1424 OpNum++; // Consumes a call operand.
1425 break;
1426 case InlineAsm::isClobber:
1427 OpVT = MVT::Other;
1428 break;
1429 }
1430
1431 ConstraintVTs.push_back(OpVT);
1432
Chris Lattner864635a2006-02-22 22:37:12 +00001433 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1434 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00001435
Chris Lattner864635a2006-02-22 22:37:12 +00001436 // Build a list of regs that this operand uses. This always has a single
1437 // element for promoted/expanded operands.
1438 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1439 false, false,
1440 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00001441
1442 switch (Constraints[i].Type) {
1443 case InlineAsm::isOutput:
1444 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001445 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001446 // If this is an early-clobber output, it cannot be assigned to the same
1447 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00001448 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00001449 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001450 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001451 case InlineAsm::isInput:
1452 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00001453 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00001454 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001455 case InlineAsm::isClobber:
1456 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00001457 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1458 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00001459 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00001460 }
1461 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00001462
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001463 // Loop over all of the inputs, copying the operand values into the
1464 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00001465 RegsForValue RetValRegs;
1466 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00001467 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00001468
Chris Lattner6656dd12006-01-31 02:03:41 +00001469 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00001470 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1471 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner1efa40f2006-02-22 00:56:39 +00001472
Chris Lattner2cc2f662006-02-01 01:28:23 +00001473 switch (Constraints[i].Type) {
1474 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00001475 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1476 if (ConstraintCode.size() == 1) // not a physreg name.
1477 CTy = TLI.getConstraintType(ConstraintCode[0]);
1478
1479 if (CTy == TargetLowering::C_Memory) {
1480 // Memory output.
1481 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1482
1483 // Check that the operand (the address to store to) isn't a float.
1484 if (!MVT::isInteger(InOperandVal.getValueType()))
1485 assert(0 && "MATCH FAIL!");
1486
1487 if (!Constraints[i].isIndirectOutput)
1488 assert(0 && "MATCH FAIL!");
1489
1490 OpNum++; // Consumes a call operand.
1491
1492 // Extend/truncate to the right pointer type if needed.
1493 MVT::ValueType PtrType = TLI.getPointerTy();
1494 if (InOperandVal.getValueType() < PtrType)
1495 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1496 else if (InOperandVal.getValueType() > PtrType)
1497 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1498
1499 // Add information to the INLINEASM node to know about this output.
1500 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1501 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1502 AsmNodeOperands.push_back(InOperandVal);
1503 break;
1504 }
1505
1506 // Otherwise, this is a register output.
1507 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1508
Chris Lattner864635a2006-02-22 22:37:12 +00001509 // If this is an early-clobber output, or if there is an input
1510 // constraint that matches this, we need to reserve the input register
1511 // so no other inputs allocate to it.
1512 bool UsesInputRegister = false;
1513 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1514 UsesInputRegister = true;
1515
1516 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00001517 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00001518 RegsForValue Regs =
1519 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1520 true, UsesInputRegister,
1521 OutputRegs, InputRegs);
1522 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner1efa40f2006-02-22 00:56:39 +00001523
Chris Lattner2cc2f662006-02-01 01:28:23 +00001524 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00001525 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00001526 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00001527 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00001528 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00001529 } else {
Chris Lattner22873462006-02-27 23:45:39 +00001530 IndirectStoresToEmit.push_back(std::make_pair(Regs,
1531 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00001532 OpNum++; // Consumes a call operand.
1533 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001534
1535 // Add information to the INLINEASM node to know that this register is
1536 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001537 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001538 break;
1539 }
1540 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00001541 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00001542 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00001543
Chris Lattner2223aea2006-02-02 00:25:23 +00001544 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1545 // If this is required to match an output register we have already set,
1546 // just use its register.
1547 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00001548
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001549 // Scan until we find the definition we already emitted of this operand.
1550 // When we find it, create a RegsForValue operand.
1551 unsigned CurOp = 2; // The first operand.
1552 for (; OperandNo; --OperandNo) {
1553 // Advance to the next operand.
1554 unsigned NumOps =
1555 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1556 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1557 "Skipped past definitions?");
1558 CurOp += (NumOps>>3)+1;
1559 }
1560
1561 unsigned NumOps =
1562 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1563 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1564 "Skipped past definitions?");
1565
1566 // Add NumOps>>3 registers to MatchedRegs.
1567 RegsForValue MatchedRegs;
1568 MatchedRegs.ValueVT = InOperandVal.getValueType();
1569 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1570 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1571 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1572 MatchedRegs.Regs.push_back(Reg);
1573 }
1574
1575 // Use the produced MatchedRegs object to
1576 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1577 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001578 break;
Chris Lattner2223aea2006-02-02 00:25:23 +00001579 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00001580
1581 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1582 if (ConstraintCode.size() == 1) // not a physreg name.
1583 CTy = TLI.getConstraintType(ConstraintCode[0]);
1584
1585 if (CTy == TargetLowering::C_Other) {
1586 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1587 assert(0 && "MATCH FAIL!");
1588
1589 // Add information to the INLINEASM node to know about this input.
1590 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1591 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1592 AsmNodeOperands.push_back(InOperandVal);
1593 break;
1594 } else if (CTy == TargetLowering::C_Memory) {
1595 // Memory input.
1596
1597 // Check that the operand isn't a float.
1598 if (!MVT::isInteger(InOperandVal.getValueType()))
1599 assert(0 && "MATCH FAIL!");
1600
1601 // Extend/truncate to the right pointer type if needed.
1602 MVT::ValueType PtrType = TLI.getPointerTy();
1603 if (InOperandVal.getValueType() < PtrType)
1604 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1605 else if (InOperandVal.getValueType() > PtrType)
1606 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1607
1608 // Add information to the INLINEASM node to know about this input.
1609 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1610 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1611 AsmNodeOperands.push_back(InOperandVal);
1612 break;
1613 }
1614
1615 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1616
1617 // Copy the input into the appropriate registers.
1618 RegsForValue InRegs =
1619 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1620 false, true, OutputRegs, InputRegs);
1621 // FIXME: should be match fail.
1622 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1623
1624 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1625
1626 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001627 break;
1628 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001629 case InlineAsm::isClobber: {
1630 RegsForValue ClobberedRegs =
1631 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1632 OutputRegs, InputRegs);
1633 // Add the clobbered value to the operand list, so that the register
1634 // allocator is aware that the physreg got clobbered.
1635 if (!ClobberedRegs.Regs.empty())
1636 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00001637 break;
1638 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00001639 }
Chris Lattner6656dd12006-01-31 02:03:41 +00001640 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00001641
1642 // Finish up input operands.
1643 AsmNodeOperands[0] = Chain;
1644 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1645
1646 std::vector<MVT::ValueType> VTs;
1647 VTs.push_back(MVT::Other);
1648 VTs.push_back(MVT::Flag);
1649 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1650 Flag = Chain.getValue(1);
1651
Chris Lattner6656dd12006-01-31 02:03:41 +00001652 // If this asm returns a register value, copy the result from that register
1653 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00001654 if (!RetValRegs.Regs.empty())
1655 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00001656
Chris Lattner6656dd12006-01-31 02:03:41 +00001657 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1658
1659 // Process indirect outputs, first output all of the flagged copies out of
1660 // physregs.
1661 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00001662 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00001663 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00001664 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1665 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00001666 }
1667
1668 // Emit the non-flagged stores from the physregs.
1669 std::vector<SDOperand> OutChains;
1670 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1671 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1672 StoresToEmit[i].first,
1673 getValue(StoresToEmit[i].second),
1674 DAG.getSrcValue(StoresToEmit[i].second)));
1675 if (!OutChains.empty())
1676 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattnerce7518c2006-01-26 22:24:51 +00001677 DAG.setRoot(Chain);
1678}
1679
1680
Chris Lattner1c08c712005-01-07 07:47:53 +00001681void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1682 SDOperand Src = getValue(I.getOperand(0));
1683
1684 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00001685
1686 if (IntPtr < Src.getValueType())
1687 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1688 else if (IntPtr > Src.getValueType())
1689 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00001690
1691 // Scale the source by the type size.
1692 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1693 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1694 Src, getIntPtrConstant(ElementSize));
1695
1696 std::vector<std::pair<SDOperand, const Type*> > Args;
1697 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattnercf5734d2005-01-08 19:26:18 +00001698
1699 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001700 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001701 DAG.getExternalSymbol("malloc", IntPtr),
1702 Args, DAG);
1703 setValue(&I, Result.first); // Pointers always fit in registers
1704 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001705}
1706
1707void SelectionDAGLowering::visitFree(FreeInst &I) {
1708 std::vector<std::pair<SDOperand, const Type*> > Args;
1709 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1710 TLI.getTargetData().getIntPtrType()));
1711 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00001712 std::pair<SDOperand,SDOperand> Result =
Chris Lattneradf6a962005-05-13 18:50:42 +00001713 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00001714 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1715 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001716}
1717
Chris Lattner025c39b2005-08-26 20:54:47 +00001718// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1719// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1720// instructions are special in various ways, which require special support to
1721// insert. The specified MachineInstr is created but not inserted into any
1722// basic blocks, and the scheduler passes ownership of it to this method.
1723MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1724 MachineBasicBlock *MBB) {
1725 std::cerr << "If a target marks an instruction with "
1726 "'usesCustomDAGSchedInserter', it must implement "
1727 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1728 abort();
1729 return 0;
1730}
1731
Chris Lattner39ae3622005-01-09 00:00:49 +00001732void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001733 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1734 getValue(I.getOperand(1)),
1735 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00001736}
1737
1738void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001739 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1740 getValue(I.getOperand(0)),
1741 DAG.getSrcValue(I.getOperand(0)));
1742 setValue(&I, V);
1743 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001744}
1745
1746void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001747 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1748 getValue(I.getOperand(1)),
1749 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001750}
1751
1752void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00001753 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1754 getValue(I.getOperand(1)),
1755 getValue(I.getOperand(2)),
1756 DAG.getSrcValue(I.getOperand(1)),
1757 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00001758}
1759
Chris Lattner39ae3622005-01-09 00:00:49 +00001760// It is always conservatively correct for llvm.returnaddress and
1761// llvm.frameaddress to return 0.
1762std::pair<SDOperand, SDOperand>
1763TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1764 unsigned Depth, SelectionDAG &DAG) {
1765 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00001766}
1767
Chris Lattner50381b62005-05-14 05:50:48 +00001768SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00001769 assert(0 && "LowerOperation not implemented for this target!");
1770 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00001771 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00001772}
1773
Nate Begeman0aed7842006-01-28 03:14:31 +00001774SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1775 SelectionDAG &DAG) {
1776 assert(0 && "CustomPromoteOperation not implemented for this target!");
1777 abort();
1778 return SDOperand();
1779}
1780
Chris Lattner39ae3622005-01-09 00:00:49 +00001781void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1782 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1783 std::pair<SDOperand,SDOperand> Result =
Chris Lattnera651cf62005-01-17 19:43:36 +00001784 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner39ae3622005-01-09 00:00:49 +00001785 setValue(&I, Result.first);
1786 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00001787}
1788
Evan Cheng74d0aa92006-02-15 21:59:04 +00001789/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00001790/// operand.
1791static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00001792 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001793 MVT::ValueType CurVT = VT;
1794 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1795 uint64_t Val = C->getValue() & 255;
1796 unsigned Shift = 8;
1797 while (CurVT != MVT::i8) {
1798 Val = (Val << Shift) | Val;
1799 Shift <<= 1;
1800 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001801 }
1802 return DAG.getConstant(Val, VT);
1803 } else {
1804 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1805 unsigned Shift = 8;
1806 while (CurVT != MVT::i8) {
1807 Value =
1808 DAG.getNode(ISD::OR, VT,
1809 DAG.getNode(ISD::SHL, VT, Value,
1810 DAG.getConstant(Shift, MVT::i8)), Value);
1811 Shift <<= 1;
1812 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001813 }
1814
1815 return Value;
1816 }
1817}
1818
Evan Cheng74d0aa92006-02-15 21:59:04 +00001819/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1820/// used when a memcpy is turned into a memset when the source is a constant
1821/// string ptr.
1822static SDOperand getMemsetStringVal(MVT::ValueType VT,
1823 SelectionDAG &DAG, TargetLowering &TLI,
1824 std::string &Str, unsigned Offset) {
1825 MVT::ValueType CurVT = VT;
1826 uint64_t Val = 0;
1827 unsigned MSB = getSizeInBits(VT) / 8;
1828 if (TLI.isLittleEndian())
1829 Offset = Offset + MSB - 1;
1830 for (unsigned i = 0; i != MSB; ++i) {
1831 Val = (Val << 8) | Str[Offset];
1832 Offset += TLI.isLittleEndian() ? -1 : 1;
1833 }
1834 return DAG.getConstant(Val, VT);
1835}
1836
Evan Cheng1db92f92006-02-14 08:22:34 +00001837/// getMemBasePlusOffset - Returns base and offset node for the
1838static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1839 SelectionDAG &DAG, TargetLowering &TLI) {
1840 MVT::ValueType VT = Base.getValueType();
1841 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1842}
1843
Evan Chengc4f8eee2006-02-14 20:12:38 +00001844/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00001845/// to replace the memset / memcpy is below the threshold. It also returns the
1846/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00001847static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1848 unsigned Limit, uint64_t Size,
1849 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001850 MVT::ValueType VT;
1851
1852 if (TLI.allowsUnalignedMemoryAccesses()) {
1853 VT = MVT::i64;
1854 } else {
1855 switch (Align & 7) {
1856 case 0:
1857 VT = MVT::i64;
1858 break;
1859 case 4:
1860 VT = MVT::i32;
1861 break;
1862 case 2:
1863 VT = MVT::i16;
1864 break;
1865 default:
1866 VT = MVT::i8;
1867 break;
1868 }
1869 }
1870
Evan Cheng80e89d72006-02-14 09:11:59 +00001871 MVT::ValueType LVT = MVT::i64;
1872 while (!TLI.isTypeLegal(LVT))
1873 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1874 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00001875
Evan Cheng80e89d72006-02-14 09:11:59 +00001876 if (VT > LVT)
1877 VT = LVT;
1878
Evan Chengdea72452006-02-14 23:05:54 +00001879 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00001880 while (Size != 0) {
1881 unsigned VTSize = getSizeInBits(VT) / 8;
1882 while (VTSize > Size) {
1883 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00001884 VTSize >>= 1;
1885 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001886 assert(MVT::isInteger(VT));
1887
1888 if (++NumMemOps > Limit)
1889 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00001890 MemOps.push_back(VT);
1891 Size -= VTSize;
1892 }
Evan Cheng80e89d72006-02-14 09:11:59 +00001893
1894 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00001895}
1896
Chris Lattner7041ee32005-01-11 05:56:49 +00001897void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00001898 SDOperand Op1 = getValue(I.getOperand(1));
1899 SDOperand Op2 = getValue(I.getOperand(2));
1900 SDOperand Op3 = getValue(I.getOperand(3));
1901 SDOperand Op4 = getValue(I.getOperand(4));
1902 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1903 if (Align == 0) Align = 1;
1904
1905 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1906 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00001907
1908 // Expand memset / memcpy to a series of load / store ops
1909 // if the size operand falls below a certain threshold.
1910 std::vector<SDOperand> OutChains;
1911 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00001912 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00001913 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00001914 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1915 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00001916 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00001917 unsigned Offset = 0;
1918 for (unsigned i = 0; i < NumMemOps; i++) {
1919 MVT::ValueType VT = MemOps[i];
1920 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00001921 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chengc080d6f2006-02-15 01:54:51 +00001922 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1923 Value,
Chris Lattner864635a2006-02-22 22:37:12 +00001924 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1925 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chengc080d6f2006-02-15 01:54:51 +00001926 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00001927 Offset += VTSize;
1928 }
Evan Cheng1db92f92006-02-14 08:22:34 +00001929 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001930 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00001931 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001932 case ISD::MEMCPY: {
1933 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1934 Size->getValue(), Align, TLI)) {
1935 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00001936 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001937 GlobalAddressSDNode *G = NULL;
1938 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00001939 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001940
1941 if (Op2.getOpcode() == ISD::GlobalAddress)
1942 G = cast<GlobalAddressSDNode>(Op2);
1943 else if (Op2.getOpcode() == ISD::ADD &&
1944 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1945 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1946 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00001947 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00001948 }
1949 if (G) {
1950 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengcffbb512006-02-16 23:11:42 +00001951 if (GV) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001952 Str = getStringValue(GV);
Evan Chengcffbb512006-02-16 23:11:42 +00001953 if (!Str.empty()) {
1954 CopyFromStr = true;
1955 SrcOff += SrcDelta;
1956 }
1957 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00001958 }
1959
Evan Chengc080d6f2006-02-15 01:54:51 +00001960 for (unsigned i = 0; i < NumMemOps; i++) {
1961 MVT::ValueType VT = MemOps[i];
1962 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00001963 SDOperand Value, Chain, Store;
1964
Evan Chengcffbb512006-02-16 23:11:42 +00001965 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00001966 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1967 Chain = getRoot();
1968 Store =
1969 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1970 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1971 DAG.getSrcValue(I.getOperand(1), DstOff));
1972 } else {
1973 Value = DAG.getLoad(VT, getRoot(),
1974 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1975 DAG.getSrcValue(I.getOperand(2), SrcOff));
1976 Chain = Value.getValue(1);
1977 Store =
1978 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1979 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1980 DAG.getSrcValue(I.getOperand(1), DstOff));
1981 }
Evan Chengc080d6f2006-02-15 01:54:51 +00001982 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00001983 SrcOff += VTSize;
1984 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00001985 }
1986 }
1987 break;
1988 }
1989 }
1990
1991 if (!OutChains.empty()) {
1992 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1993 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00001994 }
1995 }
1996
Chris Lattner7041ee32005-01-11 05:56:49 +00001997 std::vector<SDOperand> Ops;
Chris Lattnera651cf62005-01-17 19:43:36 +00001998 Ops.push_back(getRoot());
Evan Cheng1db92f92006-02-14 08:22:34 +00001999 Ops.push_back(Op1);
2000 Ops.push_back(Op2);
2001 Ops.push_back(Op3);
2002 Ops.push_back(Op4);
Chris Lattner7041ee32005-01-11 05:56:49 +00002003 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner1c08c712005-01-07 07:47:53 +00002004}
2005
Chris Lattner7041ee32005-01-11 05:56:49 +00002006//===----------------------------------------------------------------------===//
2007// SelectionDAGISel code
2008//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00002009
2010unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2011 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2012}
2013
Chris Lattner495a0b52005-08-17 06:37:43 +00002014void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00002015 // FIXME: we only modify the CFG to split critical edges. This
2016 // updates dom and loop info.
Chris Lattner495a0b52005-08-17 06:37:43 +00002017}
Chris Lattner1c08c712005-01-07 07:47:53 +00002018
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002019
2020/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2021/// casting to the type of GEPI.
2022static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2023 Value *Ptr, Value *PtrOffset) {
2024 if (V) return V; // Already computed.
2025
2026 BasicBlock::iterator InsertPt;
2027 if (BB == GEPI->getParent()) {
2028 // If insert into the GEP's block, insert right after the GEP.
2029 InsertPt = GEPI;
2030 ++InsertPt;
2031 } else {
2032 // Otherwise, insert at the top of BB, after any PHI nodes
2033 InsertPt = BB->begin();
2034 while (isa<PHINode>(InsertPt)) ++InsertPt;
2035 }
2036
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002037 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2038 // BB so that there is only one value live across basic blocks (the cast
2039 // operand).
2040 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2041 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2042 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2043
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002044 // Add the offset, cast it to the right type.
2045 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2046 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2047 return V = Ptr;
2048}
2049
2050
2051/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2052/// selection, we want to be a bit careful about some things. In particular, if
2053/// we have a GEP instruction that is used in a different block than it is
2054/// defined, the addressing expression of the GEP cannot be folded into loads or
2055/// stores that use it. In this case, decompose the GEP and move constant
2056/// indices into blocks that use it.
2057static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2058 const TargetData &TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002059 // If this GEP is only used inside the block it is defined in, there is no
2060 // need to rewrite it.
2061 bool isUsedOutsideDefBB = false;
2062 BasicBlock *DefBB = GEPI->getParent();
2063 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2064 UI != E; ++UI) {
2065 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2066 isUsedOutsideDefBB = true;
2067 break;
2068 }
2069 }
2070 if (!isUsedOutsideDefBB) return;
2071
2072 // If this GEP has no non-zero constant indices, there is nothing we can do,
2073 // ignore it.
2074 bool hasConstantIndex = false;
2075 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2076 E = GEPI->op_end(); OI != E; ++OI) {
2077 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2078 if (CI->getRawValue()) {
2079 hasConstantIndex = true;
2080 break;
2081 }
2082 }
Chris Lattner3802c252005-12-11 09:05:13 +00002083 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2084 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002085
2086 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2087 // constant offset (which we now know is non-zero) and deal with it later.
2088 uint64_t ConstantOffset = 0;
2089 const Type *UIntPtrTy = TD.getIntPtrType();
2090 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2091 const Type *Ty = GEPI->getOperand(0)->getType();
2092
2093 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2094 E = GEPI->op_end(); OI != E; ++OI) {
2095 Value *Idx = *OI;
2096 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2097 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2098 if (Field)
2099 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2100 Ty = StTy->getElementType(Field);
2101 } else {
2102 Ty = cast<SequentialType>(Ty)->getElementType();
2103
2104 // Handle constant subscripts.
2105 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2106 if (CI->getRawValue() == 0) continue;
2107
2108 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2109 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2110 else
2111 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2112 continue;
2113 }
2114
2115 // Ptr = Ptr + Idx * ElementSize;
2116
2117 // Cast Idx to UIntPtrTy if needed.
2118 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2119
2120 uint64_t ElementSize = TD.getTypeSize(Ty);
2121 // Mask off bits that should not be set.
2122 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2123 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2124
2125 // Multiply by the element size and add to the base.
2126 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2127 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2128 }
2129 }
2130
2131 // Make sure that the offset fits in uintptr_t.
2132 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2133 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2134
2135 // Okay, we have now emitted all of the variable index parts to the BB that
2136 // the GEP is defined in. Loop over all of the using instructions, inserting
2137 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002138 // instruction to use the newly computed value, making GEPI dead. When the
2139 // user is a load or store instruction address, we emit the add into the user
2140 // block, otherwise we use a canonical version right next to the gep (these
2141 // won't be foldable as addresses, so we might as well share the computation).
2142
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002143 std::map<BasicBlock*,Value*> InsertedExprs;
2144 while (!GEPI->use_empty()) {
2145 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002146
2147 // If this use is not foldable into the addressing mode, use a version
2148 // emitted in the GEP block.
2149 Value *NewVal;
2150 if (!isa<LoadInst>(User) &&
2151 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2152 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2153 Ptr, PtrOffset);
2154 } else {
2155 // Otherwise, insert the code in the User's block so it can be folded into
2156 // any users in that block.
2157 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002158 User->getParent(), GEPI,
2159 Ptr, PtrOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002160 }
Chris Lattnerc78b0b72005-12-08 08:00:12 +00002161 User->replaceUsesOfWith(GEPI, NewVal);
2162 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002163
2164 // Finally, the GEP is dead, remove it.
2165 GEPI->eraseFromParent();
2166}
2167
Chris Lattner1c08c712005-01-07 07:47:53 +00002168bool SelectionDAGISel::runOnFunction(Function &Fn) {
2169 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2170 RegMap = MF.getSSARegMap();
2171 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2172
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002173 // First, split all critical edges for PHI nodes with incoming values that are
2174 // constants, this way the load of the constant into a vreg will not be placed
2175 // into MBBs that are used some other way.
2176 //
2177 // In this pass we also look for GEP instructions that are used across basic
2178 // blocks and rewrites them to improve basic-block-at-a-time selection.
2179 //
Chris Lattner36b708f2005-08-18 17:35:14 +00002180 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2181 PHINode *PN;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002182 BasicBlock::iterator BBI;
2183 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner36b708f2005-08-18 17:35:14 +00002184 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2185 if (isa<Constant>(PN->getIncomingValue(i)))
2186 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002187
2188 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2189 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2190 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner36b708f2005-08-18 17:35:14 +00002191 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002192
Chris Lattner1c08c712005-01-07 07:47:53 +00002193 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2194
2195 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2196 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00002197
Chris Lattner1c08c712005-01-07 07:47:53 +00002198 return true;
2199}
2200
2201
Chris Lattnerddb870b2005-01-13 17:59:43 +00002202SDOperand SelectionDAGISel::
2203CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002204 SDOperand Op = SDL.getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00002205 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002206 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00002207 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002208
2209 // If this type is not legal, we must make sure to not create an invalid
2210 // register use.
2211 MVT::ValueType SrcVT = Op.getValueType();
2212 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2213 SelectionDAG &DAG = SDL.DAG;
2214 if (SrcVT == DestVT) {
2215 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2216 } else if (SrcVT < DestVT) {
2217 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00002218 if (MVT::isFloatingPoint(SrcVT))
2219 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2220 else
Chris Lattnerfab08872005-09-02 00:19:37 +00002221 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00002222 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2223 } else {
2224 // The src value is expanded into multiple registers.
2225 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2226 Op, DAG.getConstant(0, MVT::i32));
2227 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2228 Op, DAG.getConstant(1, MVT::i32));
2229 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2230 return DAG.getCopyToReg(Op, Reg+1, Hi);
2231 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002232}
2233
Chris Lattner068a81e2005-01-17 17:15:02 +00002234void SelectionDAGISel::
2235LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2236 std::vector<SDOperand> &UnorderedChains) {
2237 // If this is the entry block, emit arguments.
2238 Function &F = *BB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00002239 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00002240 SDOperand OldRoot = SDL.DAG.getRoot();
2241 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00002242
Chris Lattnerbf209482005-10-30 19:42:35 +00002243 unsigned a = 0;
2244 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2245 AI != E; ++AI, ++a)
2246 if (!AI->use_empty()) {
2247 SDL.setValue(AI, Args[a]);
Chris Lattnerfa577022005-09-13 19:30:54 +00002248
Chris Lattnerbf209482005-10-30 19:42:35 +00002249 // If this argument is live outside of the entry block, insert a copy from
2250 // whereever we got it to the vreg that other BB's will reference it as.
2251 if (FuncInfo.ValueMap.count(AI)) {
2252 SDOperand Copy =
2253 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2254 UnorderedChains.push_back(Copy);
2255 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00002256 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002257
2258 // Next, if the function has live ins that need to be copied into vregs,
2259 // emit the copies now, into the top of the block.
2260 MachineFunction &MF = SDL.DAG.getMachineFunction();
2261 if (MF.livein_begin() != MF.livein_end()) {
2262 SSARegMap *RegMap = MF.getSSARegMap();
2263 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2264 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2265 E = MF.livein_end(); LI != E; ++LI)
2266 if (LI->second)
2267 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2268 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner068a81e2005-01-17 17:15:02 +00002269 }
Chris Lattnerbf209482005-10-30 19:42:35 +00002270
2271 // Finally, if the target has anything special to do, allow it to do so.
2272 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00002273}
2274
2275
Chris Lattner1c08c712005-01-07 07:47:53 +00002276void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2277 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2278 FunctionLoweringInfo &FuncInfo) {
2279 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002280
2281 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002282
Chris Lattnerbf209482005-10-30 19:42:35 +00002283 // Lower any arguments needed in this block if this is the entry block.
2284 if (LLVMBB == &LLVMBB->getParent()->front())
2285 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00002286
2287 BB = FuncInfo.MBBMap[LLVMBB];
2288 SDL.setCurrentBasicBlock(BB);
2289
2290 // Lower all of the non-terminator instructions.
2291 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2292 I != E; ++I)
2293 SDL.visit(*I);
2294
2295 // Ensure that all instructions which are used outside of their defining
2296 // blocks are available as virtual registers.
2297 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00002298 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattneree749d72005-01-09 01:16:24 +00002299 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00002300 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00002301 UnorderedChains.push_back(
2302 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00002303 }
2304
2305 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2306 // ensure constants are generated when needed. Remember the virtual registers
2307 // that need to be added to the Machine PHI nodes as input. We cannot just
2308 // directly add them, because expansion might result in multiple MBB's for one
2309 // BB. As such, the start of the BB might correspond to a different MBB than
2310 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00002311 //
Chris Lattner1c08c712005-01-07 07:47:53 +00002312
2313 // Emit constants only once even if used by multiple PHI nodes.
2314 std::map<Constant*, unsigned> ConstantsOut;
2315
2316 // Check successor nodes PHI nodes that expect a constant to be available from
2317 // this block.
2318 TerminatorInst *TI = LLVMBB->getTerminator();
2319 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2320 BasicBlock *SuccBB = TI->getSuccessor(succ);
2321 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2322 PHINode *PN;
2323
2324 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2325 // nodes and Machine PHI nodes, but the incoming operands have not been
2326 // emitted yet.
2327 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattnerf44fd882005-01-07 21:34:19 +00002328 (PN = dyn_cast<PHINode>(I)); ++I)
2329 if (!PN->use_empty()) {
2330 unsigned Reg;
2331 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2332 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2333 unsigned &RegOut = ConstantsOut[C];
2334 if (RegOut == 0) {
2335 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002336 UnorderedChains.push_back(
2337 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattnerf44fd882005-01-07 21:34:19 +00002338 }
2339 Reg = RegOut;
2340 } else {
2341 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattneree749d72005-01-09 01:16:24 +00002342 if (Reg == 0) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00002343 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattneree749d72005-01-09 01:16:24 +00002344 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2345 "Didn't codegen value into a register!??");
2346 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattnerddb870b2005-01-13 17:59:43 +00002347 UnorderedChains.push_back(
2348 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattneree749d72005-01-09 01:16:24 +00002349 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002350 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002351
Chris Lattnerf44fd882005-01-07 21:34:19 +00002352 // Remember that this register needs to added to the machine PHI node as
2353 // the input for this MBB.
2354 unsigned NumElements =
2355 TLI.getNumElements(TLI.getValueType(PN->getType()));
2356 for (unsigned i = 0, e = NumElements; i != e; ++i)
2357 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner1c08c712005-01-07 07:47:53 +00002358 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002359 }
2360 ConstantsOut.clear();
2361
Chris Lattnerddb870b2005-01-13 17:59:43 +00002362 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00002363 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00002364 SDOperand Root = SDL.getRoot();
2365 if (Root.getOpcode() != ISD::EntryToken) {
2366 unsigned i = 0, e = UnorderedChains.size();
2367 for (; i != e; ++i) {
2368 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2369 if (UnorderedChains[i].Val->getOperand(0) == Root)
2370 break; // Don't add the root if we already indirectly depend on it.
2371 }
2372
2373 if (i == e)
2374 UnorderedChains.push_back(Root);
2375 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00002376 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2377 }
2378
Chris Lattner1c08c712005-01-07 07:47:53 +00002379 // Lower the terminator after the copies are emitted.
2380 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00002381
2382 // Make sure the root of the DAG is up-to-date.
2383 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00002384}
2385
2386void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2387 FunctionLoweringInfo &FuncInfo) {
Jim Laskeyb2efb852006-01-04 22:28:25 +00002388 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner1c08c712005-01-07 07:47:53 +00002389 CurDAG = &DAG;
2390 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2391
2392 // First step, lower LLVM code to some DAG. This DAG may use operations and
2393 // types that are not supported by the target.
2394 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2395
Chris Lattneraf21d552005-10-10 16:47:10 +00002396 // Run the DAG combiner in pre-legalize mode.
2397 DAG.Combine(false);
Nate Begeman2300f552005-09-07 00:15:36 +00002398
Chris Lattner1c08c712005-01-07 07:47:53 +00002399 DEBUG(std::cerr << "Lowered selection DAG:\n");
2400 DEBUG(DAG.dump());
2401
2402 // Second step, hack on the DAG until it only uses operations and types that
2403 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00002404 DAG.Legalize();
Chris Lattner1c08c712005-01-07 07:47:53 +00002405
2406 DEBUG(std::cerr << "Legalized selection DAG:\n");
2407 DEBUG(DAG.dump());
2408
Chris Lattneraf21d552005-10-10 16:47:10 +00002409 // Run the DAG combiner in post-legalize mode.
2410 DAG.Combine(true);
Nate Begeman2300f552005-09-07 00:15:36 +00002411
Evan Chenga9c20912006-01-21 02:32:06 +00002412 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattnerd48050a2005-10-05 06:09:10 +00002413
Chris Lattnera33ef482005-03-30 01:10:47 +00002414 // Third, instruction select all of the operations to machine code, adding the
2415 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00002416 InstructionSelectBasicBlock(DAG);
2417
Chris Lattner1c08c712005-01-07 07:47:53 +00002418 DEBUG(std::cerr << "Selected machine code:\n");
2419 DEBUG(BB->dump());
2420
Chris Lattnera33ef482005-03-30 01:10:47 +00002421 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00002422 // PHI nodes in successors.
2423 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2424 MachineInstr *PHI = PHINodesToUpdate[i].first;
2425 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2426 "This is not a machine PHI node that we are updating!");
2427 PHI->addRegOperand(PHINodesToUpdate[i].second);
2428 PHI->addMachineBasicBlockOperand(BB);
2429 }
Chris Lattnera33ef482005-03-30 01:10:47 +00002430
2431 // Finally, add the CFG edges from the last selected MBB to the successor
2432 // MBBs.
2433 TerminatorInst *TI = LLVMBB->getTerminator();
2434 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2435 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2436 BB->addSuccessor(Succ0MBB);
2437 }
Chris Lattner1c08c712005-01-07 07:47:53 +00002438}
Evan Chenga9c20912006-01-21 02:32:06 +00002439
2440//===----------------------------------------------------------------------===//
2441/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2442/// target node in the graph.
2443void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2444 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00002445 ScheduleDAG *SL = NULL;
2446
2447 switch (ISHeuristic) {
2448 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Cheng3f239522006-01-25 09:12:57 +00002449 case defaultScheduling:
2450 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2451 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2452 else /* TargetLowering::SchedulingForRegPressure */
2453 SL = createBURRListDAGScheduler(DAG, BB);
2454 break;
Evan Cheng4ef10862006-01-23 07:01:07 +00002455 case noScheduling:
2456 case simpleScheduling:
2457 case simpleNoItinScheduling:
2458 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2459 break;
Evan Chengf0f9c902006-01-23 08:26:10 +00002460 case listSchedulingBURR:
2461 SL = createBURRListDAGScheduler(DAG, BB);
Evan Cheng4ef10862006-01-23 07:01:07 +00002462 }
Chris Lattnera3818e62006-01-21 19:12:11 +00002463 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00002464 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00002465}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00002466
2467/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2468/// by tblgen. Others should not call it.
2469void SelectionDAGISel::
2470SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2471 std::vector<SDOperand> InOps;
2472 std::swap(InOps, Ops);
2473
2474 Ops.push_back(InOps[0]); // input chain.
2475 Ops.push_back(InOps[1]); // input asm string.
2476
2477 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2478 unsigned i = 2, e = InOps.size();
2479 if (InOps[e-1].getValueType() == MVT::Flag)
2480 --e; // Don't process a flag operand if it is here.
2481
2482 while (i != e) {
2483 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2484 if ((Flags & 7) != 4 /*MEM*/) {
2485 // Just skip over this operand, copying the operands verbatim.
2486 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2487 i += (Flags >> 3) + 1;
2488 } else {
2489 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2490 // Otherwise, this is a memory operand. Ask the target to select it.
2491 std::vector<SDOperand> SelOps;
2492 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2493 std::cerr << "Could not match memory address. Inline asm failure!\n";
2494 exit(1);
2495 }
2496
2497 // Add this to the output node.
2498 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2499 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2500 i += 2;
2501 }
2502 }
2503
2504 // Add the flag input back if present.
2505 if (e != InOps.size())
2506 Ops.push_back(InOps.back());
2507}