irgenerator.cpp 132 KB
Newer Older
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1
// Copyright (c) 2014-2015 Dropbox, Inc.
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2
//
3 4 5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Kevin Modzelewski's avatar
Kevin Modzelewski committed
6
//
7
//    http://www.apache.org/licenses/LICENSE-2.0
Kevin Modzelewski's avatar
Kevin Modzelewski committed
8
//
9 10 11 12 13 14
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
#include "codegen/irgen/irgenerator.h"
16

17
#include "llvm/IR/Module.h"
18
#include "llvm/Support/raw_ostream.h"
19

20 21 22
#include "analysis/function_analysis.h"
#include "analysis/scoping_analysis.h"
#include "analysis/type_analysis.h"
23
#include "asm_writing/icinfo.h"
24
#include "codegen/codegen.h"
25
#include "codegen/compvars.h"
26 27
#include "codegen/irgen.h"
#include "codegen/irgen/util.h"
28 29
#include "codegen/osrentry.h"
#include "codegen/patchpoints.h"
30
#include "codegen/type_recording.h"
31 32
#include "core/ast.h"
#include "core/cfg.h"
33
#include "core/types.h"
34
#include "core/util.h"
35
#include "runtime/generator.h"
36 37 38 39 40
#include "runtime/objmodel.h"
#include "runtime/types.h"

namespace pyston {

41 42
extern "C" void dumpLLVM(void* _v) {
    llvm::Value* v = (llvm::Value*)_v;
43
    v->getType()->dump();
44 45 46
    v->dump();
}

47
IRGenState::IRGenState(FunctionMetadata* md, CompiledFunction* cf, SourceInfo* source_info,
48
                       std::unique_ptr<PhiAnalysis> phis, ParamNames* param_names, GCBuilder* gc,
49
                       llvm::MDNode* func_dbg_info, RefcountTracker* refcount_tracker)
50
    : md(md),
51
      cf(cf),
52 53 54 55 56
      source_info(source_info),
      phis(std::move(phis)),
      param_names(param_names),
      gc(gc),
      func_dbg_info(func_dbg_info),
57
      refcount_tracker(refcount_tracker),
58 59 60
      scratch_space(NULL),
      frame_info(NULL),
      frame_info_arg(NULL),
61
      globals(NULL),
62 63
      scratch_size(0) {
    assert(cf->func);
64
    assert(!cf->md); // in this case don't need to pass in sourceinfo
65 66 67 68 69
}

IRGenState::~IRGenState() {
}

70
llvm::Value* IRGenState::getScratchSpace(int min_bytes) {
71
    llvm::BasicBlock& entry_block = getLLVMFunction()->getEntryBlock();
72 73 74 75 76 77 78 79 80 81 82

    if (scratch_space) {
        assert(scratch_space->getParent() == &entry_block);
        assert(scratch_space->isStaticAlloca());
        if (scratch_size >= min_bytes)
            return scratch_space;
    }

    llvm::AllocaInst* new_scratch_space;
    // If the entry block is currently empty, we have to be more careful:
    if (entry_block.begin() == entry_block.end()) {
83
        new_scratch_space = new llvm::AllocaInst(g.i8, getConstantInt(min_bytes, g.i64), "scratch", &entry_block);
84
    } else {
85 86
        new_scratch_space = new llvm::AllocaInst(g.i8, getConstantInt(min_bytes, g.i64), "scratch",
                                                 entry_block.getFirstInsertionPt());
87
    }
88

89 90 91 92 93 94 95 96 97 98 99
    assert(new_scratch_space->isStaticAlloca());

    if (scratch_space)
        scratch_space->replaceAllUsesWith(new_scratch_space);

    scratch_size = min_bytes;
    scratch_space = new_scratch_space;

    return scratch_space;
}

100
ExceptionStyle UnwindInfo::preferredExceptionStyle() const {
101
    if (FORCE_LLVM_CAPI_CALLS)
102
        return CAPI;
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117
    // TODO: I think this makes more sense as a relative percentage rather
    // than an absolute threshold, but currently we don't count how many
    // times a statement was executed but didn't throw.
    //
    // In theory this means that eventually anything that throws will be viewed
    // as a highly-throwing statement, but I think that this is less bad than
    // it might be because the denominator will be roughly fixed since we will
    // tend to run this check after executing the statement a somewhat-fixed
    // number of times.
    // We might want to zero these out after we are done compiling, though.
    if (current_stmt->cxx_exception_count >= 10)
        return CAPI;

    return CXX;
118 119
}

Travis Hance's avatar
Travis Hance committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
static llvm::Value* getClosureParentGep(IREmitter& emitter, llvm::Value* closure) {
    static_assert(sizeof(Box) == offsetof(BoxedClosure, parent), "");
    static_assert(offsetof(BoxedClosure, parent) + sizeof(BoxedClosure*) == offsetof(BoxedClosure, nelts), "");
    return emitter.getBuilder()->CreateConstInBoundsGEP2_32(closure, 0, 1);
}

static llvm::Value* getClosureElementGep(IREmitter& emitter, llvm::Value* closure, size_t index) {
    static_assert(sizeof(Box) == offsetof(BoxedClosure, parent), "");
    static_assert(offsetof(BoxedClosure, parent) + sizeof(BoxedClosure*) == offsetof(BoxedClosure, nelts), "");
    static_assert(offsetof(BoxedClosure, nelts) + sizeof(size_t) == offsetof(BoxedClosure, elts), "");
    return emitter.getBuilder()->CreateGEP(
        closure,
        { llvm::ConstantInt::get(g.i32, 0), llvm::ConstantInt::get(g.i32, 3), llvm::ConstantInt::get(g.i32, index) });
}

Travis Hance's avatar
exec  
Travis Hance committed
135 136
static llvm::Value* getBoxedLocalsGep(llvm::IRBuilder<true>& builder, llvm::Value* v) {
    static_assert(offsetof(FrameInfo, exc) == 0, "");
137 138
    static_assert(sizeof(ExcInfo) == 24, "");
    static_assert(offsetof(FrameInfo, boxedLocals) == 24, "");
Travis Hance's avatar
exec  
Travis Hance committed
139 140 141 142 143
    return builder.CreateConstInBoundsGEP2_32(v, 0, 1);
}

static llvm::Value* getExcinfoGep(llvm::IRBuilder<true>& builder, llvm::Value* v) {
    static_assert(offsetof(FrameInfo, exc) == 0, "");
144
    return builder.CreateConstInBoundsGEP2_32(v, 0, 0);
Travis Hance's avatar
exec  
Travis Hance committed
145 146
}

147 148
static llvm::Value* getFrameObjGep(llvm::IRBuilder<true>& builder, llvm::Value* v) {
    static_assert(offsetof(FrameInfo, exc) == 0, "");
149
    static_assert(sizeof(ExcInfo) == 24, "");
150
    static_assert(sizeof(Box*) == 8, "");
151
    static_assert(offsetof(FrameInfo, frame_obj) == 32, "");
152 153 154 155 156
    return builder.CreateConstInBoundsGEP2_32(v, 0, 2);
    // TODO: this could be made more resilient by doing something like
    // gep->accumulateConstantOffset(g.tm->getDataLayout(), ap_offset)
}

157
llvm::Value* IRGenState::getFrameInfoVar() {
Travis Hance's avatar
exec  
Travis Hance committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    /*
        There is a matrix of possibilities here.

        For complete (non-OSR) functions, we initialize the FrameInfo* with an alloca and
        set this->frame_info to that llvm value.
        - If the function has NAME-scope, we initialize the frame_info.boxedLocals to a dictionary
          and set this->boxed_locals to an llvm value which is that dictionary.
        - If it is non-NAME-scope, we leave it NULL, because  most of the time it won't
          be initialized (unless someone calls locals() or something).
          this->boxed_locals is unused within the IR, so we don't set it.

        If this is an OSR function, then a FrameInfo* is passed in as an argument, so we don't
        need to initialize it with an alloca, and frame_info is already
        pointer.
        - If the function is NAME-scope, we extract the boxedLocals from the frame_info in order
          to set this->boxed_locals.
    */

    if (!this->frame_info) {
177 178 179 180 181 182 183 184
        llvm::BasicBlock& entry_block = getLLVMFunction()->getEntryBlock();

        llvm::IRBuilder<true> builder(&entry_block);

        if (entry_block.begin() != entry_block.end())
            builder.SetInsertPoint(&entry_block, entry_block.getFirstInsertionPt());


Travis Hance's avatar
exec  
Travis Hance committed
185
        llvm::AllocaInst* al = builder.CreateAlloca(g.llvm_frame_info_type, NULL, "frame_info");
186 187
        assert(al->isStaticAlloca());

Travis Hance's avatar
exec  
Travis Hance committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
        if (entry_block.getTerminator())
            builder.SetInsertPoint(entry_block.getTerminator());
        else
            builder.SetInsertPoint(&entry_block);

        if (frame_info_arg) {
            // The OSR case

            this->frame_info = frame_info_arg;

            if (getScopeInfo()->usesNameLookup()) {
                // load frame_info.boxedLocals
                this->boxed_locals = builder.CreateLoad(getBoxedLocalsGep(builder, this->frame_info));
            }
        } else {
            // The "normal" case

            // frame_info.exc.type = NULL
206
            llvm::Constant* null_value = getNullPtr(g.llvm_value_type_ptr);
207
            getRefcounts()->setType(null_value, RefType::BORROWED);
208 209 210
            llvm::Value* exc_info = getExcinfoGep(builder, al);
            builder.CreateStore(
                null_value, builder.CreateConstInBoundsGEP2_32(exc_info, 0, offsetof(ExcInfo, type) / sizeof(Box*)));
211

Travis Hance's avatar
exec  
Travis Hance committed
212 213
            // frame_info.boxedLocals = NULL
            llvm::Value* boxed_locals_gep = getBoxedLocalsGep(builder, al);
214 215
            builder.CreateStore(getRefcounts()->setType(getNullPtr(g.llvm_value_type_ptr), RefType::BORROWED),
                                boxed_locals_gep);
216

Travis Hance's avatar
exec  
Travis Hance committed
217 218 219 220
            if (getScopeInfo()->usesNameLookup()) {
                // frame_info.boxedLocals = createDict()
                // (Since this can call into the GC, we have to initialize it to NULL first as we did above.)
                this->boxed_locals = builder.CreateCall(g.funcs.createDict);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
221
                getRefcounts()->setType(this->boxed_locals, RefType::OWNED);
Travis Hance's avatar
exec  
Travis Hance committed
222 223 224
                builder.CreateStore(this->boxed_locals, boxed_locals_gep);
            }

225 226 227
            // frame_info.frame_obj = NULL
            static llvm::Type* llvm_frame_obj_type_ptr
                = llvm::cast<llvm::StructType>(g.llvm_frame_info_type)->getElementType(2);
228 229
            builder.CreateStore(getRefcounts()->setType(getNullPtr(llvm_frame_obj_type_ptr), RefType::BORROWED),
                                getFrameObjGep(builder, al));
230

Travis Hance's avatar
exec  
Travis Hance committed
231 232
            this->frame_info = al;
        }
233
    }
Travis Hance's avatar
exec  
Travis Hance committed
234 235 236 237 238 239 240 241 242

    return this->frame_info;
}

llvm::Value* IRGenState::getBoxedLocalsVar() {
    assert(getScopeInfo()->usesNameLookup());
    getFrameInfoVar(); // ensures this->boxed_locals_var is initialized
    assert(this->boxed_locals != NULL);
    return this->boxed_locals;
243 244
}

245
ScopeInfo* IRGenState::getScopeInfo() {
246 247 248 249 250 251
    return getSourceInfo()->getScopeInfo();
}

ScopeInfo* IRGenState::getScopeInfoForNode(AST* node) {
    auto source = getSourceInfo();
    return source->scoping->getScopeInfoForNode(node);
252 253
}

254 255 256 257 258 259 260 261 262 263
void IRGenState::setGlobals(llvm::Value* globals) {
    assert(!source_info->scoping->areGlobalsFromModule());
    assert(!this->globals);
    this->globals = globals;
}

llvm::Value* IRGenState::getGlobals() {
    if (!globals) {
        assert(source_info->scoping->areGlobalsFromModule());
        this->globals = embedRelocatablePtr(source_info->parent_module, g.llvm_value_type_ptr);
264
        this->getRefcounts()->setType(this->globals, RefType::BORROWED);
265 266 267 268 269 270 271 272 273 274
    }
    return this->globals;
}

llvm::Value* IRGenState::getGlobalsIfCustom() {
    if (source_info->scoping->areGlobalsFromModule())
        return getNullPtr(g.llvm_value_type_ptr);
    return getGlobals();
}

275 276 277
// XXX This is pretty hacky, but I think I can get rid of it once I merge in Marius's new frame introspection work
#define NO_CXX_INTERCEPTION ((llvm::BasicBlock*)-1)

278
class IREmitterImpl : public IREmitter {
279 280
private:
    IRGenState* irstate;
281
    std::unique_ptr<IRBuilder> builder;
282
    llvm::BasicBlock*& curblock;
283 284
    IRGenerator* irgenerator;

285 286
    llvm::CallSite emitCall(const UnwindInfo& unw_info, llvm::Value* callee, const std::vector<llvm::Value*>& args,
                            ExceptionStyle target_exception_style) {
287 288 289 290
        bool needs_cxx_interception;
        if (unw_info.exc_dest == NO_CXX_INTERCEPTION) {
            needs_cxx_interception = false;
        } else {
291
            bool needs_refcounting_fixup = false;
292 293 294
            needs_cxx_interception = (target_exception_style == CXX && (needs_refcounting_fixup || unw_info.hasHandler()
                                                                        || irstate->getExceptionStyle() == CAPI));
        }
295 296

        if (needs_cxx_interception) {
297
            // Create the invoke:
298 299
            llvm::BasicBlock* normal_dest
                = llvm::BasicBlock::Create(g.context, curblock->getName(), irstate->getLLVMFunction());
300 301 302 303 304 305 306 307

            llvm::BasicBlock* final_exc_dest;
            if (unw_info.hasHandler()) {
                final_exc_dest = unw_info.exc_dest;
            } else {
                final_exc_dest = NULL; // signal to reraise as a capi exception
            }

308
            llvm::BasicBlock* exc_dest = irgenerator->getCXXExcDest(unw_info);
309 310
            normal_dest->moveAfter(curblock);

311 312 313
            llvm::InvokeInst* rtn = getBuilder()->CreateInvoke(callee, normal_dest, exc_dest, args);

            // Normal case:
314 315 316 317
            getBuilder()->SetInsertPoint(normal_dest);
            curblock = normal_dest;
            return rtn;
        } else {
318 319
            llvm::CallInst* cs = getBuilder()->CreateCall(callee, args);
            return cs;
320 321 322 323 324
        }
    }

    llvm::CallSite emitPatchpoint(llvm::Type* return_type, const ICSetupInfo* pp, llvm::Value* func,
                                  const std::vector<llvm::Value*>& args,
325 326
                                  const std::vector<llvm::Value*>& ic_stackmap_args, const UnwindInfo& unw_info,
                                  ExceptionStyle target_exception_style) {
327 328 329
        if (pp == NULL)
            assert(ic_stackmap_args.size() == 0);

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
        // Retrieve address of called function, currently handles the IR
        // embedConstantPtr() and embedRelocatablePtr() create.
        void* func_addr = nullptr;
        if (llvm::isa<llvm::ConstantExpr>(func)) {
            llvm::ConstantExpr* cast = llvm::cast<llvm::ConstantExpr>(func);
            auto opcode = cast->getOpcode();
            if (opcode == llvm::Instruction::IntToPtr) {
                auto operand = cast->getOperand(0);
                if (llvm::isa<llvm::ConstantInt>(operand))
                    func_addr = (void*)llvm::cast<llvm::ConstantInt>(operand)->getZExtValue();
            }
        }
        assert(func_addr);

        PatchpointInfo* info = PatchpointInfo::create(currentFunction(), pp, ic_stackmap_args.size(), func_addr);

        int64_t pp_id = info->getId();
347 348 349
        int pp_size = pp ? pp->totalSize() : CALL_ONLY_SIZE;

        std::vector<llvm::Value*> pp_args;
350
        pp_args.push_back(getConstantInt(pp_id, g.i64));
351
        pp_args.push_back(getConstantInt(pp_size, g.i32));
352 353 354 355 356
        if (ENABLE_JIT_OBJECT_CACHE)
            // add fixed dummy dest pointer, we will replace it with the correct address during stackmap processing
            pp_args.push_back(embedConstantPtr((void*)-1L, g.i8_ptr));
        else
            pp_args.push_back(func);
357 358 359 360 361 362 363 364 365 366
        pp_args.push_back(getConstantInt(args.size(), g.i32));

        pp_args.insert(pp_args.end(), args.begin(), args.end());

        int num_scratch_bytes = info->scratchSize();
        llvm::Value* scratch_space = irstate->getScratchSpace(num_scratch_bytes);
        pp_args.push_back(scratch_space);

        pp_args.insert(pp_args.end(), ic_stackmap_args.begin(), ic_stackmap_args.end());

367
        irgenerator->addFrameStackmapArgs(info, unw_info.current_stmt, pp_args);
368

369 370 371 372 373 374 375 376 377 378 379 380 381
        llvm::Intrinsic::ID intrinsic_id;
        if (return_type->isIntegerTy() || return_type->isPointerTy()) {
            intrinsic_id = llvm::Intrinsic::experimental_patchpoint_i64;
        } else if (return_type->isVoidTy()) {
            intrinsic_id = llvm::Intrinsic::experimental_patchpoint_void;
        } else if (return_type->isDoubleTy()) {
            intrinsic_id = llvm::Intrinsic::experimental_patchpoint_double;
        } else {
            return_type->dump();
            abort();
        }
        llvm::Function* patchpoint = this->getIntrinsic(intrinsic_id);

382
        llvm::CallSite rtn = this->emitCall(unw_info, patchpoint, pp_args, target_exception_style);
383 384
        return rtn;
    }
385

386
public:
387 388
    explicit IREmitterImpl(IRGenState* irstate, llvm::BasicBlock*& curblock, IRGenerator* irgenerator)
        : irstate(irstate), builder(new IRBuilder(g.context)), curblock(curblock), irgenerator(irgenerator) {
389 390 391
        // Perf note: it seems to be more efficient to separately allocate the "builder" member,
        // even though we could allocate it in-line; maybe it's infrequently used enough that it's better
        // to not have it take up cache space.
392

393
        builder->setEmitter(this);
394
        builder->SetInsertPoint(curblock);
395
    }
396

397
    IRBuilder* getBuilder() override { return &*builder; }
398

399
    GCBuilder* getGC() override { return irstate->getGC(); }
400

401 402 403
    llvm::Function* getIntrinsic(llvm::Intrinsic::ID intrinsic_id) override {
        return llvm::Intrinsic::getDeclaration(g.cur_module, intrinsic_id);
    }
404

405 406 407 408
    llvm::Value* getScratch(int num_bytes) override { return irstate->getScratchSpace(num_bytes); }

    void releaseScratch(llvm::Value* scratch) override { assert(0); }

409
    CompiledFunction* currentFunction() override { return irstate->getCurFunction(); }
410 411 412 413 414 415 416 417 418 419
    llvm::BasicBlock* currentBasicBlock() override { return curblock; }

    void setCurrentBasicBlock(llvm::BasicBlock* bb) override {
        curblock = bb;
        getBuilder()->SetInsertPoint(curblock);
    }

    llvm::BasicBlock* createBasicBlock(const char* name) override {
        return llvm::BasicBlock::Create(g.context, name, irstate->getLLVMFunction());
    }
420

421
    llvm::Instruction* createCall(const UnwindInfo& unw_info, llvm::Value* callee, const std::vector<llvm::Value*>& args,
422
                            ExceptionStyle target_exception_style = CXX) override {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
#ifndef NDEBUG
        // Copied the argument-type-checking from CallInst::init, since the patchpoint arguments don't
        // get checked.
        llvm::FunctionType* FTy
            = llvm::cast<llvm::FunctionType>(llvm::cast<llvm::PointerType>(callee->getType())->getElementType());

        assert((args.size() == FTy->getNumParams() || (FTy->isVarArg() && args.size() > FTy->getNumParams()))
               && "Calling a function with wrong number of args!");

        for (unsigned i = 0; i != args.size(); ++i) {
            if (!(i >= FTy->getNumParams() || FTy->getParamType(i) == args[i]->getType())) {
                llvm::errs() << "Expected: " << *FTy->getParamType(i) << '\n';
                llvm::errs() << "Got: " << *args[i]->getType() << '\n';
                ASSERT(0, "Calling a function with a bad type for argument %d!", i);
            }
        }
#endif

441 442 443 444 445
        if (ENABLE_FRAME_INTROSPECTION) {
            llvm::Type* rtn_type = llvm::cast<llvm::FunctionType>(llvm::cast<llvm::PointerType>(callee->getType())
                                                                      ->getElementType())->getReturnType();

            llvm::Value* bitcasted = getBuilder()->CreateBitCast(callee, g.i8->getPointerTo());
446
            llvm::CallSite cs = emitPatchpoint(rtn_type, NULL, bitcasted, args, {}, unw_info, target_exception_style);
447 448 449 450

            if (rtn_type == cs->getType()) {
                return cs.getInstruction();
            } else if (rtn_type == g.i1) {
451
                return llvm::cast<llvm::Instruction>(getBuilder()->CreateTrunc(cs.getInstruction(), rtn_type));
452
            } else if (llvm::isa<llvm::PointerType>(rtn_type)) {
453
                return llvm::cast<llvm::Instruction>(getBuilder()->CreateIntToPtr(cs.getInstruction(), rtn_type));
454 455 456 457 458 459
            } else {
                cs.getInstruction()->getType()->dump();
                rtn_type->dump();
                RELEASE_ASSERT(0, "don't know how to convert those");
            }
        } else {
460
            return emitCall(unw_info, callee, args, target_exception_style).getInstruction();
461
        }
462 463
    }

464
    llvm::Instruction* createCall(const UnwindInfo& unw_info, llvm::Value* callee,
465 466
                            ExceptionStyle target_exception_style = CXX) override {
        return createCall(unw_info, callee, std::vector<llvm::Value*>(), target_exception_style);
467 468
    }

469
    llvm::Instruction* createCall(const UnwindInfo& unw_info, llvm::Value* callee, llvm::Value* arg1,
470 471
                            ExceptionStyle target_exception_style = CXX) override {
        return createCall(unw_info, callee, std::vector<llvm::Value*>({ arg1 }), target_exception_style);
472 473
    }

474
    llvm::Instruction* createCall2(const UnwindInfo& unw_info, llvm::Value* callee, llvm::Value* arg1, llvm::Value* arg2,
475 476
                             ExceptionStyle target_exception_style = CXX) override {
        return createCall(unw_info, callee, { arg1, arg2 }, target_exception_style);
477 478
    }

479
    llvm::Instruction* createCall3(const UnwindInfo& unw_info, llvm::Value* callee, llvm::Value* arg1, llvm::Value* arg2,
480 481
                             llvm::Value* arg3, ExceptionStyle target_exception_style = CXX) override {
        return createCall(unw_info, callee, { arg1, arg2, arg3 }, target_exception_style);
482 483
    }

484
    llvm::Instruction* createIC(const ICSetupInfo* pp, void* func_addr, const std::vector<llvm::Value*>& args,
485
                          const UnwindInfo& unw_info, ExceptionStyle target_exception_style = CXX) override {
486
        std::vector<llvm::Value*> stackmap_args;
487

488 489 490
        llvm::CallSite rtn = emitPatchpoint(pp->hasReturnValue() ? g.i64 : g.void_, pp,
                                            embedConstantPtr(func_addr, g.i8->getPointerTo()), args, stackmap_args,
                                            unw_info, target_exception_style);
491

492
        rtn.setCallingConv(pp->getCallingConvention());
493
        return rtn.getInstruction();
494
    }
495

496 497 498 499 500 501 502 503
    void checkAndPropagateCapiException(const UnwindInfo& unw_info, llvm::Value* returned_val, llvm::Value* exc_val,
                                        bool double_check = false) override {
        assert(!double_check); // need to call PyErr_Occurred

        llvm::BasicBlock* normal_dest
            = llvm::BasicBlock::Create(g.context, curblock->getName(), irstate->getLLVMFunction());
        normal_dest->moveAfter(curblock);

504
        llvm::BasicBlock* exc_dest = irgenerator->getCAPIExcDest(curblock, unw_info.exc_dest, unw_info.current_stmt);
505 506 507 508 509 510 511 512

        assert(returned_val->getType() == exc_val->getType());
        llvm::Value* check_val = getBuilder()->CreateICmpEQ(returned_val, exc_val);
        llvm::BranchInst* nullcheck = getBuilder()->CreateCondBr(check_val, exc_dest, normal_dest);

        setCurrentBasicBlock(normal_dest);
    }

513
    Box* getIntConstant(int64_t n) override {
514
        return irstate->getSourceInfo()->parent_module->getIntConstant(n);
515 516 517
    }

    Box* getFloatConstant(double d) override {
518
        return irstate->getSourceInfo()->parent_module->getFloatConstant(d);
519
    }
520

521 522 523 524
    void refConsumed(llvm::Value* v, llvm::Instruction* inst) {
        irstate->getRefcounts()->refConsumed(v, inst);
    }

525
    llvm::Value* setType(llvm::Value* v, RefType reftype) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
526 527
        assert(llvm::isa<PointerType>(v->getType()));

528
        irstate->getRefcounts()->setType(v, reftype);
529
        return v;
530 531
    }

532 533 534 535 536
    llvm::Value* setNullable(llvm::Value* v, bool nullable) {
        irstate->getRefcounts()->setNullable(v, nullable);
        return v;
    }

537 538 539 540 541
    ConcreteCompilerVariable* getNone() {
        llvm::Constant* none = embedRelocatablePtr(None, g.llvm_value_type_ptr, "cNone");
        setType(none, RefType::BORROWED);
        return new ConcreteCompilerVariable(typeFromClass(none_cls), none);
    }
542
};
543

544 545
IREmitter* createIREmitter(IRGenState* irstate, llvm::BasicBlock*& curblock, IRGenerator* irgenerator) {
    return new IREmitterImpl(irstate, curblock, irgenerator);
546 547
}

548
static std::unordered_map<AST_expr*, std::vector<BoxedString*>*> made_keyword_storage;
549
std::vector<BoxedString*>* getKeywordNameStorage(AST_Call* node) {
550 551 552 553
    auto it = made_keyword_storage.find(node);
    if (it != made_keyword_storage.end())
        return it->second;

554
    auto rtn = new std::vector<BoxedString*>();
555
    made_keyword_storage.insert(it, std::make_pair(node, rtn));
556 557 558 559 560 561 562 563 564

    // Only add the keywords to the array the first time, since
    // the later times we will hit the cache which will have the
    // keyword names already populated:
    if (!rtn->size()) {
        for (auto kw : node->keywords)
            rtn->push_back(kw->arg.getBox());
    }

565 566 567
    return rtn;
}

568 569 570
const std::string CREATED_CLOSURE_NAME = "#created_closure";
const std::string PASSED_CLOSURE_NAME = "#passed_closure";
const std::string PASSED_GENERATOR_NAME = "#passed_generator";
Travis Hance's avatar
exec  
Travis Hance committed
571
const std::string FRAME_INFO_PTR_NAME = "#frame_info_ptr";
572
const std::string PASSED_GLOBALS_NAME = "#passed_globals";
Kevin Modzelewski's avatar
Kevin Modzelewski committed
573

574
bool isIsDefinedName(llvm::StringRef name) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
575 576 577
    return startswith(name, "!is_defined_");
}

578 579
InternedString getIsDefinedName(InternedString name, InternedStringPool& interned_strings) {
    // TODO could cache this
580
    return interned_strings.get(("!is_defined_" + name.s()).str());
581 582
}

583
class IRGeneratorImpl : public IRGenerator {
584 585 586
private:
    IRGenState* irstate;

587
    llvm::BasicBlock* curblock;
588
    IREmitterImpl emitter;
589
    // symbol_table tracks which (non-global) python variables are bound to which CompilerVariables
590 591 592 593 594
    SymbolTable symbol_table;
    std::unordered_map<CFGBlock*, llvm::BasicBlock*>& entry_blocks;
    CFGBlock* myblock;
    TypeAnalysis* types;

595 596 597 598 599 600 601 602 603
    // These are some special values used for passing exception data between blocks;
    // this transfer is not explicitly represented in the CFG which is why it has special
    // handling here.  ie these variables are how we handle the special "invoke->landingpad"
    // value transfer, which doesn't involve the normal symbol name handling.
    //
    // These are the values that are incoming to a landingpad block:
    llvm::SmallVector<ExceptionState, 2> incoming_exc_state;
    // These are the values that are outgoing of an invoke block:
    llvm::SmallVector<ExceptionState, 2> outgoing_exc_state;
604
    //llvm::DenseMap<llvm::BasicBlock*, llvm::BasicBlock*> cxx_exc_dests;
605
    llvm::DenseMap<llvm::BasicBlock*, llvm::BasicBlock*> capi_exc_dests;
606
    llvm::DenseMap<llvm::BasicBlock*, llvm::PHINode*> capi_phis;
607

608 609 610 611 612 613 614 615
    enum State {
        RUNNING,  // normal
        DEAD,     // passed a Return statement; still syntatically valid but the code should not be compiled
        FINISHED, // passed a pseudo-node such as Branch or Jump; internal error if there are any more statements
    } state;

public:
    IRGeneratorImpl(IRGenState* irstate, std::unordered_map<CFGBlock*, llvm::BasicBlock*>& entry_blocks,
616
                    CFGBlock* myblock, TypeAnalysis* types)
617 618 619 620 621 622 623
        : irstate(irstate),
          curblock(entry_blocks[myblock]),
          emitter(irstate, curblock, this),
          entry_blocks(entry_blocks),
          myblock(myblock),
          types(types),
          state(RUNNING) {}
624

625 626 627 628
    virtual CFGBlock* getCFGBlock() {
        return myblock;
    }

629
private:
630
    OpInfo getOpInfoForNode(AST* ast, const UnwindInfo& unw_info) {
631
        assert(ast);
632

633
        EffortLevel effort = irstate->getEffortLevel();
634 635 636 637
        // This is the only place we create type recorders for the llvm tier;
        // if we are ok with never doing that there's a bunch of code that could
        // be removed.
        bool record_types = false;
638

639 640 641 642 643
        TypeRecorder* type_recorder;
        if (record_types) {
            type_recorder = getTypeRecorderForNode(ast);
        } else {
            type_recorder = NULL;
644 645
        }

646
        return OpInfo(irstate->getEffortLevel(), type_recorder, unw_info, ICInfo::getICInfoForNode(ast));
647
    }
648

649 650 651
    OpInfo getEmptyOpInfo(const UnwindInfo& unw_info) {
        return OpInfo(irstate->getEffortLevel(), NULL, unw_info, NULL);
    }
652

653
    void createExprTypeGuard(llvm::Value* check_val, AST* node, llvm::Value* node_value, AST_stmt* current_statement) {
654
        assert(check_val->getType() == g.i1);
655

Kevin Modzelewski's avatar
Kevin Modzelewski committed
656 657 658 659
        llvm::Metadata* md_vals[]
            = { llvm::MDString::get(g.context, "branch_weights"), llvm::ConstantAsMetadata::get(getConstantInt(1000)),
                llvm::ConstantAsMetadata::get(getConstantInt(1)) };
        llvm::MDNode* branch_weights = llvm::MDNode::get(g.context, llvm::ArrayRef<llvm::Metadata*>(md_vals));
660

661 662 663 664 665 666
        // For some reason there doesn't seem to be the ability to place the new BB
        // right after the current bb (can only place it *before* something else),
        // but we can put it somewhere arbitrary and then move it.
        llvm::BasicBlock* success_bb
            = llvm::BasicBlock::Create(g.context, "check_succeeded", irstate->getLLVMFunction());
        success_bb->moveAfter(curblock);
667

668
        llvm::BasicBlock* deopt_bb = llvm::BasicBlock::Create(g.context, "check_failed", irstate->getLLVMFunction());
669

670 671 672
        llvm::BranchInst* guard = emitter.getBuilder()->CreateCondBr(check_val, success_bb, deopt_bb, branch_weights);

        curblock = deopt_bb;
673
        emitter.getBuilder()->SetInsertPoint(curblock);
674
        llvm::Value* v = emitter.createCall2(UnwindInfo(current_statement, NULL), g.funcs.deopt,
675
                                             embedRelocatablePtr(node, g.llvm_astexpr_type_ptr), node_value);
676
        emitter.getBuilder()->CreateRet(v);
677

678 679 680
        curblock = success_bb;
        emitter.getBuilder()->SetInsertPoint(curblock);
    }
681

682 683 684 685 686 687
    template <typename T> InternedString internString(T&& s) {
        return irstate->getSourceInfo()->getInternedStrings().get(std::forward<T>(s));
    }

    InternedString getIsDefinedName(InternedString name) {
        return pyston::getIsDefinedName(name, irstate->getSourceInfo()->getInternedStrings());
688
    }
689

690
    CompilerVariable* evalAttribute(AST_Attribute* node, const UnwindInfo& unw_info) {
691
        CompilerVariable* value = evalExpr(node->value, unw_info);
692

693
        CompilerVariable* rtn = value->getattr(emitter, getOpInfoForNode(node, unw_info), node->attr.getBox(), false);
694 695
        return rtn;
    }
696

697
    CompilerVariable* evalClsAttribute(AST_ClsAttribute* node, const UnwindInfo& unw_info) {
698
        CompilerVariable* value = evalExpr(node->value, unw_info);
699
        CompilerVariable* rtn = value->getattr(emitter, getOpInfoForNode(node, unw_info), node->attr.getBox(), true);
700 701 702
        return rtn;
    }

703
    CompilerVariable* evalLangPrimitive(AST_LangPrimitive* node, const UnwindInfo& unw_info) {
704
        switch (node->opcode) {
705 706
            case AST_LangPrimitive::CHECK_EXC_MATCH: {
                assert(node->args.size() == 2);
707 708
                CompilerVariable* obj = evalExpr(node->args[0], unw_info);
                CompilerVariable* cls = evalExpr(node->args[1], unw_info);
709 710 711 712

                ConcreteCompilerVariable* converted_obj = obj->makeConverted(emitter, obj->getBoxType());
                ConcreteCompilerVariable* converted_cls = cls->makeConverted(emitter, cls->getBoxType());

713 714
                llvm::Value* v = emitter.createCall(unw_info, g.funcs.exceptionMatches,
                                                    { converted_obj->getValue(), converted_cls->getValue() });
715 716
                assert(v->getType() == g.i1);

717
                return boolFromI1(emitter, v);
718 719
            }
            case AST_LangPrimitive::LANDINGPAD: {
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
                ConcreteCompilerVariable* exc_type;
                ConcreteCompilerVariable* exc_value;
                ConcreteCompilerVariable* exc_tb;

                if (this->incoming_exc_state.size()) {
                    if (incoming_exc_state.size() == 1) {
                        exc_type = this->incoming_exc_state[0].exc_type;
                        exc_value = this->incoming_exc_state[0].exc_value;
                        exc_tb = this->incoming_exc_state[0].exc_tb;
                    } else {
                        llvm::PHINode* phi_exc_type
                            = emitter.getBuilder()->CreatePHI(g.llvm_value_type_ptr, incoming_exc_state.size());
                        llvm::PHINode* phi_exc_value
                            = emitter.getBuilder()->CreatePHI(g.llvm_value_type_ptr, incoming_exc_state.size());
                        llvm::PHINode* phi_exc_tb
                            = emitter.getBuilder()->CreatePHI(g.llvm_value_type_ptr, incoming_exc_state.size());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
736 737 738
                        emitter.setType(phi_exc_type, RefType::OWNED);
                        emitter.setType(phi_exc_value, RefType::OWNED);
                        emitter.setType(phi_exc_tb, RefType::OWNED);
739 740 741 742
                        for (auto e : this->incoming_exc_state) {
                            phi_exc_type->addIncoming(e.exc_type->getValue(), e.from_block);
                            phi_exc_value->addIncoming(e.exc_value->getValue(), e.from_block);
                            phi_exc_tb->addIncoming(e.exc_tb->getValue(), e.from_block);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
743 744 745
                            emitter.refConsumed(e.exc_type->getValue(), e.from_block->getTerminator());
                            emitter.refConsumed(e.exc_value->getValue(), e.from_block->getTerminator());
                            emitter.refConsumed(e.exc_tb->getValue(), e.from_block->getTerminator());
746
                        }
747 748 749
                        exc_type = new ConcreteCompilerVariable(UNKNOWN, phi_exc_type);
                        exc_value = new ConcreteCompilerVariable(UNKNOWN, phi_exc_value);
                        exc_tb = new ConcreteCompilerVariable(UNKNOWN, phi_exc_tb);
750
                    }
751
                } else {
752 753 754 755 756
                    // There can be no incoming exception if the irgenerator was able to prove that
                    // an exception would not get thrown.
                    // For example, the cfg code will conservatively assume that any name-access can
                    // trigger an exception, but the irgenerator will know that definitely-defined
                    // local symbols will not throw.
757
                    emitter.getBuilder()->CreateUnreachable();
758 759 760
                    exc_type = undefVariable();
                    exc_value = undefVariable();
                    exc_tb = undefVariable();
761
                    endBlock(DEAD);
762
                }
763

764 765 766 767
                // clear this out to signal that we consumed them:
                this->incoming_exc_state.clear();

                return makeTuple({ exc_type, exc_value, exc_tb });
768
            }
769
            case AST_LangPrimitive::LOCALS: {
770
                return new ConcreteCompilerVariable(UNKNOWN, irstate->getBoxedLocalsVar());
771
            }
772 773
            case AST_LangPrimitive::GET_ITER: {
                assert(node->args.size() == 1);
774
                CompilerVariable* obj = evalExpr(node->args[0], unw_info);
775 776
                auto rtn = obj->getPystonIter(emitter, getOpInfoForNode(node, unw_info));
                return rtn;
777
            }
778 779 780
            case AST_LangPrimitive::IMPORT_FROM: {
                assert(node->args.size() == 2);
                assert(node->args[0]->type == AST_TYPE::Name);
781
                assert(node->args[1]->type == AST_TYPE::Str);
782

783
                CompilerVariable* module = evalExpr(node->args[0], unw_info);
784 785
                ConcreteCompilerVariable* converted_module = module->makeConverted(emitter, module->getBoxType());

786 787 788
                auto ast_str = ast_cast<AST_Str>(node->args[1]);
                assert(ast_str->str_type == AST_Str::STR);
                const std::string& name = ast_str->str_data;
789 790
                assert(name.size());

791 792 793
                llvm::Value* name_arg
                    = embedRelocatablePtr(irstate->getSourceInfo()->parent_module->getStringConstant(name, true),
                                          g.llvm_boxedstring_type_ptr);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
794
                emitter.setType(name_arg, RefType::BORROWED);
795 796
                llvm::Value* r
                    = emitter.createCall2(unw_info, g.funcs.importFrom, converted_module->getValue(), name_arg);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
797
                emitter.setType(r, RefType::OWNED);
798

799
                CompilerVariable* v = new ConcreteCompilerVariable(UNKNOWN, r);
800 801
                return v;
            }
Travis Hance's avatar
Travis Hance committed
802 803 804 805 806
            case AST_LangPrimitive::IMPORT_STAR: {
                assert(node->args.size() == 1);
                assert(node->args[0]->type == AST_TYPE::Name);

                RELEASE_ASSERT(irstate->getSourceInfo()->ast->type == AST_TYPE::Module,
807
                               "import * not supported in functions (yet)");
Travis Hance's avatar
Travis Hance committed
808

809
                CompilerVariable* module = evalExpr(node->args[0], unw_info);
Travis Hance's avatar
Travis Hance committed
810 811
                ConcreteCompilerVariable* converted_module = module->makeConverted(emitter, module->getBoxType());

812
                llvm::Value* r = emitter.createCall2(unw_info, g.funcs.importStar, converted_module->getValue(),
813
                                                     irstate->getGlobals());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
814
                emitter.setType(r, RefType::OWNED);
815
                CompilerVariable* v = new ConcreteCompilerVariable(UNKNOWN, r);
Travis Hance's avatar
Travis Hance committed
816 817 818 819 820 821 822 823 824 825 826
                return v;
            }
            case AST_LangPrimitive::IMPORT_NAME: {
                assert(node->args.size() == 3);
                assert(node->args[0]->type == AST_TYPE::Num);
                assert(static_cast<AST_Num*>(node->args[0])->num_type == AST_Num::INT);
                assert(node->args[2]->type == AST_TYPE::Str);

                int level = static_cast<AST_Num*>(node->args[0])->n_int;

                // TODO this could be a constant Box* too
827
                CompilerVariable* froms = evalExpr(node->args[1], unw_info);
Travis Hance's avatar
Travis Hance committed
828 829
                ConcreteCompilerVariable* converted_froms = froms->makeConverted(emitter, froms->getBoxType());

830 831 832
                auto ast_str = ast_cast<AST_Str>(node->args[2]);
                assert(ast_str->str_type == AST_Str::STR);
                const std::string& module_name = ast_str->str_data;
Travis Hance's avatar
Travis Hance committed
833

Kevin Modzelewski's avatar
Kevin Modzelewski committed
834 835 836 837 838
                llvm::Value* imported = emitter.createCall(
                    unw_info, g.funcs.import,
                    { getConstantInt(level, g.i32), converted_froms->getValue(),
                      emitter.setType(embedRelocatablePtr(module_name.c_str(), g.i8_ptr), RefType::BORROWED),
                      getConstantInt(module_name.size(), g.i64) });
Kevin Modzelewski's avatar
Kevin Modzelewski committed
839
                emitter.setType(imported, RefType::OWNED);
840
                ConcreteCompilerVariable* v = new ConcreteCompilerVariable(UNKNOWN, imported);
Travis Hance's avatar
Travis Hance committed
841 842 843
                return v;
            }
            case AST_LangPrimitive::NONE: {
844
                return emitter.getNone();
Travis Hance's avatar
Travis Hance committed
845
            }
846 847 848 849
            case AST_LangPrimitive::NONZERO: {
                assert(node->args.size() == 1);
                CompilerVariable* obj = evalExpr(node->args[0], unw_info);

Kevin Modzelewski's avatar
Kevin Modzelewski committed
850
                CompilerVariable* rtn = obj->nonzero(emitter, getOpInfoForNode(node, unw_info));
851 852 853 854 855
                return rtn;
            }
            case AST_LangPrimitive::HASNEXT: {
                assert(node->args.size() == 1);
                CompilerVariable* obj = evalExpr(node->args[0], unw_info);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
856

Kevin Modzelewski's avatar
Kevin Modzelewski committed
857
                CompilerVariable* rtn = obj->hasnext(emitter, getOpInfoForNode(node, unw_info));
858
                return rtn;
859
            }
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
            case AST_LangPrimitive::SET_EXC_INFO: {
                assert(node->args.size() == 3);
                CompilerVariable* type = evalExpr(node->args[0], unw_info);
                CompilerVariable* value = evalExpr(node->args[1], unw_info);
                CompilerVariable* traceback = evalExpr(node->args[2], unw_info);

                auto* builder = emitter.getBuilder();

                llvm::Value* frame_info = irstate->getFrameInfoVar();
                llvm::Value* exc_info = builder->CreateConstInBoundsGEP2_32(frame_info, 0, 0);
                assert(exc_info->getType() == g.llvm_excinfo_type->getPointerTo());

                ConcreteCompilerVariable* converted_type = type->makeConverted(emitter, UNKNOWN);
                builder->CreateStore(converted_type->getValue(), builder->CreateConstInBoundsGEP2_32(exc_info, 0, 0));
                ConcreteCompilerVariable* converted_value = value->makeConverted(emitter, UNKNOWN);
                builder->CreateStore(converted_value->getValue(), builder->CreateConstInBoundsGEP2_32(exc_info, 0, 1));
                ConcreteCompilerVariable* converted_traceback = traceback->makeConverted(emitter, UNKNOWN);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
877 878
                builder->CreateStore(converted_traceback->getValue(),
                                     builder->CreateConstInBoundsGEP2_32(exc_info, 0, 2));
879

880
                return emitter.getNone();
881
            }
882 883 884 885 886 887 888 889 890
            case AST_LangPrimitive::UNCACHE_EXC_INFO: {
                assert(node->args.empty());

                auto* builder = emitter.getBuilder();

                llvm::Value* frame_info = irstate->getFrameInfoVar();
                llvm::Value* exc_info = builder->CreateConstInBoundsGEP2_32(frame_info, 0, 0);
                assert(exc_info->getType() == g.llvm_excinfo_type->getPointerTo());

891
                llvm::Constant* v = getNullPtr(g.llvm_value_type_ptr);
892 893 894 895
                builder->CreateStore(v, builder->CreateConstInBoundsGEP2_32(exc_info, 0, 0));
                builder->CreateStore(v, builder->CreateConstInBoundsGEP2_32(exc_info, 0, 1));
                builder->CreateStore(v, builder->CreateConstInBoundsGEP2_32(exc_info, 0, 2));

896
                return emitter.getNone();
897
            }
898 899 900 901 902 903 904 905
            case AST_LangPrimitive::PRINT_EXPR: {
                assert(node->args.size() == 1);

                CompilerVariable* obj = evalExpr(node->args[0], unw_info);
                ConcreteCompilerVariable* converted = obj->makeConverted(emitter, obj->getBoxType());

                emitter.createCall(unw_info, g.funcs.printExprHelper, converted->getValue());

906
                return emitter.getNone();
907
            }
908 909 910 911 912
            default:
                RELEASE_ASSERT(0, "%d", node->opcode);
        }
    }

913
    CompilerVariable* _evalBinExp(AST* node, CompilerVariable* left, CompilerVariable* right, AST_TYPE::AST_TYPE type,
914
                                  BinExpType exp_type, const UnwindInfo& unw_info) {
915 916 917
        assert(left);
        assert(right);

918 919
        if (type == AST_TYPE::In || type == AST_TYPE::NotIn) {
            CompilerVariable* r = right->contains(emitter, getOpInfoForNode(node, unw_info), left);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
920 921
            ASSERT(r->getType() == BOOL, "%s gave %s", right->getType()->debugName().c_str(),
                   r->getType()->debugName().c_str());
922 923 924 925 926 927 928 929 930 931
            if (type == AST_TYPE::NotIn) {
                ConcreteCompilerVariable* converted = r->makeConverted(emitter, BOOL);
                // TODO: would be faster to just do unboxBoolNegated
                llvm::Value* raw = i1FromBool(emitter, converted);
                raw = emitter.getBuilder()->CreateXor(raw, getConstantInt(1, g.i1));
                r = boolFromI1(emitter, raw);
            }
            return r;
        }

932
        return left->binexp(emitter, getOpInfoForNode(node, unw_info), right, type, exp_type);
933
    }
934

935
    CompilerVariable* evalBinOp(AST_BinOp* node, const UnwindInfo& unw_info) {
936 937
        CompilerVariable* left = evalExpr(node->left, unw_info);
        CompilerVariable* right = evalExpr(node->right, unw_info);
938

939
        assert(node->op_type != AST_TYPE::Is && node->op_type != AST_TYPE::IsNot && "not tested yet");
940

941
        CompilerVariable* rtn = this->_evalBinExp(node, left, right, node->op_type, BinOp, unw_info);
942 943
        return rtn;
    }
944

945
    CompilerVariable* evalAugBinOp(AST_AugBinOp* node, const UnwindInfo& unw_info) {
946 947
        CompilerVariable* left = evalExpr(node->left, unw_info);
        CompilerVariable* right = evalExpr(node->right, unw_info);
948

949
        assert(node->op_type != AST_TYPE::Is && node->op_type != AST_TYPE::IsNot && "not tested yet");
950

951
        CompilerVariable* rtn = this->_evalBinExp(node, left, right, node->op_type, AugBinOp, unw_info);
952 953
        return rtn;
    }
954

955
    CompilerVariable* evalCompare(AST_Compare* node, const UnwindInfo& unw_info) {
956
        RELEASE_ASSERT(node->ops.size() == 1, "");
957

958 959
        CompilerVariable* left = evalExpr(node->left, unw_info);
        CompilerVariable* right = evalExpr(node->comparators[0], unw_info);
960

961 962
        assert(left);
        assert(right);
963

964
        if (node->ops[0] == AST_TYPE::Is || node->ops[0] == AST_TYPE::IsNot) {
965
            return doIs(emitter, left, right, node->ops[0] == AST_TYPE::IsNot);
966 967
        }

968
        CompilerVariable* rtn = _evalBinExp(node, left, right, node->ops[0], Compare, unw_info);
969 970
        return rtn;
    }
971

972
    CompilerVariable* evalCall(AST_Call* node, const UnwindInfo& unw_info) {
973 974
        bool is_callattr;
        bool callattr_clsonly = false;
975
        InternedString attr;
976 977 978 979 980
        CompilerVariable* func;
        if (node->func->type == AST_TYPE::Attribute) {
            is_callattr = true;
            callattr_clsonly = false;
            AST_Attribute* attr_ast = ast_cast<AST_Attribute>(node->func);
981
            func = evalExpr(attr_ast->value, unw_info);
982
            attr = attr_ast->attr;
983 984 985 986
        } else if (node->func->type == AST_TYPE::ClsAttribute) {
            is_callattr = true;
            callattr_clsonly = true;
            AST_ClsAttribute* attr_ast = ast_cast<AST_ClsAttribute>(node->func);
987
            func = evalExpr(attr_ast->value, unw_info);
988
            attr = attr_ast->attr;
989 990
        } else {
            is_callattr = false;
991
            func = evalExpr(node->func, unw_info);
992 993
        }

994
        std::vector<CompilerVariable*> args;
995 996
        std::vector<BoxedString*>* keyword_names = NULL;
        if (node->keywords.size())
997
            keyword_names = getKeywordNameStorage(node);
998

999
        for (int i = 0; i < node->args.size(); i++) {
1000
            CompilerVariable* a = evalExpr(node->args[i], unw_info);
1001 1002
            args.push_back(a);
        }
1003

1004
        for (int i = 0; i < node->keywords.size(); i++) {
1005
            CompilerVariable* a = evalExpr(node->keywords[i]->value, unw_info);
1006 1007 1008 1009
            args.push_back(a);
        }

        if (node->starargs)
1010
            args.push_back(evalExpr(node->starargs, unw_info));
1011
        if (node->kwargs)
1012
            args.push_back(evalExpr(node->kwargs, unw_info));
1013 1014 1015 1016 1017

        struct ArgPassSpec argspec(node->args.size(), node->keywords.size(), node->starargs != NULL,
                                   node->kwargs != NULL);


1018 1019 1020 1021 1022
        // if (VERBOSITY("irgen") >= 1)
        //_addAnnotation("before_call");

        CompilerVariable* rtn;
        if (is_callattr) {
1023 1024
            CallattrFlags flags = {.cls_only = callattr_clsonly, .null_on_nonexistent = false, .argspec = argspec };
            rtn = func->callattr(emitter, getOpInfoForNode(node, unw_info), attr.getBox(), flags, args, keyword_names);
1025
        } else {
1026
            rtn = func->call(emitter, getOpInfoForNode(node, unw_info), argspec, args, keyword_names);
1027 1028
        }

1029 1030
        return rtn;
    }
1031

1032
    CompilerVariable* evalDict(AST_Dict* node, const UnwindInfo& unw_info) {
1033
        llvm::Value* v = emitter.getBuilder()->CreateCall(g.funcs.createDict);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1034
        emitter.setType(v, RefType::OWNED);
1035
        ConcreteCompilerVariable* rtn = new ConcreteCompilerVariable(DICT, v);
1036
        if (node->keys.size()) {
1037
            static BoxedString* setitem_str = getStaticString("__setitem__");
1038
            CompilerVariable* setitem = rtn->getattr(emitter, getEmptyOpInfo(unw_info), setitem_str, true);
1039
            for (int i = 0; i < node->keys.size(); i++) {
1040 1041
                CompilerVariable* key = evalExpr(node->keys[i], unw_info);
                CompilerVariable* value = evalExpr(node->values[i], unw_info);
1042 1043 1044 1045 1046 1047
                assert(key);
                assert(value);

                std::vector<CompilerVariable*> args;
                args.push_back(key);
                args.push_back(value);
1048
                // TODO should use callattr
1049
                CompilerVariable* rtn = setitem->call(emitter, getEmptyOpInfo(unw_info), ArgPassSpec(2), args, NULL);
1050
            }
1051 1052 1053
        }
        return rtn;
    }
1054

1055 1056 1057
    void _addAnnotation(const char* message) {
        llvm::Instruction* inst = emitter.getBuilder()->CreateCall(
            llvm::Intrinsic::getDeclaration(g.cur_module, llvm::Intrinsic::donothing));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1058
        llvm::Metadata* md_vals[] = { llvm::ConstantAsMetadata::get(getConstantInt(0)) };
1059 1060 1061
        llvm::MDNode* mdnode = llvm::MDNode::get(g.context, md_vals);
        inst->setMetadata(message, mdnode);
    }
1062

1063
    CompilerVariable* evalIndex(AST_Index* node, const UnwindInfo& unw_info) { return evalExpr(node->value, unw_info); }
1064

1065
    CompilerVariable* evalLambda(AST_Lambda* node, const UnwindInfo& unw_info) {
1066 1067 1068
        AST_Return* expr = new AST_Return();
        expr->value = node->body;

1069
        std::vector<AST_stmt*> body = { expr };
1070
        CompilerVariable* func = _createFunction(node, unw_info, node->args, body);
1071 1072 1073 1074 1075 1076
        ConcreteCompilerVariable* converted = func->makeConverted(emitter, func->getBoxType());

        return converted;
    }


1077
    CompilerVariable* evalList(AST_List* node, const UnwindInfo& unw_info) {
1078 1079
        std::vector<CompilerVariable*> elts;
        for (int i = 0; i < node->elts.size(); i++) {
1080
            CompilerVariable* value = evalExpr(node->elts[i], unw_info);
1081
            elts.push_back(value);
1082 1083
        }

1084
        llvm::Value* v = emitter.getBuilder()->CreateCall(g.funcs.createList);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1085
        emitter.setType(v, RefType::OWNED);
1086
        ConcreteCompilerVariable* rtn = new ConcreteCompilerVariable(LIST, v);
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096

        llvm::Value* f = g.funcs.listAppendInternal;
        llvm::Value* bitcast = emitter.getBuilder()->CreateBitCast(
            v, *llvm::cast<llvm::FunctionType>(llvm::cast<llvm::PointerType>(f->getType())->getElementType())
                    ->param_begin());

        for (int i = 0; i < node->elts.size(); i++) {
            CompilerVariable* elt = elts[i];
            ConcreteCompilerVariable* converted = elt->makeConverted(emitter, elt->getBoxType());

1097
            emitter.createCall2(unw_info, f, bitcast, converted->getValue());
1098
        }
1099 1100
        return rtn;
    }
1101

Dong-hee Na's avatar
Dong-hee Na committed
1102 1103
    ConcreteCompilerVariable* getEllipsis() {
        llvm::Constant* ellipsis = embedRelocatablePtr(Ellipsis, g.llvm_value_type_ptr, "cEllipsis");
1104
        emitter.setType(ellipsis, RefType::BORROWED);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1105
        auto ellipsis_cls = Ellipsis->cls;
1106
        return new ConcreteCompilerVariable(typeFromClass(ellipsis_cls), ellipsis);
Dong-hee Na's avatar
Dong-hee Na committed
1107
    }
1108

1109
    llvm::Constant* embedParentModulePtr() {
1110
        BoxedModule* parent_module = irstate->getSourceInfo()->parent_module;
1111 1112 1113
        auto r = embedRelocatablePtr(parent_module, g.llvm_value_type_ptr, "cParentModule");
        emitter.setType(r, RefType::BORROWED);
        return r;
1114 1115
    }

1116
    ConcreteCompilerVariable* _getGlobal(AST_Name* node, const UnwindInfo& unw_info) {
1117
        if (node->id.s() == "None")
1118
            return emitter.getNone();
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1119

1120
        bool do_patchpoint = ENABLE_ICGETGLOBALS;
1121
        if (do_patchpoint) {
1122
            ICSetupInfo* pp = createGetGlobalIC(getOpInfoForNode(node, unw_info).getTypeRecorder());
1123 1124

            std::vector<llvm::Value*> llvm_args;
1125
            llvm_args.push_back(irstate->getGlobals());
1126 1127
            llvm_args.push_back(emitter.setType(embedRelocatablePtr(node->id.getBox(), g.llvm_boxedstring_type_ptr),
                                                RefType::BORROWED));
1128

1129
            llvm::Value* uncasted = emitter.createIC(pp, (void*)pyston::getGlobal, llvm_args, unw_info);
1130
            llvm::Value* r = emitter.getBuilder()->CreateIntToPtr(uncasted, g.llvm_value_type_ptr);
1131
            emitter.setType(r, RefType::OWNED);
1132
            return new ConcreteCompilerVariable(UNKNOWN, r);
1133
        } else {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1134 1135 1136 1137
            llvm::Value* r = emitter.createCall2(
                unw_info, g.funcs.getGlobal, irstate->getGlobals(),
                emitter.setType(embedRelocatablePtr(node->id.getBox(), g.llvm_boxedstring_type_ptr),
                                RefType::BORROWED));
1138
            emitter.setType(r, RefType::OWNED);
1139
            return new ConcreteCompilerVariable(UNKNOWN, r);
1140 1141 1142
        }
    }

1143
    CompilerVariable* evalName(AST_Name* node, const UnwindInfo& unw_info) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1144 1145
        auto scope_info = irstate->getScopeInfo();

1146
        bool is_kill = irstate->getLiveness()->isKill(node, myblock);
1147
        assert(!is_kill || node->id.s()[0] == '#');
1148

Travis Hance's avatar
Travis Hance committed
1149 1150
        ScopeInfo::VarScopeType vst = scope_info->getScopeTypeOfName(node->id);
        if (vst == ScopeInfo::VarScopeType::GLOBAL) {
1151
            assert(!is_kill);
1152
            return _getGlobal(node, unw_info);
Travis Hance's avatar
Travis Hance committed
1153
        } else if (vst == ScopeInfo::VarScopeType::DEREF) {
1154
            assert(!is_kill);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1155 1156
            assert(scope_info->takesClosure());

Travis Hance's avatar
Travis Hance committed
1157
            // This is the information on how to look up the variable in the closure object.
Travis Hance's avatar
Travis Hance committed
1158 1159
            DerefInfo deref_info = scope_info->getDerefInfo(node->id);

Travis Hance's avatar
Travis Hance committed
1160 1161 1162 1163 1164 1165 1166
            // This code is basically:
            // closure = created_closure;
            // closure = closure->parent;
            // [...]
            // closure = closure->parent;
            // closure->elts[deref_info.offset]
            // Where the parent lookup is done `deref_info.num_parents_from_passed_closure` times
1167
            CompilerVariable* closure = symbol_table[internString(PASSED_CLOSURE_NAME)];
Travis Hance's avatar
Travis Hance committed
1168 1169
            llvm::Value* closureValue = closure->makeConverted(emitter, CLOSURE)->getValue();
            for (int i = 0; i < deref_info.num_parents_from_passed_closure; i++) {
Travis Hance's avatar
Travis Hance committed
1170
                closureValue = emitter.getBuilder()->CreateLoad(getClosureParentGep(emitter, closureValue));
Travis Hance's avatar
Travis Hance committed
1171
            }
Travis Hance's avatar
Travis Hance committed
1172 1173
            llvm::Value* lookupResult
                = emitter.getBuilder()->CreateLoad(getClosureElementGep(emitter, closureValue, deref_info.offset));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1174

Travis Hance's avatar
Travis Hance committed
1175 1176
            // If the value is NULL, the variable is undefined.
            // Create a branch on if the value is NULL.
Travis Hance's avatar
Travis Hance committed
1177 1178 1179 1180 1181 1182 1183
            llvm::BasicBlock* success_bb
                = llvm::BasicBlock::Create(g.context, "deref_defined", irstate->getLLVMFunction());
            success_bb->moveAfter(curblock);
            llvm::BasicBlock* fail_bb
                = llvm::BasicBlock::Create(g.context, "deref_undefined", irstate->getLLVMFunction());

            llvm::Value* check_val
1184
                = emitter.getBuilder()->CreateICmpEQ(lookupResult, getNullPtr(g.llvm_value_type_ptr));
Travis Hance's avatar
Travis Hance committed
1185 1186
            llvm::BranchInst* non_null_check = emitter.getBuilder()->CreateCondBr(check_val, fail_bb, success_bb);

Travis Hance's avatar
Travis Hance committed
1187
            // Case that it is undefined: call the assert fail function.
Travis Hance's avatar
Travis Hance committed
1188 1189 1190 1191
            curblock = fail_bb;
            emitter.getBuilder()->SetInsertPoint(curblock);

            llvm::CallSite call = emitter.createCall(unw_info, g.funcs.assertFailDerefNameDefined,
1192
                                                     embedRelocatablePtr(node->id.c_str(), g.i8_ptr));
Travis Hance's avatar
Travis Hance committed
1193 1194 1195
            call.setDoesNotReturn();
            emitter.getBuilder()->CreateUnreachable();

Travis Hance's avatar
Travis Hance committed
1196
            // Case that it is defined: carry on in with the retrieved value.
Travis Hance's avatar
Travis Hance committed
1197 1198
            curblock = success_bb;
            emitter.getBuilder()->SetInsertPoint(curblock);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1199

1200
            return new ConcreteCompilerVariable(UNKNOWN, lookupResult);
Travis Hance's avatar
exec  
Travis Hance committed
1201 1202
        } else if (vst == ScopeInfo::VarScopeType::NAME) {
            llvm::Value* boxedLocals = irstate->getBoxedLocalsVar();
1203
            llvm::Value* attr = embedRelocatablePtr(node->id.getBox(), g.llvm_boxedstring_type_ptr);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1204
            emitter.setType(attr, RefType::BORROWED);
1205
            llvm::Value* module = irstate->getGlobals();
Travis Hance's avatar
exec  
Travis Hance committed
1206
            llvm::Value* r = emitter.createCall3(unw_info, g.funcs.boxedLocalsGet, boxedLocals, attr, module);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1207
            emitter.setType(r, RefType::OWNED);
1208
            return new ConcreteCompilerVariable(UNKNOWN, r);
1209
        } else {
1210
            // vst is one of {FAST, CLOSURE}
1211 1212 1213
            if (symbol_table.find(node->id) == symbol_table.end()) {
                // TODO should mark as DEAD here, though we won't end up setting all the names appropriately
                // state = DEAD;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1214
                llvm::CallSite call = emitter.createCall(
1215
                    unw_info, g.funcs.assertNameDefined,
1216
                    { getConstantInt(0, g.i1), embedRelocatablePtr(node->id.c_str(), g.i8_ptr),
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1217 1218
                      emitter.setType(embedRelocatablePtr(UnboundLocalError, g.llvm_class_type_ptr), RefType::BORROWED),
                      getConstantInt(true, g.i1) });
1219
                call.setDoesNotReturn();
1220 1221
                return undefVariable();
            }
1222

1223
            InternedString defined_name = getIsDefinedName(node->id);
1224 1225
            ConcreteCompilerVariable* is_defined_var
                = static_cast<ConcreteCompilerVariable*>(_getFake(defined_name, true));
1226

1227
            if (is_defined_var) {
1228 1229 1230
                emitter.createCall(
                    unw_info, g.funcs.assertNameDefined,
                    { i1FromBool(emitter, is_defined_var), embedRelocatablePtr(node->id.c_str(), g.i8_ptr),
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1231 1232
                      emitter.setType(embedRelocatablePtr(UnboundLocalError, g.llvm_class_type_ptr), RefType::BORROWED),
                      getConstantInt(true, g.i1) });
1233 1234 1235

                // At this point we know the name must be defined (otherwise the assert would have fired):
                _popFake(defined_name);
1236
            }
1237 1238

            CompilerVariable* rtn = symbol_table[node->id];
1239 1240
            if (is_kill)
                symbol_table.erase(node->id);
1241
            return rtn;
1242
        }
1243
    }
1244

1245
    CompilerVariable* evalNum(AST_Num* node, const UnwindInfo& unw_info) {
1246 1247 1248
        // We can operate on ints and floats unboxed, so don't box those at first;
        // complex and long's have to get boxed so box them immediately.
        if (node->num_type == AST_Num::INT) {
1249
            return makeInt(node->n_int);
1250
        } else if (node->num_type == AST_Num::FLOAT) {
1251
            return makeFloat(node->n_float);
1252
        } else if (node->num_type == AST_Num::COMPLEX) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1253 1254
            return makePureImaginary(emitter,
                                     irstate->getSourceInfo()->parent_module->getPureImaginaryConstant(node->n_float));
1255
        } else {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1256
            return makeLong(emitter, irstate->getSourceInfo()->parent_module->getLongConstant(node->n_long));
1257
        }
1258
    }
1259

1260
    CompilerVariable* evalRepr(AST_Repr* node, const UnwindInfo& unw_info) {
1261
        CompilerVariable* var = evalExpr(node->value, unw_info);
1262
        ConcreteCompilerVariable* cvar = var->makeConverted(emitter, var->getBoxType());
Marius Wachtler's avatar
Marius Wachtler committed
1263

1264
        std::vector<llvm::Value*> args{ cvar->getValue() };
1265
        llvm::Value* rtn = emitter.createCall(unw_info, g.funcs.repr, args);
1266
        rtn = emitter.getBuilder()->CreateBitCast(rtn, g.llvm_value_type_ptr);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1267
        emitter.setType(rtn, RefType::OWNED);
Marius Wachtler's avatar
Marius Wachtler committed
1268

1269
        return new ConcreteCompilerVariable(STR, rtn);
1270
    }
Marius Wachtler's avatar
Marius Wachtler committed
1271

1272
    CompilerVariable* evalSet(AST_Set* node, const UnwindInfo& unw_info) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1273 1274
        std::vector<CompilerVariable*> elts;
        for (int i = 0; i < node->elts.size(); i++) {
1275
            CompilerVariable* value = evalExpr(node->elts[i], unw_info);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1276 1277 1278 1279
            elts.push_back(value);
        }

        llvm::Value* v = emitter.getBuilder()->CreateCall(g.funcs.createSet);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1280
        emitter.setType(v, RefType::OWNED);
1281
        ConcreteCompilerVariable* rtn = new ConcreteCompilerVariable(SET, v);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1282

1283
        static BoxedString* add_str = getStaticString("add");
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1284 1285 1286

        for (int i = 0; i < node->elts.size(); i++) {
            CompilerVariable* elt = elts[i];
1287 1288 1289
            CallattrFlags flags = {.cls_only = true, .null_on_nonexistent = false, .argspec = ArgPassSpec(1) };
            CompilerVariable* r
                = rtn->callattr(emitter, getOpInfoForNode(node, unw_info), add_str, flags, { elt }, NULL);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1290 1291 1292 1293 1294
        }

        return rtn;
    }

1295
    CompilerVariable* evalSlice(AST_Slice* node, const UnwindInfo& unw_info) {
1296
        CompilerVariable* start, *stop, *step;
1297 1298 1299 1300 1301
        start = node->lower ? evalExpr(node->lower, unw_info) : NULL;
        stop = node->upper ? evalExpr(node->upper, unw_info) : NULL;
        step = node->step ? evalExpr(node->step, unw_info) : NULL;

        return makeSlice(start, stop, step);
1302
    }
1303

1304
    CompilerVariable* evalExtSlice(AST_ExtSlice* node, const UnwindInfo& unw_info) {
1305 1306
        std::vector<CompilerVariable*> elts;
        for (auto* e : node->dims) {
1307
            elts.push_back(evalSlice(e, unw_info));
1308 1309 1310 1311 1312 1313
        }

        CompilerVariable* rtn = makeTuple(elts);
        return rtn;
    }

1314
    CompilerVariable* evalStr(AST_Str* node, const UnwindInfo& unw_info) {
1315
        if (node->str_type == AST_Str::STR) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1316 1317 1318
            llvm::Value* rtn
                = embedRelocatablePtr(irstate->getSourceInfo()->parent_module->getStringConstant(node->str_data, true),
                                      g.llvm_value_type_ptr);
1319
            emitter.setType(rtn, RefType::BORROWED);
1320

1321
            return new ConcreteCompilerVariable(STR, rtn);
1322
        } else if (node->str_type == AST_Str::UNICODE) {
1323 1324
            llvm::Value* rtn = embedRelocatablePtr(
                irstate->getSourceInfo()->parent_module->getUnicodeConstant(node->str_data), g.llvm_value_type_ptr);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1325
            emitter.setType(rtn, RefType::BORROWED);
1326

1327
            return new ConcreteCompilerVariable(typeFromClass(unicode_cls), rtn);
1328 1329 1330 1331
        } else {
            RELEASE_ASSERT(0, "%d", node->str_type);
        }
    }
1332

1333
    CompilerVariable* evalSubscript(AST_Subscript* node, const UnwindInfo& unw_info) {
1334
        CompilerVariable* value = evalExpr(node->value, unw_info);
1335
        CompilerVariable* slice = evalSlice(node->slice, unw_info);
1336

1337
        CompilerVariable* rtn = value->getitem(emitter, getOpInfoForNode(node, unw_info), slice);
1338 1339
        return rtn;
    }
1340

1341
    CompilerVariable* evalTuple(AST_Tuple* node, const UnwindInfo& unw_info) {
1342 1343
        std::vector<CompilerVariable*> elts;
        for (int i = 0; i < node->elts.size(); i++) {
1344
            CompilerVariable* value = evalExpr(node->elts[i], unw_info);
1345 1346
            elts.push_back(value);
        }
1347

1348 1349 1350
        CompilerVariable* rtn = makeTuple(elts);
        return rtn;
    }
1351

1352
    CompilerVariable* evalUnaryOp(AST_UnaryOp* node, const UnwindInfo& unw_info) {
1353
        CompilerVariable* operand = evalExpr(node->operand, unw_info);
1354

1355
        if (node->op_type == AST_TYPE::Not) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1356
            CompilerVariable* rtn = operand->nonzero(emitter, getOpInfoForNode(node, unw_info));
1357

1358
            assert(rtn->getType() == BOOL);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1359
            llvm::Value* v = i1FromBool(emitter, static_cast<ConcreteCompilerVariable*>(rtn));
1360 1361
            assert(v->getType() == g.i1);

1362
            llvm::Value* negated = emitter.getBuilder()->CreateNot(v);
1363
            return boolFromI1(emitter, negated);
1364
        } else {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1365
            CompilerVariable* rtn = operand->unaryop(emitter, getOpInfoForNode(node, unw_info), node->op_type);
1366
            return rtn;
1367
        }
1368
    }
1369

1370
    CompilerVariable* evalYield(AST_Yield* node, const UnwindInfo& unw_info) {
1371 1372
        CompilerVariable* generator = symbol_table[internString(PASSED_GENERATOR_NAME)];
        assert(generator);
1373 1374 1375
        ConcreteCompilerVariable* convertedGenerator = generator->makeConverted(emitter, generator->getBoxType());


1376
        CompilerVariable* value = node->value ? evalExpr(node->value, unw_info) : emitter.getNone();
1377 1378
        ConcreteCompilerVariable* convertedValue = value->makeConverted(emitter, value->getBoxType());

1379
        llvm::Value* rtn
1380
            = emitter.createCall2(unw_info, g.funcs.yield, convertedGenerator->getValue(), convertedValue->getValue());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1381
        emitter.setType(rtn, RefType::OWNED);
1382

1383
        return new ConcreteCompilerVariable(UNKNOWN, rtn);
1384 1385
    }

1386
    CompilerVariable* evalMakeClass(AST_MakeClass* mkclass, const UnwindInfo& unw_info) {
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
        assert(mkclass->type == AST_TYPE::MakeClass && mkclass->class_def->type == AST_TYPE::ClassDef);
        AST_ClassDef* node = mkclass->class_def;
        ScopeInfo* scope_info = irstate->getScopeInfoForNode(node);
        assert(scope_info);

        std::vector<CompilerVariable*> bases;
        for (auto b : node->bases) {
            CompilerVariable* base = evalExpr(b, unw_info);
            bases.push_back(base);
        }

        CompilerVariable* _bases_tuple = makeTuple(bases);
        ConcreteCompilerVariable* bases_tuple = _bases_tuple->makeConverted(emitter, _bases_tuple->getBoxType());

        std::vector<CompilerVariable*> decorators;
        for (auto d : node->decorator_list) {
            decorators.push_back(evalExpr(d, unw_info));
        }

1406
        FunctionMetadata* md = wrapFunction(node, nullptr, node->body, irstate->getSourceInfo());
1407 1408 1409 1410

        // TODO duplication with _createFunction:
        CompilerVariable* created_closure = NULL;
        if (scope_info->takesClosure()) {
1411 1412 1413 1414 1415 1416
            if (irstate->getScopeInfo()->createsClosure()) {
                created_closure = symbol_table[internString(CREATED_CLOSURE_NAME)];
            } else {
                assert(irstate->getScopeInfo()->passesThroughClosure());
                created_closure = symbol_table[internString(PASSED_CLOSURE_NAME)];
            }
1417 1418 1419 1420 1421 1422 1423
            assert(created_closure);
        }

        // TODO kind of silly to create the function just to usually-delete it afterwards;
        // one reason to do this is to pass the closure through if necessary,
        // but since the classdef can't create its own closure, shouldn't need to explicitly
        // create that scope to pass the closure through.
1424
        assert(irstate->getSourceInfo()->scoping->areGlobalsFromModule());
1425
        CompilerVariable* func = makeFunction(emitter, md, created_closure, irstate->getGlobalsIfCustom(), {});
1426 1427 1428 1429 1430

        CompilerVariable* attr_dict = func->call(emitter, getEmptyOpInfo(unw_info), ArgPassSpec(0), {}, NULL);

        ConcreteCompilerVariable* converted_attr_dict = attr_dict->makeConverted(emitter, attr_dict->getBoxType());

1431
        llvm::Value* classobj = emitter.createCall3(
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1432 1433
            unw_info, g.funcs.createUserClass,
            emitter.setType(embedRelocatablePtr(node->name.getBox(), g.llvm_boxedstring_type_ptr), RefType::BORROWED),
1434
            bases_tuple->getValue(), converted_attr_dict->getValue());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1435
        emitter.setType(classobj, RefType::OWNED);
1436 1437

        // Note: createuserClass is free to manufacture non-class objects
1438
        CompilerVariable* cls = new ConcreteCompilerVariable(UNKNOWN, classobj);
1439 1440 1441 1442 1443 1444 1445 1446

        for (int i = decorators.size() - 1; i >= 0; i--) {
            cls = decorators[i]->call(emitter, getOpInfoForNode(node, unw_info), ArgPassSpec(1), { cls }, NULL);
        }

        return cls;
    }

1447
    CompilerVariable* _createFunction(AST* node, const UnwindInfo& unw_info, AST_arguments* args,
1448
                                      const std::vector<AST_stmt*>& body) {
1449
        FunctionMetadata* md = wrapFunction(node, args, body, irstate->getSourceInfo());
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471

        std::vector<ConcreteCompilerVariable*> defaults;
        for (auto d : args->defaults) {
            CompilerVariable* e = evalExpr(d, unw_info);
            ConcreteCompilerVariable* converted = e->makeConverted(emitter, e->getBoxType());
            defaults.push_back(converted);
        }

        CompilerVariable* created_closure = NULL;

        bool takes_closure;
        // Optimization: when compiling a module, it's nice to not have to run analyses into the
        // entire module's source code.
        // If we call getScopeInfoForNode, that will trigger an analysis of that function tree,
        // but we're only using it here to figure out if that function takes a closure.
        // Top level functions never take a closure, so we can skip the analysis.
        if (irstate->getSourceInfo()->ast->type == AST_TYPE::Module)
            takes_closure = false;
        else {
            takes_closure = irstate->getScopeInfoForNode(node)->takesClosure();
        }

1472
        bool is_generator = md->source->is_generator;
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483

        if (takes_closure) {
            if (irstate->getScopeInfo()->createsClosure()) {
                created_closure = symbol_table[internString(CREATED_CLOSURE_NAME)];
            } else {
                assert(irstate->getScopeInfo()->passesThroughClosure());
                created_closure = symbol_table[internString(PASSED_CLOSURE_NAME)];
            }
            assert(created_closure);
        }

1484
        CompilerVariable* func = makeFunction(emitter, md, created_closure, irstate->getGlobalsIfCustom(), defaults);
1485 1486 1487 1488

        return func;
    }

1489
    CompilerVariable* evalMakeFunction(AST_MakeFunction* mkfn, const UnwindInfo& unw_info) {
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
        AST_FunctionDef* node = mkfn->function_def;
        std::vector<CompilerVariable*> decorators;
        for (auto d : node->decorator_list) {
            decorators.push_back(evalExpr(d, unw_info));
        }

        CompilerVariable* func = _createFunction(node, unw_info, node->args, node->body);

        for (int i = decorators.size() - 1; i >= 0; i--) {
            func = decorators[i]->call(emitter, getOpInfoForNode(node, unw_info), ArgPassSpec(1), { func }, NULL);
        }

        return func;
    }

1505
    // Note: the behavior of this function must match type_analysis.cpp:unboxedType()
1506
    CompilerVariable* unboxVar(ConcreteCompilerType* t, llvm::Value* v) {
1507
        if (t == BOXED_INT) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1508
            return makeUnboxedInt(emitter, v);
1509
        }
1510
        if (t == BOXED_FLOAT) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1511
            return makeUnboxedFloat(emitter, v);
1512
        }
1513 1514
        if (t == BOXED_BOOL) {
            llvm::Value* unboxed = emitter.getBuilder()->CreateCall(g.funcs.unboxBool, v);
1515
            return boolFromI1(emitter, unboxed);
1516
        }
1517
        return new ConcreteCompilerVariable(t, v);
1518
    }
1519

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    template <typename AstType>
    CompilerVariable* evalSliceExprPost(AstType* node, const UnwindInfo& unw_info, CompilerVariable* rtn) {
        assert(rtn);

        // Out-guarding:
        BoxedClass* speculated_class = types->speculatedExprClass(node);
        if (speculated_class != NULL) {
            assert(rtn);

            ConcreteCompilerType* speculated_type = typeFromClass(speculated_class);
            if (VERBOSITY("irgen") >= 2) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1531
                printf("Speculating that %s is actually %s, at ", rtn->getType()->debugName().c_str(),
1532
                       speculated_type->debugName().c_str());
1533 1534 1535
                fflush(stdout);
                print_ast(node);
                llvm::outs().flush();
1536 1537 1538
                printf("\n");
            }

1539
#ifndef NDEBUG
1540 1541
            // That's not really a speculation.... could potentially handle this here, but
            // I think it's better to just not generate bad speculations:
1542 1543 1544 1545 1546 1547 1548 1549 1550
            if (rtn->canConvertTo(speculated_type)) {
                auto source = irstate->getSourceInfo();
                printf("On %s:%d, function %s:\n", source->getFn()->c_str(), source->body[0]->lineno,
                       source->getName()->c_str());
                irstate->getSourceInfo()->cfg->print();
            }
            RELEASE_ASSERT(!rtn->canConvertTo(speculated_type), "%s %s", rtn->getType()->debugName().c_str(),
                           speculated_type->debugName().c_str());
#endif
1551 1552 1553 1554 1555 1556 1557

            ConcreteCompilerVariable* old_rtn = rtn->makeConverted(emitter, UNKNOWN);

            llvm::Value* guard_check = old_rtn->makeClassCheck(emitter, speculated_class);
            assert(guard_check->getType() == g.i1);
            createExprTypeGuard(guard_check, node, old_rtn->getValue(), unw_info.current_stmt);

1558
            rtn = unboxVar(speculated_type, old_rtn->getValue());
1559 1560 1561
        }

        assert(rtn);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1562
        assert(rtn->getType()->isUsable());
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578

        return rtn;
    }

    CompilerVariable* evalSlice(AST_slice* node, const UnwindInfo& unw_info) {
        // printf("%d expr: %d\n", node->type, node->lineno);
        if (node->lineno) {
            emitter.getBuilder()->SetCurrentDebugLocation(
                llvm::DebugLoc::get(node->lineno, 0, irstate->getFuncDbgInfo()));
        }

        CompilerVariable* rtn = NULL;
        switch (node->type) {
            case AST_TYPE::ExtSlice:
                rtn = evalExtSlice(ast_cast<AST_ExtSlice>(node), unw_info);
                break;
Dong-hee Na's avatar
Dong-hee Na committed
1579 1580 1581
            case AST_TYPE::Ellipsis:
                rtn = getEllipsis();
                break;
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
            case AST_TYPE::Index:
                rtn = evalIndex(ast_cast<AST_Index>(node), unw_info);
                break;
            case AST_TYPE::Slice:
                rtn = evalSlice(ast_cast<AST_Slice>(node), unw_info);
                break;
            default:
                printf("Unhandled slice type: %d (irgenerator.cpp:" STRINGIFY(__LINE__) ")\n", node->type);
                exit(1);
        }
        return evalSliceExprPost(node, unw_info, rtn);
    }

1595
    CompilerVariable* evalExpr(AST_expr* node, const UnwindInfo& unw_info) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1596
        // printf("%d expr: %d\n", node->type, node->lineno);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1597
        if (node->lineno) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1598 1599
            emitter.getBuilder()->SetCurrentDebugLocation(
                llvm::DebugLoc::get(node->lineno, 0, irstate->getFuncDbgInfo()));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1600
        }
1601

1602
        CompilerVariable* rtn = NULL;
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
        switch (node->type) {
            case AST_TYPE::Attribute:
                rtn = evalAttribute(ast_cast<AST_Attribute>(node), unw_info);
                break;
            case AST_TYPE::AugBinOp:
                rtn = evalAugBinOp(ast_cast<AST_AugBinOp>(node), unw_info);
                break;
            case AST_TYPE::BinOp:
                rtn = evalBinOp(ast_cast<AST_BinOp>(node), unw_info);
                break;
            case AST_TYPE::Call:
                rtn = evalCall(ast_cast<AST_Call>(node), unw_info);
                break;
            case AST_TYPE::Compare:
                rtn = evalCompare(ast_cast<AST_Compare>(node), unw_info);
                break;
            case AST_TYPE::Dict:
                rtn = evalDict(ast_cast<AST_Dict>(node), unw_info);
                break;
            case AST_TYPE::Lambda:
                rtn = evalLambda(ast_cast<AST_Lambda>(node), unw_info);
                break;
            case AST_TYPE::List:
                rtn = evalList(ast_cast<AST_List>(node), unw_info);
                break;
            case AST_TYPE::Name:
                rtn = evalName(ast_cast<AST_Name>(node), unw_info);
                break;
            case AST_TYPE::Num:
                rtn = evalNum(ast_cast<AST_Num>(node), unw_info);
                break;
            case AST_TYPE::Repr:
                rtn = evalRepr(ast_cast<AST_Repr>(node), unw_info);
                break;
            case AST_TYPE::Set:
                rtn = evalSet(ast_cast<AST_Set>(node), unw_info);
                break;
            case AST_TYPE::Str:
                rtn = evalStr(ast_cast<AST_Str>(node), unw_info);
                break;
            case AST_TYPE::Subscript:
                rtn = evalSubscript(ast_cast<AST_Subscript>(node), unw_info);
                break;
            case AST_TYPE::Tuple:
                rtn = evalTuple(ast_cast<AST_Tuple>(node), unw_info);
                break;
            case AST_TYPE::UnaryOp:
                rtn = evalUnaryOp(ast_cast<AST_UnaryOp>(node), unw_info);
                break;
            case AST_TYPE::Yield:
                rtn = evalYield(ast_cast<AST_Yield>(node), unw_info);
                break;
1655

1656
            // pseudo-nodes
1657 1658 1659 1660 1661 1662
            case AST_TYPE::ClsAttribute:
                rtn = evalClsAttribute(ast_cast<AST_ClsAttribute>(node), unw_info);
                break;
            case AST_TYPE::LangPrimitive:
                rtn = evalLangPrimitive(ast_cast<AST_LangPrimitive>(node), unw_info);
                break;
1663 1664 1665 1666 1667 1668
            case AST_TYPE::MakeClass:
                rtn = evalMakeClass(ast_cast<AST_MakeClass>(node), unw_info);
                break;
            case AST_TYPE::MakeFunction:
                rtn = evalMakeFunction(ast_cast<AST_MakeFunction>(node), unw_info);
                break;
1669 1670 1671 1672
            default:
                printf("Unhandled expr type: %d (irgenerator.cpp:" STRINGIFY(__LINE__) ")\n", node->type);
                exit(1);
        }
1673
        return evalSliceExprPost(node, unw_info, rtn);
1674
    }
1675

1676
    void _setFake(InternedString name, CompilerVariable* val) {
1677
        assert(name.s()[0] == '!');
1678 1679 1680 1681
        CompilerVariable*& cur = symbol_table[name];
        assert(cur == NULL);
        cur = val;
    }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1682

1683 1684 1685 1686 1687 1688
    // whether a Python variable FOO might be undefined or not is determined by whether the corresponding is_defined_FOO
    // variable is present in our symbol table. If it is, then it *might* be undefined. If it isn't, then it either is
    // definitely defined, or definitely isn't.
    //
    // to check whether a variable is in our symbol table, call _getFake with allow_missing = true and check whether the
    // result is NULL.
1689
    CompilerVariable* _getFake(InternedString name, bool allow_missing = false) {
1690
        assert(name.s()[0] == '!');
1691 1692 1693 1694 1695 1696
        auto it = symbol_table.find(name);
        if (it == symbol_table.end()) {
            assert(allow_missing);
            return NULL;
        }
        return it->second;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1697
    }
1698

1699
    CompilerVariable* _popFake(InternedString name, bool allow_missing = false) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1700
        CompilerVariable* rtn = _getFake(name, allow_missing);
1701
        symbol_table.erase(name);
1702 1703
        if (!allow_missing)
            assert(rtn != NULL);
1704 1705 1706
        return rtn;
    }

1707
    // only updates symbol_table if we're *not* setting a global
1708
    void _doSet(InternedString name, CompilerVariable* val, const UnwindInfo& unw_info) {
1709 1710
        assert(name.s() != "None");
        assert(name.s() != FRAME_INFO_PTR_NAME);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1711
        assert(val->getType()->isUsable());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1712 1713

        auto scope_info = irstate->getScopeInfo();
Travis Hance's avatar
exec  
Travis Hance committed
1714 1715
        ScopeInfo::VarScopeType vst = scope_info->getScopeTypeOfName(name);
        assert(vst != ScopeInfo::VarScopeType::DEREF);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1716

Travis Hance's avatar
exec  
Travis Hance committed
1717
        if (vst == ScopeInfo::VarScopeType::GLOBAL) {
1718 1719
            if (irstate->getSourceInfo()->scoping->areGlobalsFromModule()) {
                auto parent_module = llvm::ConstantExpr::getPointerCast(embedParentModulePtr(), g.llvm_value_type_ptr);
1720
                ConcreteCompilerVariable* module = new ConcreteCompilerVariable(MODULE, parent_module);
1721 1722 1723
                module->setattr(emitter, getEmptyOpInfo(unw_info), name.getBox(), val);
            } else {
                auto converted = val->makeConverted(emitter, val->getBoxType());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1724 1725 1726 1727
                emitter.createCall3(
                    unw_info, g.funcs.setGlobal, irstate->getGlobals(),
                    emitter.setType(embedRelocatablePtr(name.getBox(), g.llvm_boxedstring_type_ptr), RefType::BORROWED),
                    converted->getValue());
1728
            }
Travis Hance's avatar
exec  
Travis Hance committed
1729 1730 1731
        } else if (vst == ScopeInfo::VarScopeType::NAME) {
            // TODO inefficient
            llvm::Value* boxedLocals = irstate->getBoxedLocalsVar();
1732
            llvm::Value* attr = embedRelocatablePtr(name.getBox(), g.llvm_boxedstring_type_ptr);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1733
            emitter.setType(attr, RefType::BORROWED);
Travis Hance's avatar
exec  
Travis Hance committed
1734 1735
            emitter.createCall3(unw_info, g.funcs.boxedLocalsSet, boxedLocals, attr,
                                val->makeConverted(emitter, UNKNOWN)->getValue());
1736
        } else {
Travis Hance's avatar
exec  
Travis Hance committed
1737 1738
            // FAST or CLOSURE

1739 1740
            CompilerVariable*& prev = symbol_table[name];
            prev = val;
1741

1742
            // Clear out the is_defined name since it is now definitely defined:
1743
            assert(!isIsDefinedName(name.s()));
1744
            InternedString defined_name = getIsDefinedName(name);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1745 1746
            _popFake(defined_name, true);

Travis Hance's avatar
exec  
Travis Hance committed
1747
            if (vst == ScopeInfo::VarScopeType::CLOSURE) {
Travis Hance's avatar
Travis Hance committed
1748
                size_t offset = scope_info->getClosureOffset(name);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1749

Travis Hance's avatar
Travis Hance committed
1750
                // This is basically `closure->elts[offset] = val;`
Travis Hance's avatar
Travis Hance committed
1751 1752
                CompilerVariable* closure = symbol_table[internString(CREATED_CLOSURE_NAME)];
                llvm::Value* closureValue = closure->makeConverted(emitter, CLOSURE)->getValue();
Travis Hance's avatar
Travis Hance committed
1753
                llvm::Value* gep = getClosureElementGep(emitter, closureValue, offset);
Travis Hance's avatar
Travis Hance committed
1754
                emitter.getBuilder()->CreateStore(val->makeConverted(emitter, UNKNOWN)->getValue(), gep);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1755
            }
1756
        }
1757
    }
1758

1759
    void _doSetattr(AST_Attribute* target, CompilerVariable* val, const UnwindInfo& unw_info) {
1760
        CompilerVariable* t = evalExpr(target->value, unw_info);
1761
        t->setattr(emitter, getEmptyOpInfo(unw_info), target->attr.getBox(), val);
1762
    }
1763

1764
    void _doSetitem(AST_Subscript* target, CompilerVariable* val, const UnwindInfo& unw_info) {
1765
        CompilerVariable* tget = evalExpr(target->value, unw_info);
1766
        CompilerVariable* slice = evalSlice(target->slice, unw_info);
1767 1768 1769

        ConcreteCompilerVariable* converted_target = tget->makeConverted(emitter, tget->getBoxType());
        ConcreteCompilerVariable* converted_slice = slice->makeConverted(emitter, slice->getBoxType());
1770

1771 1772
        ConcreteCompilerVariable* converted_val = val->makeConverted(emitter, val->getBoxType());

1773 1774 1775
        // TODO add a CompilerVariable::setattr, which can (similar to getitem)
        // statically-resolve the function if possible, and only fall back to
        // patchpoints if it couldn't.
1776
        bool do_patchpoint = ENABLE_ICSETITEMS;
1777
        if (do_patchpoint) {
1778
            ICSetupInfo* pp = createSetitemIC(getEmptyOpInfo(unw_info).getTypeRecorder());
1779 1780

            std::vector<llvm::Value*> llvm_args;
1781 1782 1783 1784
            llvm_args.push_back(converted_target->getValue());
            llvm_args.push_back(converted_slice->getValue());
            llvm_args.push_back(converted_val->getValue());

1785
            emitter.createIC(pp, (void*)pyston::setitem, llvm_args, unw_info);
1786
        } else {
1787
            emitter.createCall3(unw_info, g.funcs.setitem, converted_target->getValue(), converted_slice->getValue(),
1788
                                converted_val->getValue());
1789
        }
1790
    }
1791

1792
    void _doUnpackTuple(AST_Tuple* target, CompilerVariable* val, const UnwindInfo& unw_info) {
1793
        int ntargets = target->elts.size();
1794

1795
        std::vector<CompilerVariable*> unpacked = val->unpack(emitter, getOpInfoForNode(target, unw_info), ntargets);
1796 1797 1798

#ifndef NDEBUG
        for (auto e : target->elts) {
1799
            ASSERT(e->type == AST_TYPE::Name && ast_cast<AST_Name>(e)->id.s()[0] == '#',
1800 1801 1802 1803
                   "should only be unpacking tuples into cfg-generated names!");
        }
#endif

1804
        for (int i = 0; i < ntargets; i++) {
1805
            CompilerVariable* thisval = unpacked[i];
1806
            _doSet(target->elts[i], thisval, unw_info);
1807
        }
1808
    }
1809

1810
    void _doSet(AST* target, CompilerVariable* val, const UnwindInfo& unw_info) {
1811 1812
        switch (target->type) {
            case AST_TYPE::Attribute:
1813
                _doSetattr(ast_cast<AST_Attribute>(target), val, unw_info);
1814 1815
                break;
            case AST_TYPE::Name:
1816
                _doSet(ast_cast<AST_Name>(target)->id, val, unw_info);
1817 1818
                break;
            case AST_TYPE::Subscript:
1819
                _doSetitem(ast_cast<AST_Subscript>(target), val, unw_info);
1820 1821
                break;
            case AST_TYPE::Tuple:
1822
                _doUnpackTuple(ast_cast<AST_Tuple>(target), val, unw_info);
1823 1824 1825 1826 1827 1828
                break;
            default:
                ASSERT(0, "Unknown type for IRGenerator: %d", target->type);
                abort();
        }
    }
1829

1830
    void doAssert(AST_Assert* node, const UnwindInfo& unw_info) {
1831
        // cfg translates all asserts into only 'assert 0' on the failing path.
1832 1833 1834 1835 1836 1837 1838
        AST_expr* test = node->test;
        assert(test->type == AST_TYPE::Num);
        AST_Num* num = ast_cast<AST_Num>(test);
        assert(num->num_type == AST_Num::INT);
        assert(num->n_int == 0);

        std::vector<llvm::Value*> llvm_args;
1839 1840 1841

        // We could patchpoint this or try to avoid the overhead, but this should only
        // happen when the assertion is actually thrown so I don't think it will be necessary.
1842
        static BoxedString* AssertionError_str = getStaticString("AssertionError");
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1843 1844 1845 1846 1847
        llvm_args.push_back(emitter.setType(
            emitter.createCall2(unw_info, g.funcs.getGlobal, irstate->getGlobals(),
                                emitter.setType(embedRelocatablePtr(AssertionError_str, g.llvm_boxedstring_type_ptr),
                                                RefType::BORROWED)),
            RefType::OWNED));
1848 1849 1850

        ConcreteCompilerVariable* converted_msg = NULL;
        if (node->msg) {
1851
            CompilerVariable* msg = evalExpr(node->msg, unw_info);
1852 1853 1854
            converted_msg = msg->makeConverted(emitter, msg->getBoxType());
            llvm_args.push_back(converted_msg->getValue());
        } else {
1855
            llvm_args.push_back(getNullPtr(g.llvm_value_type_ptr));
1856
        }
1857
        llvm::CallSite call = emitter.createCall(unw_info, g.funcs.assertFail, llvm_args);
1858
        call.setDoesNotReturn();
1859
    }
1860

1861
    void doAssign(AST_Assign* node, const UnwindInfo& unw_info) {
1862
        CompilerVariable* val = evalExpr(node->value, unw_info);
1863

1864
        for (int i = 0; i < node->targets.size(); i++) {
1865
            _doSet(node->targets[i], val, unw_info);
1866
        }
1867
    }
1868

1869
    void doDelete(AST_Delete* node, const UnwindInfo& unw_info) {
1870 1871 1872
        for (AST_expr* target : node->targets) {
            switch (target->type) {
                case AST_TYPE::Subscript:
1873
                    _doDelitem(static_cast<AST_Subscript*>(target), unw_info);
1874
                    break;
1875
                case AST_TYPE::Attribute:
1876
                    _doDelAttr(static_cast<AST_Attribute*>(target), unw_info);
1877
                    break;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1878
                case AST_TYPE::Name:
1879
                    _doDelName(static_cast<AST_Name*>(target), unw_info);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1880
                    break;
1881
                default:
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1882
                    ASSERT(0, "Unsupported del target: %d", target->type);
1883 1884 1885 1886 1887 1888
                    abort();
            }
        }
    }

    // invoke delitem in objmodel.cpp, which will invoke the listDelitem of list
1889
    void _doDelitem(AST_Subscript* target, const UnwindInfo& unw_info) {
1890
        CompilerVariable* tget = evalExpr(target->value, unw_info);
1891
        CompilerVariable* slice = evalSlice(target->slice, unw_info);
1892 1893 1894 1895

        ConcreteCompilerVariable* converted_target = tget->makeConverted(emitter, tget->getBoxType());
        ConcreteCompilerVariable* converted_slice = slice->makeConverted(emitter, slice->getBoxType());

1896
        bool do_patchpoint = ENABLE_ICDELITEMS;
1897
        if (do_patchpoint) {
1898
            ICSetupInfo* pp = createDelitemIC(getEmptyOpInfo(unw_info).getTypeRecorder());
1899 1900 1901 1902 1903

            std::vector<llvm::Value*> llvm_args;
            llvm_args.push_back(converted_target->getValue());
            llvm_args.push_back(converted_slice->getValue());

1904
            emitter.createIC(pp, (void*)pyston::delitem, llvm_args, unw_info);
1905
        } else {
1906
            emitter.createCall2(unw_info, g.funcs.delitem, converted_target->getValue(), converted_slice->getValue());
1907 1908 1909
        }
    }

1910
    void _doDelAttr(AST_Attribute* node, const UnwindInfo& unw_info) {
1911
        CompilerVariable* value = evalExpr(node->value, unw_info);
1912
        value->delattr(emitter, getEmptyOpInfo(unw_info), node->attr.getBox());
1913 1914
    }

1915
    void _doDelName(AST_Name* target, const UnwindInfo& unw_info) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1916
        auto scope_info = irstate->getScopeInfo();
Travis Hance's avatar
exec  
Travis Hance committed
1917 1918
        ScopeInfo::VarScopeType vst = scope_info->getScopeTypeOfName(target->id);
        if (vst == ScopeInfo::VarScopeType::GLOBAL) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1919
            // Can't use delattr since the errors are different:
1920
            emitter.createCall2(unw_info, g.funcs.delGlobal, irstate->getGlobals(),
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1921 1922
                                emitter.setType(embedRelocatablePtr(target->id.getBox(), g.llvm_boxedstring_type_ptr),
                                                RefType::BORROWED));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1923 1924 1925
            return;
        }

Travis Hance's avatar
exec  
Travis Hance committed
1926 1927
        if (vst == ScopeInfo::VarScopeType::NAME) {
            llvm::Value* boxedLocals = irstate->getBoxedLocalsVar();
1928
            llvm::Value* attr = embedRelocatablePtr(target->id.getBox(), g.llvm_boxedstring_type_ptr);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1929
            emitter.setType(attr, RefType::BORROWED);
Travis Hance's avatar
exec  
Travis Hance committed
1930 1931 1932
            emitter.createCall2(unw_info, g.funcs.boxedLocalsDel, boxedLocals, attr);
            return;
        }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1933

Travis Hance's avatar
exec  
Travis Hance committed
1934 1935 1936
        // Can't be in a closure because of this syntax error:
        // SyntaxError: can not delete variable 'x' referenced in nested scope
        assert(vst == ScopeInfo::VarScopeType::FAST);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1937 1938

        if (symbol_table.count(target->id) == 0) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1939 1940 1941 1942 1943
            llvm::CallSite call = emitter.createCall(
                unw_info, g.funcs.assertNameDefined,
                { getConstantInt(0, g.i1), embedConstantPtr(target->id.c_str(), g.i8_ptr),
                  emitter.setType(embedRelocatablePtr(NameError, g.llvm_class_type_ptr), RefType::BORROWED),
                  getConstantInt(true /*local_error_msg*/, g.i1) });
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1944 1945 1946 1947
            call.setDoesNotReturn();
            return;
        }

1948
        InternedString defined_name = getIsDefinedName(target->id);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1949 1950 1951
        ConcreteCompilerVariable* is_defined_var = static_cast<ConcreteCompilerVariable*>(_getFake(defined_name, true));

        if (is_defined_var) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1952 1953 1954 1955 1956
            emitter.createCall(
                unw_info, g.funcs.assertNameDefined,
                { i1FromBool(emitter, is_defined_var), embedConstantPtr(target->id.c_str(), g.i8_ptr),
                  emitter.setType(embedRelocatablePtr(NameError, g.llvm_class_type_ptr), RefType::BORROWED),
                  getConstantInt(true /*local_error_msg*/, g.i1) });
Kevin Modzelewski's avatar
Kevin Modzelewski committed
1957 1958 1959 1960 1961 1962
            _popFake(defined_name);
        }

        symbol_table.erase(target->id);
    }

1963
    void doExec(AST_Exec* node, const UnwindInfo& unw_info) {
Travis Hance's avatar
exec  
Travis Hance committed
1964
        CompilerVariable* body = evalExpr(node->body, unw_info);
1965
        llvm::Value* vbody = body->makeConverted(emitter, body->getBoxType())->getValue();
Travis Hance's avatar
exec  
Travis Hance committed
1966

1967 1968 1969 1970 1971
        llvm::Value* vglobals;
        if (node->globals) {
            CompilerVariable* globals = evalExpr(node->globals, unw_info);
            vglobals = globals->makeConverted(emitter, globals->getBoxType())->getValue();
        } else {
1972
            vglobals = getNullPtr(g.llvm_value_type_ptr);
1973 1974 1975 1976 1977 1978 1979
        }

        llvm::Value* vlocals;
        if (node->locals) {
            CompilerVariable* locals = evalExpr(node->locals, unw_info);
            vlocals = locals->makeConverted(emitter, locals->getBoxType())->getValue();
        } else {
1980
            vlocals = getNullPtr(g.llvm_value_type_ptr);
1981 1982
        }

1983 1984 1985
        static_assert(sizeof(FutureFlags) == 4, "");
        emitter.createCall(unw_info, g.funcs.exec,
                           { vbody, vglobals, vlocals, getConstantInt(irstate->getSourceInfo()->future_flags, g.i32) });
Travis Hance's avatar
exec  
Travis Hance committed
1986 1987
    }

1988
    void doPrint(AST_Print* node, const UnwindInfo& unw_info) {
1989 1990
        ConcreteCompilerVariable* dest = NULL;
        if (node->dest) {
1991
            auto d = evalExpr(node->dest, unw_info);
1992
            dest = d->makeConverted(emitter, d->getBoxType());
1993
        } else {
1994
            llvm::Value* sys_stdout_val = emitter.createCall(unw_info, g.funcs.getSysStdout, NOEXC);
1995
            emitter.setType(sys_stdout_val, RefType::BORROWED);
1996
            dest = new ConcreteCompilerVariable(UNKNOWN, sys_stdout_val);
1997
            // TODO: speculate that sys.stdout is a file?
1998 1999 2000
        }
        assert(dest);

2001 2002
        assert(node->values.size() <= 1);
        ConcreteCompilerVariable* converted;
2003

2004 2005 2006 2007
        if (node->values.size() == 1) {
            CompilerVariable* var = evalExpr(node->values[0], unw_info);
            converted = var->makeConverted(emitter, var->getBoxType());
        } else {
2008
            converted = new ConcreteCompilerVariable(UNKNOWN, getNullPtr(g.llvm_value_type_ptr));
2009 2010
        }

2011 2012
        emitter.createCall3(unw_info, g.funcs.printHelper, dest->getValue(), converted->getValue(),
                            getConstantInt(node->nl, g.i1));
2013
    }
2014

2015 2016
    void doReturn(AST_Return* node, const UnwindInfo& unw_info) {
        assert(!unw_info.hasHandler());
2017

2018 2019
        CompilerVariable* val;
        if (node->value == NULL) {
2020
            val = emitter.getNone();
2021
        } else {
2022
            val = evalExpr(node->value, unw_info);
2023
        }
2024 2025 2026 2027 2028 2029 2030 2031
        assert(val);

        ConcreteCompilerType* opt_rtn_type = irstate->getReturnType();
        if (irstate->getReturnType()->llvmType() == val->getConcreteType()->llvmType())
            opt_rtn_type = val->getConcreteType();

        ConcreteCompilerVariable* rtn = val->makeConverted(emitter, opt_rtn_type);

2032 2033 2034 2035 2036
        assert(rtn->getValue());
        auto ret_inst = emitter.getBuilder()->CreateRet(rtn->getValue());

        irstate->getRefcounts()->refConsumed(rtn->getValue(), ret_inst);

2037 2038
        symbol_table.clear();

2039 2040
        endBlock(DEAD);
    }
2041

2042 2043
    void doBranch(AST_Branch* node, const UnwindInfo& unw_info) {
        assert(!unw_info.hasHandler());
2044

2045 2046
        assert(node->iftrue->idx > myblock->idx);
        assert(node->iffalse->idx > myblock->idx);
2047

2048
        CompilerVariable* val = evalExpr(node->test, unw_info);
2049
        assert(val);
2050

2051 2052 2053 2054 2055
        // We could call nonzero here if there is no try-catch block?
        ASSERT(val->getType() == BOOL, "should have called NONZERO before this; is %s",
               val->getType()->debugName().c_str());
        llvm::Value* v = i1FromBool(emitter, static_cast<ConcreteCompilerVariable*>(val));
        assert(v->getType() == g.i1);
2056

2057 2058
        llvm::BasicBlock* iftrue = entry_blocks[node->iftrue];
        llvm::BasicBlock* iffalse = entry_blocks[node->iffalse];
2059

2060
        endBlock(FINISHED);
2061

2062
        emitter.getBuilder()->CreateCondBr(v, iftrue, iffalse);
2063
    }
2064

2065
    void doExpr(AST_Expr* node, const UnwindInfo& unw_info) {
2066
        CompilerVariable* var = evalExpr(node->value, unw_info);
2067
    }
2068

2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
    void doOSRExit(llvm::BasicBlock* normal_target, AST_Jump* osr_key) {
        llvm::BasicBlock* starting_block = curblock;
        llvm::BasicBlock* onramp = llvm::BasicBlock::Create(g.context, "onramp", irstate->getLLVMFunction());

        // Code to check if we want to do the OSR:
        llvm::GlobalVariable* edgecount_ptr = new llvm::GlobalVariable(
            *g.cur_module, g.i64, false, llvm::GlobalValue::InternalLinkage, getConstantInt(0, g.i64), "edgecount");
        llvm::Value* curcount = emitter.getBuilder()->CreateLoad(edgecount_ptr);
        llvm::Value* newcount = emitter.getBuilder()->CreateAdd(curcount, getConstantInt(1, g.i64));
        emitter.getBuilder()->CreateStore(newcount, edgecount_ptr);

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2080 2081
        auto effort = irstate->getEffortLevel();
        int osr_threshold;
2082
        if (effort == EffortLevel::MODERATE)
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2083 2084 2085 2086
            osr_threshold = OSR_THRESHOLD_T2;
        else
            RELEASE_ASSERT(0, "Unknown effort: %d", (int)effort);
        llvm::Value* osr_test = emitter.getBuilder()->CreateICmpSGT(newcount, getConstantInt(osr_threshold));
2087

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2088 2089 2090 2091
        llvm::Metadata* md_vals[]
            = { llvm::MDString::get(g.context, "branch_weights"), llvm::ConstantAsMetadata::get(getConstantInt(1)),
                llvm::ConstantAsMetadata::get(getConstantInt(1000)) };
        llvm::MDNode* branch_weights = llvm::MDNode::get(g.context, llvm::ArrayRef<llvm::Metadata*>(md_vals));
2092 2093 2094 2095
        emitter.getBuilder()->CreateCondBr(osr_test, onramp, normal_target, branch_weights);

        // Emitting the actual OSR:
        emitter.getBuilder()->SetInsertPoint(onramp);
2096
        OSREntryDescriptor* entry = OSREntryDescriptor::create(irstate->getMD(), osr_key, irstate->getExceptionStyle());
2097
        OSRExit* exit = new OSRExit(entry);
2098
        llvm::Value* partial_func = emitter.getBuilder()->CreateCall(g.funcs.compilePartialFunc,
2099
                                                                     embedRelocatablePtr(exit, g.i8->getPointerTo()));
2100 2101 2102 2103 2104 2105 2106

        std::vector<llvm::Value*> llvm_args;
        std::vector<llvm::Type*> llvm_arg_types;
        std::vector<ConcreteCompilerVariable*> converted_args;

        SortedSymbolTable sorted_symbol_table(symbol_table.begin(), symbol_table.end());

Travis Hance's avatar
exec  
Travis Hance committed
2107
        sorted_symbol_table[internString(FRAME_INFO_PTR_NAME)]
2108
            = new ConcreteCompilerVariable(FRAME_INFO, irstate->getFrameInfoVar());
Travis Hance's avatar
exec  
Travis Hance committed
2109

2110 2111
        if (!irstate->getSourceInfo()->scoping->areGlobalsFromModule()) {
            sorted_symbol_table[internString(PASSED_GLOBALS_NAME)]
2112
                = new ConcreteCompilerVariable(UNKNOWN, irstate->getGlobals());
2113 2114
        }

2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
        // For OSR calls, we use the same calling convention as in some other places; namely,
        // arg1, arg2, arg3, argarray [nargs is ommitted]
        // It would be nice to directly pass all variables as arguments, instead of packing them into
        // an array, for a couple reasons (eliminate copies, and allow for a tail call).
        // But this doesn't work if the IR is being interpreted, because the interpreter can't
        // do arbitrary-arity function calls (yet?).  One possibility is to pass them as an
        // array for the interpreter and as all arguments for compilation, but I'd rather avoid
        // having two different calling conventions for the same thing.  Plus, this would
        // prevent us from having two OSR exits point to the same OSR entry; not something that
        // we're doing right now but something that would be nice in the future.

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2126
        llvm::Value* arg_array = NULL, * malloc_save = NULL;
2127 2128 2129 2130 2131
        if (sorted_symbol_table.size() > 3) {
            // Leave in the ability to use malloc but I guess don't use it.
            // Maybe if there are a ton of live variables it'd be nice to have them be
            // heap-allocated, or if we don't immediately return the result of the OSR?
            bool use_malloc = false;
2132
            if (use_malloc) {
2133 2134 2135 2136 2137 2138 2139
                llvm::Value* n_bytes = getConstantInt((sorted_symbol_table.size() - 3) * sizeof(Box*), g.i64);
                llvm::Value* l_malloc = embedConstantPtr(
                    (void*)malloc, llvm::FunctionType::get(g.i8->getPointerTo(), g.i64, false)->getPointerTo());
                malloc_save = emitter.getBuilder()->CreateCall(l_malloc, n_bytes);
                arg_array = emitter.getBuilder()->CreateBitCast(malloc_save, g.llvm_value_type_ptr->getPointerTo());
            } else {
                llvm::Value* n_varargs = llvm::ConstantInt::get(g.i64, sorted_symbol_table.size() - 3, false);
2140 2141 2142 2143
                // TODO we have a number of allocas with non-overlapping lifetimes, that end up
                // being redundant.
                arg_array = new llvm::AllocaInst(g.llvm_value_type_ptr, n_varargs, "",
                                                 irstate->getLLVMFunction()->getEntryBlock().getFirstInsertionPt());
2144 2145
            }
        }
2146

2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
        int arg_num = -1;
        for (const auto& p : sorted_symbol_table) {
            arg_num++;

            // This line can never get hit right now since we unnecessarily force every variable to be concrete
            // for a loop, since we generate all potential phis:
            ASSERT(p.second->getType() == p.second->getConcreteType(), "trying to pass through %s\n",
                   p.second->getType()->debugName().c_str());

            ConcreteCompilerVariable* var = p.second->makeConverted(emitter, p.second->getConcreteType());
            converted_args.push_back(var);

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2159
            assert(var->getType() != BOXED_INT);
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
            assert(var->getType() != BOXED_FLOAT
                   && "should probably unbox it, but why is it boxed in the first place?");

            llvm::Value* val = var->getValue();

            if (arg_num < 3) {
                llvm_args.push_back(val);
                llvm_arg_types.push_back(val->getType());
            } else {
                llvm::Value* ptr = emitter.getBuilder()->CreateConstGEP1_32(arg_array, arg_num - 3);
2170

2171
                if (var->getType() == INT || var->getType() == BOOL) {
2172 2173 2174 2175
                    val = emitter.getBuilder()->CreateIntToPtr(val, g.llvm_value_type_ptr);
                } else if (var->getType() == FLOAT) {
                    // val = emitter.getBuilder()->CreateBitCast(val, g.llvm_value_type_ptr);
                    ptr = emitter.getBuilder()->CreateBitCast(ptr, g.double_->getPointerTo());
2176 2177
                } else if (var->getType() == GENERATOR) {
                    ptr = emitter.getBuilder()->CreateBitCast(ptr, g.llvm_generator_type_ptr->getPointerTo());
2178 2179 2180 2181 2182 2183
                } else if (var->getType() == UNDEF) {
                    // TODO if there are any undef variables, we're in 'unreachable' territory.
                    // Do we even need to generate any of this code?

                    // Currently we represent 'undef's as 'i16 undef'
                    val = emitter.getBuilder()->CreateIntToPtr(val, g.llvm_value_type_ptr);
2184 2185
                } else if (var->getType() == CLOSURE) {
                    ptr = emitter.getBuilder()->CreateBitCast(ptr, g.llvm_closure_type_ptr->getPointerTo());
Travis Hance's avatar
exec  
Travis Hance committed
2186 2187 2188
                } else if (var->getType() == FRAME_INFO) {
                    ptr = emitter.getBuilder()->CreateBitCast(ptr,
                                                              g.llvm_frame_info_type->getPointerTo()->getPointerTo());
2189
                } else {
2190
                    assert(val->getType() == g.llvm_value_type_ptr);
2191 2192
                }

2193
                emitter.getBuilder()->CreateStore(val, ptr);
2194 2195
            }

2196
            ConcreteCompilerType*& t = entry->args[p.first];
2197 2198 2199 2200 2201
            if (t == NULL)
                t = var->getType();
            else
                ASSERT(t == var->getType(), "%s %s\n", t->debugName().c_str(), var->getType()->debugName().c_str());
        }
2202

2203 2204 2205 2206
        if (sorted_symbol_table.size() > 3) {
            llvm_args.push_back(arg_array);
            llvm_arg_types.push_back(arg_array->getType());
        }
2207

2208 2209 2210
        llvm::FunctionType* ft
            = llvm::FunctionType::get(irstate->getReturnType()->llvmType(), llvm_arg_types, false /*vararg*/);
        partial_func = emitter.getBuilder()->CreateBitCast(partial_func, ft->getPointerTo());
2211

2212
        llvm::CallInst* rtn = emitter.getBuilder()->CreateCall(partial_func, llvm_args);
2213

2214 2215 2216 2217
        // If we alloca'd the arg array, we can't make this into a tail call:
        if (arg_array == NULL && malloc_save != NULL) {
            rtn->setTailCall(true);
        }
2218

2219 2220 2221 2222 2223
        if (malloc_save != NULL) {
            llvm::Value* l_free = embedConstantPtr(
                (void*)free, llvm::FunctionType::get(g.void_, g.i8->getPointerTo(), false)->getPointerTo());
            emitter.getBuilder()->CreateCall(l_free, malloc_save);
        }
2224

2225
        emitter.getBuilder()->CreateRet(rtn);
2226

2227 2228
        emitter.getBuilder()->SetInsertPoint(starting_block);
    }
2229

2230
    void doJump(AST_Jump* node, const UnwindInfo& unw_info) {
2231
        endBlock(FINISHED);
2232

2233 2234 2235 2236 2237 2238 2239
        llvm::BasicBlock* target = entry_blocks[node->target];

        if (ENABLE_OSR && node->target->idx < myblock->idx && irstate->getEffortLevel() < EffortLevel::MAXIMAL) {
            assert(node->target->predecessors.size() > 1);
            doOSRExit(target, node);
        } else {
            emitter.getBuilder()->CreateBr(target);
2240
        }
2241
    }
2242

2243
    void doRaise(AST_Raise* node, const UnwindInfo& unw_info) {
2244 2245 2246
        // It looks like ommitting the second and third arguments are equivalent to passing None,
        // but ommitting the first argument is *not* the same as passing None.

2247 2248 2249
        ExceptionStyle target_exception_style;

        if (unw_info.hasHandler())
2250
            target_exception_style = CAPI;
2251 2252
        else
            target_exception_style = irstate->getExceptionStyle();
2253

2254 2255 2256
        if (node->arg0 == NULL) {
            assert(!node->arg1);
            assert(!node->arg2);
2257

2258
            llvm::Value* exc_info = emitter.getBuilder()->CreateConstInBoundsGEP2_32(irstate->getFrameInfoVar(), 0, 0);
2259
            if (target_exception_style == CAPI) {
2260
                emitter.createCall(unw_info, g.funcs.raise0_capi, exc_info, CAPI);
2261 2262 2263 2264
                emitter.checkAndPropagateCapiException(unw_info, getNullPtr(g.llvm_value_type_ptr),
                                                       getNullPtr(g.llvm_value_type_ptr));
                emitter.getBuilder()->CreateUnreachable();
            } else {
2265
                emitter.createCall(unw_info, g.funcs.raise0, exc_info);
2266 2267
                emitter.getBuilder()->CreateUnreachable();
            }
2268 2269 2270 2271 2272 2273

            endBlock(DEAD);
            return;
        }

        std::vector<llvm::Value*> args;
2274 2275
        for (auto a : { node->arg0, node->arg1, node->arg2 }) {
            if (a) {
2276
                CompilerVariable* v = evalExpr(a, unw_info);
2277 2278 2279
                ConcreteCompilerVariable* converted = v->makeConverted(emitter, v->getBoxType());
                args.push_back(converted->getValue());
            } else {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2280
                args.push_back(emitter.getNone()->getValue());
2281
            }
2282
        }
2283

2284 2285 2286 2287 2288 2289 2290
        if (target_exception_style == CAPI) {
            emitter.createCall(unw_info, g.funcs.raise3_capi, args, CAPI);
            emitter.checkAndPropagateCapiException(unw_info, getNullPtr(g.llvm_value_type_ptr),
                                                   getNullPtr(g.llvm_value_type_ptr));
        } else {
            emitter.createCall(unw_info, g.funcs.raise3, args, CXX);
        }
2291 2292 2293 2294 2295
        emitter.getBuilder()->CreateUnreachable();

        endBlock(DEAD);
    }

2296
    void doStmt(AST_stmt* node, const UnwindInfo& unw_info) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2297
        // printf("%d stmt: %d\n", node->type, node->lineno);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2298
        if (node->lineno) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2299 2300
            emitter.getBuilder()->SetCurrentDebugLocation(
                llvm::DebugLoc::get(node->lineno, 0, irstate->getFuncDbgInfo()));
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2301 2302
        }

2303 2304
        switch (node->type) {
            case AST_TYPE::Assert:
2305
                doAssert(ast_cast<AST_Assert>(node), unw_info);
2306 2307
                break;
            case AST_TYPE::Assign:
2308
                doAssign(ast_cast<AST_Assign>(node), unw_info);
2309
                break;
2310
            case AST_TYPE::Delete:
2311
                doDelete(ast_cast<AST_Delete>(node), unw_info);
2312
                break;
Travis Hance's avatar
exec  
Travis Hance committed
2313 2314 2315
            case AST_TYPE::Exec:
                doExec(ast_cast<AST_Exec>(node), unw_info);
                break;
2316
            case AST_TYPE::Expr:
2317 2318
                if ((((AST_Expr*)node)->value)->type != AST_TYPE::Str)
                    doExpr(ast_cast<AST_Expr>(node), unw_info);
2319 2320 2321 2322
                break;
            // case AST_TYPE::If:
            // doIf(ast_cast<AST_If>(node));
            // break;
Travis Hance's avatar
Travis Hance committed
2323
            // case AST_TYPE::Import:
2324
            //     doImport(ast_cast<AST_Import>(node), unw_info);
Travis Hance's avatar
Travis Hance committed
2325 2326
            //     break;
            // case AST_TYPE::ImportFrom:
2327
            //     doImportFrom(ast_cast<AST_ImportFrom>(node), unw_info);
Travis Hance's avatar
Travis Hance committed
2328
            //     break;
2329 2330 2331 2332 2333 2334
            case AST_TYPE::Global:
                // Should have been handled already
                break;
            case AST_TYPE::Pass:
                break;
            case AST_TYPE::Print:
2335
                doPrint(ast_cast<AST_Print>(node), unw_info);
2336 2337
                break;
            case AST_TYPE::Return:
2338
                assert(!unw_info.hasHandler());
2339
                doReturn(ast_cast<AST_Return>(node), unw_info);
2340 2341
                break;
            case AST_TYPE::Branch:
2342
                assert(!unw_info.hasHandler());
2343
                doBranch(ast_cast<AST_Branch>(node), unw_info);
2344 2345
                break;
            case AST_TYPE::Jump:
2346
                assert(!unw_info.hasHandler());
2347
                doJump(ast_cast<AST_Jump>(node), unw_info);
2348 2349
                break;
            case AST_TYPE::Invoke: {
2350
                assert(!unw_info.hasHandler());
2351
                AST_Invoke* invoke = ast_cast<AST_Invoke>(node);
2352

2353
                doStmt(invoke->stmt, UnwindInfo(node, entry_blocks[invoke->exc_dest]));
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363

                assert(state == RUNNING || state == DEAD);
                if (state == RUNNING) {
                    emitter.getBuilder()->CreateBr(entry_blocks[invoke->normal_dest]);
                    endBlock(FINISHED);
                }

                break;
            }
            case AST_TYPE::Raise:
2364
                doRaise(ast_cast<AST_Raise>(node), unw_info);
2365 2366 2367 2368
                break;
            default:
                printf("Unhandled stmt type at " __FILE__ ":" STRINGIFY(__LINE__) ": %d\n", node->type);
                exit(1);
2369
        }
2370
    }
2371

2372
    void loadArgument(InternedString name, ConcreteCompilerType* t, llvm::Value* v, const UnwindInfo& unw_info) {
2373
        assert(name.s() != FRAME_INFO_PTR_NAME);
2374
        CompilerVariable* var = unboxVar(t, v);
2375 2376 2377
        _doSet(name, var, unw_info);
    }

2378
    void loadArgument(AST_expr* name, ConcreteCompilerType* t, llvm::Value* v, const UnwindInfo& unw_info) {
2379
        CompilerVariable* var = unboxVar(t, v);
2380
        _doSet(name, var, unw_info);
2381
    }
2382

2383 2384
    bool allowableFakeEndingSymbol(InternedString name) {
        // TODO this would be a great place to be able to use interned versions of the static names...
2385 2386
        return isIsDefinedName(name.s()) || name.s() == PASSED_CLOSURE_NAME || name.s() == CREATED_CLOSURE_NAME
               || name.s() == PASSED_GENERATOR_NAME;
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2387 2388
    }

2389 2390
    void endBlock(State new_state) {
        assert(state == RUNNING);
2391

2392
        // cf->func->dump();
2393

2394 2395
        SourceInfo* source = irstate->getSourceInfo();
        ScopeInfo* scope_info = irstate->getScopeInfo();
2396

2397 2398 2399
        // Sort the names here to make the process deterministic:
        std::map<InternedString, CompilerVariable*> sorted_symbol_table(symbol_table.begin(), symbol_table.end());
        for (const auto& p : sorted_symbol_table) {
2400
            assert(p.first.s() != FRAME_INFO_PTR_NAME);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2401
            assert(p.second->getType()->isUsable());
2402
            if (allowableFakeEndingSymbol(p.first))
2403 2404
                continue;

2405 2406 2407
            // ASSERT(p.first[0] != '!' || isIsDefinedName(p.first), "left a fake variable in the real
            // symbol table? '%s'", p.first.c_str());

2408
            if (!irstate->getLiveness()->isLiveAtEnd(p.first, myblock)) {
2409 2410
                symbol_table.erase(getIsDefinedName(p.first));
                symbol_table.erase(p.first);
2411
            } else if (irstate->getPhis()->isRequiredAfter(p.first, myblock)) {
2412 2413
                assert(scope_info->getScopeTypeOfName(p.first) != ScopeInfo::VarScopeType::GLOBAL);
                ConcreteCompilerType* phi_type = types->getTypeAtBlockEnd(p.first, myblock);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2414
                assert(phi_type->isUsable());
2415 2416 2417 2418 2419
                // printf("Converting %s from %s to %s\n", p.first.c_str(),
                // p.second->getType()->debugName().c_str(), phi_type->debugName().c_str());
                // printf("have to convert %s from %s to %s\n", p.first.c_str(),
                // p.second->getType()->debugName().c_str(), phi_type->debugName().c_str());
                ConcreteCompilerVariable* v = p.second->makeConverted(emitter, phi_type);
2420
                symbol_table[p.first] = v;
2421
            } else {
2422
#ifndef NDEBUG
2423
                if (myblock->successors.size()) {
Travis Hance's avatar
Travis Hance committed
2424 2425
                    // TODO getTypeAtBlockEnd will automatically convert up to the concrete type, which we don't
                    // want
2426
                    // here, but this is just for debugging so I guess let it happen for now:
2427 2428 2429
                    ConcreteCompilerType* ending_type = types->getTypeAtBlockEnd(p.first, myblock);
                    ASSERT(p.second->canConvertTo(ending_type), "%s is supposed to be %s, but somehow is %s",
                           p.first.c_str(), ending_type->debugName().c_str(), p.second->getType()->debugName().c_str());
2430
                }
2431 2432
#endif
            }
2433
        }
2434

2435
        const PhiAnalysis::RequiredSet& all_phis = irstate->getPhis()->getAllRequiredAfter(myblock);
2436
        for (PhiAnalysis::RequiredSet::const_iterator it = all_phis.begin(), end = all_phis.end(); it != end; ++it) {
2437 2438
            if (VERBOSITY() >= 3)
                printf("phi will be required for %s\n", it->c_str());
Travis Hance's avatar
exec  
Travis Hance committed
2439
            assert(scope_info->getScopeTypeOfName(*it) != ScopeInfo::VarScopeType::GLOBAL);
2440
            CompilerVariable*& cur = symbol_table[*it];
2441

2442
            InternedString defined_name = getIsDefinedName(*it);
2443

2444 2445
            if (cur != NULL) {
                // printf("defined on this path; ");
2446

2447
                ConcreteCompilerVariable* is_defined
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2448
                    = static_cast<ConcreteCompilerVariable*>(_popFake(defined_name, true));
2449

2450
                if (irstate->getPhis()->isPotentiallyUndefinedAfter(*it, myblock)) {
2451 2452 2453
                    // printf("is potentially undefined later, so marking it defined\n");
                    if (is_defined) {
                        _setFake(defined_name, is_defined);
2454
                    } else {
2455
                        _setFake(defined_name, makeBool(1));
2456 2457
                    }
                } else {
2458 2459
                    // printf("is defined in all later paths, so not marking\n");
                    assert(!is_defined);
2460
                }
2461 2462 2463
            } else {
                // printf("no st entry, setting undefined\n");
                ConcreteCompilerType* phi_type = types->getTypeAtBlockEnd(*it, myblock);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2464
                assert(phi_type->isUsable());
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476

                // Forward an incref'd None instead of a NULL.
                // TODO Change to using NULL to represent not-defined for boxed types, similar
                // to CPython?
                llvm::Value* v;
                if (phi_type == phi_type->getBoxType()) {
                    v = emitter.getNone()->getValue();
                } else {
                    v = llvm::UndefValue::get(phi_type->llvmType());
                }

                cur = new ConcreteCompilerVariable(phi_type, v);
2477
                _setFake(defined_name, makeBool(0));
2478 2479 2480
            }
        }

2481 2482
        state = new_state;
    }
2483

2484
public:
2485 2486
    void addFrameStackmapArgs(PatchpointInfo* pp, AST_stmt* current_stmt,
                              std::vector<llvm::Value*>& stackmap_args) override {
2487
        int initial_args = stackmap_args.size();
2488

2489 2490
        stackmap_args.push_back(irstate->getFrameInfoVar());

2491 2492 2493 2494 2495
        if (!irstate->getSourceInfo()->scoping->areGlobalsFromModule()) {
            stackmap_args.push_back(irstate->getGlobals());
            pp->addFrameVar(PASSED_GLOBALS_NAME, UNKNOWN);
        }

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2496
        assert(UNBOXED_INT->llvmType() == g.i64);
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
        if (ENABLE_JIT_OBJECT_CACHE) {
            llvm::Value* v;
            if (current_stmt)
                v = emitter.getBuilder()->CreatePtrToInt(embedRelocatablePtr(current_stmt, g.i8_ptr), g.i64);
            else
                v = getConstantInt(0, g.i64);
            stackmap_args.push_back(v);
        } else {
            stackmap_args.push_back(getConstantInt((uint64_t)current_stmt, g.i64));
        }

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2508
        pp->addFrameVar("!current_stmt", UNBOXED_INT);
2509

2510 2511 2512
        if (ENABLE_FRAME_INTROSPECTION) {
            // TODO: don't need to use a sorted symbol table if we're explicitly recording the names!
            // nice for debugging though.
2513 2514 2515 2516
            typedef std::pair<InternedString, CompilerVariable*> Entry;
            std::vector<Entry> sorted_symbol_table(symbol_table.begin(), symbol_table.end());
            std::sort(sorted_symbol_table.begin(), sorted_symbol_table.end(),
                      [](const Entry& lhs, const Entry& rhs) { return lhs.first < rhs.first; });
2517 2518 2519
            for (const auto& p : sorted_symbol_table) {
                CompilerVariable* v = p.second;
                v->serializeToFrame(stackmap_args);
2520
                pp->addFrameVar(p.first.s(), v->getType());
2521 2522
            }
        }
2523 2524 2525

        int num_frame_args = stackmap_args.size() - initial_args;
        pp->setNumFrameArgs(num_frame_args);
2526 2527
    }

2528 2529
    EndingState getEndingSymbolTable() override {
        assert(state == FINISHED || state == DEAD);
2530

2531
        SourceInfo* source = irstate->getSourceInfo();
2532

2533 2534 2535
        SymbolTable* st = new SymbolTable(symbol_table);
        ConcreteSymbolTable* phi_st = new ConcreteSymbolTable();

2536 2537 2538
        // This should have been consumed:
        assert(incoming_exc_state.empty());

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2539 2540 2541 2542
        for (auto&& p : symbol_table) {
            ASSERT(p.second->getType()->isUsable(), "%s", p.first.c_str());
        }

2543
        if (myblock->successors.size() == 0) {
2544 2545
            st->clear();
            symbol_table.clear();
2546
            return EndingState(st, phi_st, curblock, outgoing_exc_state);
2547 2548 2549
        } else if (myblock->successors.size() > 1) {
            // Since there are no critical edges, all successors come directly from this node,
            // so there won't be any required phis.
2550
            return EndingState(st, phi_st, curblock, outgoing_exc_state);
2551
        }
2552

2553
        assert(myblock->successors.size() == 1); // other cases should have been handled
2554

2555 2556 2557 2558 2559
        // In theory this case shouldn't be necessary:
        if (myblock->successors[0]->predecessors.size() == 1) {
            // If the next block has a single predecessor, don't have to
            // emit any phis.
            // Should probably not emit no-op jumps like this though.
2560
            return EndingState(st, phi_st, curblock, outgoing_exc_state);
2561
        }
2562

2563 2564
        // We have one successor, but they have more than one predecessor.
        // We're going to sort out which symbols need to go in phi_st and which belong inst.
2565
        for (SymbolTable::iterator it = st->begin(); it != st->end();) {
2566
            if (allowableFakeEndingSymbol(it->first) || irstate->getPhis()->isRequiredAfter(it->first, myblock)) {
2567 2568
                // this conversion should have already happened... should refactor this.
                ConcreteCompilerType* ending_type;
2569
                if (isIsDefinedName(it->first.s())) {
2570 2571
                    assert(it->second->getType() == BOOL);
                    ending_type = BOOL;
2572
                } else if (it->first.s() == PASSED_CLOSURE_NAME) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2573
                    ending_type = getPassedClosureType();
2574
                } else if (it->first.s() == CREATED_CLOSURE_NAME) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2575
                    ending_type = getCreatedClosureType();
2576
                } else if (it->first.s() == PASSED_GENERATOR_NAME) {
2577
                    ending_type = GENERATOR;
2578
                } else if (it->first.s() == FRAME_INFO_PTR_NAME) {
Travis Hance's avatar
exec  
Travis Hance committed
2579
                    ending_type = FRAME_INFO;
2580
                } else {
2581
                    ending_type = types->getTypeAtBlockEnd(it->first, myblock);
2582
                }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2583
                assert(ending_type->isUsable());
2584
                //(*phi_st)[it->first] = it->second->makeConverted(emitter, it->second->getConcreteType());
2585
                (*phi_st)[it->first] = it->second->makeConverted(emitter, ending_type);
2586 2587 2588
                it = st->erase(it);
            } else {
                ++it;
2589 2590
            }
        }
2591
        return EndingState(st, phi_st, curblock, outgoing_exc_state);
2592
    }
2593

2594
    void giveLocalSymbol(InternedString name, CompilerVariable* var) override {
2595 2596
        assert(name.s() != "None");
        assert(name.s() != FRAME_INFO_PTR_NAME);
Travis Hance's avatar
exec  
Travis Hance committed
2597 2598
        ASSERT(irstate->getScopeInfo()->getScopeTypeOfName(name) != ScopeInfo::VarScopeType::GLOBAL, "%s",
               name.c_str());
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2599 2600 2601

        ASSERT(var->getType()->isUsable(), "%s", name.c_str());

2602 2603 2604 2605
        CompilerVariable*& cur = symbol_table[name];
        assert(cur == NULL);
        cur = var;
    }
2606

2607 2608 2609
    void copySymbolsFrom(SymbolTable* st) override {
        assert(st);
        DupCache cache;
2610
        for (SymbolTable::iterator it = st->begin(); it != st->end(); ++it) {
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2611
            // printf("Copying in %s, a %s\n", it->first.c_str(), it->second->getType()->debugName().c_str());
2612
            symbol_table[it->first] = it->second->dup(cache);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2613
            assert(symbol_table[it->first]->getType()->isUsable());
2614
        }
2615
    }
2616

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
    ConcreteCompilerType* getPassedClosureType() {
        // TODO could know the exact closure shape
        return CLOSURE;
    }

    ConcreteCompilerType* getCreatedClosureType() {
        // TODO could know the exact closure shape
        return CLOSURE;
    }

2627 2628
    void doFunctionEntry(const ParamNames& param_names, const std::vector<ConcreteCompilerType*>& arg_types) override {
        assert(param_names.totalParameters() == arg_types.size());
2629

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2630 2631 2632 2633
        auto scope_info = irstate->getScopeInfo();

        llvm::Value* passed_closure = NULL;
        llvm::Function::arg_iterator AI = irstate->getLLVMFunction()->arg_begin();
2634

Kevin Modzelewski's avatar
Kevin Modzelewski committed
2635 2636
        if (scope_info->takesClosure()) {
            passed_closure = AI;
2637
            emitter.setType(passed_closure, RefType::BORROWED);
2638
            symbol_table[internString(PASSED_CLOSURE_NAME)]
2639
                = new ConcreteCompilerVariable(getPassedClosureType(), AI);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2640 2641 2642 2643
            ++AI;
        }

        if (scope_info->createsClosure()) {
2644
            if (!passed_closure) {
2645
                passed_closure = getNullPtr(g.llvm_closure_type_ptr);
2646 2647
                emitter.setType(passed_closure, RefType::BORROWED);
            }
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2648

Travis Hance's avatar
Travis Hance committed
2649 2650
            llvm::Value* new_closure = emitter.getBuilder()->CreateCall2(
                g.funcs.createClosure, passed_closure, getConstantInt(scope_info->getClosureSize(), g.i64));
2651
            emitter.setType(new_closure, RefType::OWNED);
2652
            symbol_table[internString(CREATED_CLOSURE_NAME)]
2653
                = new ConcreteCompilerVariable(getCreatedClosureType(), new_closure);
Kevin Modzelewski's avatar
Kevin Modzelewski committed
2654 2655
        }

2656
        if (irstate->getSourceInfo()->is_generator) {
2657
            symbol_table[internString(PASSED_GENERATOR_NAME)] = new ConcreteCompilerVariable(GENERATOR, AI);
2658
            emitter.setType(AI, RefType::BORROWED);
2659 2660 2661
            ++AI;
        }

2662 2663
        if (!irstate->getSourceInfo()->scoping->areGlobalsFromModule()) {
            irstate->setGlobals(AI);
2664
            emitter.setType(AI, RefType::BORROWED);
2665 2666 2667
            ++AI;
        }

2668 2669 2670 2671
        std::vector<llvm::Value*> python_parameters;
        for (int i = 0; i < arg_types.size(); i++) {
            assert(AI != irstate->getLLVMFunction()->arg_end());

2672
            if (i == 3) {
2673 2674 2675 2676 2677 2678
                for (int i = 3; i < arg_types.size(); i++) {
                    llvm::Value* ptr = emitter.getBuilder()->CreateConstGEP1_32(AI, i - 3);
                    llvm::Value* loaded = emitter.getBuilder()->CreateLoad(ptr);

                    if (arg_types[i]->llvmType() == g.i64)
                        loaded = emitter.getBuilder()->CreatePtrToInt(loaded, arg_types[i]->llvmType());
2679
                    else {
2680
                        assert(arg_types[i]->llvmType() == g.llvm_value_type_ptr);
2681 2682
                        emitter.setType(loaded, RefType::BORROWED);
                    }
2683 2684 2685 2686

                    python_parameters.push_back(loaded);
                }
                ++AI;
2687
                break;
2688
            }
2689 2690

            python_parameters.push_back(AI);
2691
            emitter.setType(AI, RefType::BORROWED);
2692
            ++AI;
2693
        }
2694

2695
        assert(AI == irstate->getLLVMFunction()->arg_end());
2696
        assert(python_parameters.size() == param_names.totalParameters());
2697

2698 2699
        int i = 0;
        for (; i < param_names.args.size(); i++) {
2700 2701
            loadArgument(internString(param_names.args[i]), arg_types[i], python_parameters[i],
                         UnwindInfo::cantUnwind());
2702
        }
2703

2704
        if (param_names.vararg.size()) {
2705 2706
            loadArgument(internString(param_names.vararg), arg_types[i], python_parameters[i],
                         UnwindInfo::cantUnwind());
2707 2708
            i++;
        }
2709

2710
        if (param_names.kwarg.size()) {
2711 2712 2713
            llvm::Value* passed_dict = python_parameters[i];
            emitter.setNullable(passed_dict, true);

2714 2715 2716 2717 2718
            llvm::BasicBlock* starting_block = emitter.currentBasicBlock();
            llvm::BasicBlock* isnull_bb = emitter.createBasicBlock("isnull");
            llvm::BasicBlock* continue_bb = emitter.createBasicBlock("kwargs_join");

            llvm::Value* kwargs_null
2719
                = emitter.getBuilder()->CreateICmpEQ(passed_dict, getNullPtr(g.llvm_value_type_ptr));
2720 2721 2722 2723
            llvm::BranchInst* null_check = emitter.getBuilder()->CreateCondBr(kwargs_null, isnull_bb, continue_bb);

            emitter.setCurrentBasicBlock(isnull_bb);
            llvm::Value* created_dict = emitter.getBuilder()->CreateCall(g.funcs.createDict);
2724 2725
            emitter.setType(created_dict, RefType::OWNED);
            auto isnull_terminator = emitter.getBuilder()->CreateBr(continue_bb);
2726 2727 2728

            emitter.setCurrentBasicBlock(continue_bb);
            llvm::PHINode* phi = emitter.getBuilder()->CreatePHI(g.llvm_value_type_ptr, 2);
2729
            phi->addIncoming(passed_dict, starting_block);
2730 2731
            phi->addIncoming(created_dict, isnull_bb);

2732 2733 2734 2735
            emitter.setType(phi, RefType::OWNED);
            emitter.refConsumed(passed_dict, null_check);
            emitter.refConsumed(created_dict, isnull_terminator);

2736
            loadArgument(internString(param_names.kwarg), arg_types[i], phi, UnwindInfo::cantUnwind());
2737
            i++;
2738
        }
2739 2740

        assert(i == arg_types.size());
2741
    }
2742

2743
    void run(const CFGBlock* block) override {
2744
        if (VERBOSITY("irgenerator") >= 2) { // print starting symbol table
2745 2746 2747 2748 2749
            printf("  %d init:", block->idx);
            for (auto it = symbol_table.begin(); it != symbol_table.end(); ++it)
                printf(" %s", it->first.c_str());
            printf("\n");
        }
2750 2751 2752 2753
        for (int i = 0; i < block->body.size(); i++) {
            if (state == DEAD)
                break;
            assert(state != FINISHED);
2754 2755 2756

#if ENABLE_SAMPLING_PROFILER
            auto stmt = block->body[i];
2757
            if (!(i == 0 && stmt->type == AST_TYPE::Assign) && stmt->lineno > 0) // could be a landingpad
2758 2759 2760
                doSafePoint(block->body[i]);
#endif

2761
            doStmt(block->body[i], UnwindInfo(block->body[i], NULL));
2762
        }
2763
        if (VERBOSITY("irgenerator") >= 2) { // print ending symbol table
2764 2765 2766 2767 2768
            printf("  %d fini:", block->idx);
            for (auto it = symbol_table.begin(); it != symbol_table.end(); ++it)
                printf(" %s", it->first.c_str());
            printf("\n");
        }
2769
    }
2770

2771
    void doSafePoint(AST_stmt* next_statement) override {
2772 2773
        // Unwind info is always needed in allowGLReadPreemption if it has any chance of
        // running arbitrary code like finalizers.
2774
        emitter.createCall(UnwindInfo(next_statement, NULL), g.funcs.allowGLReadPreemption, NOEXC);
2775 2776
    }

2777 2778
    // Create a (or reuse an existing) block that will catch a CAPI exception, and then forward
    // it to the "final_dest" block.  ie final_dest is a block corresponding to the IR level
2779
    // LANDINGPAD, and this function will create a helper block that fetches the exception.
2780 2781
    // As a special-case, a NULL value for final_dest means that this helper block should
    // instead propagate the exception out of the function.
2782
    llvm::BasicBlock* getCAPIExcDest(llvm::BasicBlock* from_block, llvm::BasicBlock* final_dest,
2783
                                     AST_stmt* current_stmt) override {
2784
        assert(0 && "check refcounting");
2785
        llvm::BasicBlock*& capi_exc_dest = capi_exc_dests[final_dest];
2786
        llvm::PHINode*& phi_node = capi_phis[final_dest];
2787

2788 2789
        if (!capi_exc_dest) {
            auto orig_block = curblock;
2790

2791
            capi_exc_dest = llvm::BasicBlock::Create(g.context, "", irstate->getLLVMFunction());
2792

2793 2794 2795 2796 2797
            emitter.setCurrentBasicBlock(capi_exc_dest);
            assert(!phi_node);
            phi_node = emitter.getBuilder()->CreatePHI(g.llvm_aststmt_type_ptr, 0);
            emitter.getBuilder()->CreateCall2(g.funcs.caughtCapiException, phi_node,
                                              embedRelocatablePtr(irstate->getSourceInfo(), g.i8_ptr));
2798

2799 2800 2801 2802 2803 2804 2805 2806
            if (!final_dest) {
                // Propagate the exception out of the function:
                if (irstate->getExceptionStyle() == CXX) {
                    emitter.getBuilder()->CreateCall(g.funcs.reraiseCapiExcAsCxx);
                    emitter.getBuilder()->CreateUnreachable();
                } else {
                    emitter.getBuilder()->CreateRet(getNullPtr(g.llvm_value_type_ptr));
                }
2807
            } else {
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
                // Catch the exception and forward to final_dest:
                llvm::Value* exc_type_ptr
                    = new llvm::AllocaInst(g.llvm_value_type_ptr, getConstantInt(1, g.i64), "exc_type",
                                           irstate->getLLVMFunction()->getEntryBlock().getFirstInsertionPt());
                llvm::Value* exc_value_ptr
                    = new llvm::AllocaInst(g.llvm_value_type_ptr, getConstantInt(1, g.i64), "exc_value",
                                           irstate->getLLVMFunction()->getEntryBlock().getFirstInsertionPt());
                llvm::Value* exc_traceback_ptr
                    = new llvm::AllocaInst(g.llvm_value_type_ptr, getConstantInt(1, g.i64), "exc_traceback",
                                           irstate->getLLVMFunction()->getEntryBlock().getFirstInsertionPt());
                emitter.getBuilder()->CreateCall3(g.funcs.PyErr_Fetch, exc_type_ptr, exc_value_ptr, exc_traceback_ptr);
                // TODO: I think we should be doing this on a python raise() or when we enter a python catch:
                emitter.getBuilder()->CreateCall3(g.funcs.PyErr_NormalizeException, exc_type_ptr, exc_value_ptr,
                                                  exc_traceback_ptr);
                llvm::Value* exc_type = emitter.getBuilder()->CreateLoad(exc_type_ptr);
                llvm::Value* exc_value = emitter.getBuilder()->CreateLoad(exc_value_ptr);
                llvm::Value* exc_traceback = emitter.getBuilder()->CreateLoad(exc_traceback_ptr);

                addOutgoingExceptionState(
2827 2828 2829
                    IRGenerator::ExceptionState(capi_exc_dest, new ConcreteCompilerVariable(UNKNOWN, exc_type),
                                                new ConcreteCompilerVariable(UNKNOWN, exc_value),
                                                new ConcreteCompilerVariable(UNKNOWN, exc_traceback)));
2830 2831

                emitter.getBuilder()->CreateBr(final_dest);
2832
            }
2833 2834 2835 2836 2837 2838 2839 2840 2841

            emitter.setCurrentBasicBlock(from_block);
        }

        assert(capi_exc_dest);
        assert(phi_node);


        phi_node->addIncoming(embedRelocatablePtr(current_stmt, g.llvm_aststmt_type_ptr), from_block);
2842 2843 2844 2845

        return capi_exc_dest;
    }

2846
    llvm::BasicBlock* getCXXExcDest(const UnwindInfo& unw_info) override {
2847 2848 2849
        //llvm::BasicBlock*& cxx_exc_dest = cxx_exc_dests[final_dest];
        //if (cxx_exc_dest)
            //return cxx_exc_dest;
2850

2851 2852 2853 2854 2855 2856 2857
        llvm::BasicBlock* final_dest;
        if (unw_info.hasHandler()) {
            final_dest = unw_info.exc_dest;
        } else {
            final_dest = NULL;
        }

2858 2859
        llvm::BasicBlock* orig_block = curblock;

Kevin Modzelewski's avatar
wip  
Kevin Modzelewski committed
2860
        llvm::BasicBlock* cxx_exc_dest = llvm::BasicBlock::Create(g.context, "cxxwrapper", irstate->getLLVMFunction());
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888

        emitter.getBuilder()->SetInsertPoint(cxx_exc_dest);

        llvm::Function* _personality_func = g.stdlib_module->getFunction("__gxx_personality_v0");
        assert(_personality_func);
        llvm::Value* personality_func
            = g.cur_module->getOrInsertFunction(_personality_func->getName(), _personality_func->getFunctionType());
        assert(personality_func);
        llvm::LandingPadInst* landing_pad = emitter.getBuilder()->CreateLandingPad(
            llvm::StructType::create(std::vector<llvm::Type*>{ g.i8_ptr, g.i64 }), personality_func, 1);
        landing_pad->addClause(getNullPtr(g.i8_ptr));

        llvm::Value* cxaexc_pointer = emitter.getBuilder()->CreateExtractValue(landing_pad, { 0 });

        llvm::Function* std_module_catch = g.stdlib_module->getFunction("__cxa_begin_catch");
        auto begin_catch_func
            = g.cur_module->getOrInsertFunction(std_module_catch->getName(), std_module_catch->getFunctionType());
        assert(begin_catch_func);

        llvm::Value* excinfo_pointer = emitter.getBuilder()->CreateCall(begin_catch_func, cxaexc_pointer);
        llvm::Value* excinfo_pointer_casted
            = emitter.getBuilder()->CreateBitCast(excinfo_pointer, g.llvm_excinfo_type->getPointerTo());

        auto* builder = emitter.getBuilder();
        llvm::Value* exc_type = builder->CreateLoad(builder->CreateConstInBoundsGEP2_32(excinfo_pointer_casted, 0, 0));
        llvm::Value* exc_value = builder->CreateLoad(builder->CreateConstInBoundsGEP2_32(excinfo_pointer_casted, 0, 1));
        llvm::Value* exc_traceback
            = builder->CreateLoad(builder->CreateConstInBoundsGEP2_32(excinfo_pointer_casted, 0, 2));
2889 2890 2891
        emitter.setType(exc_type, RefType::OWNED);
        emitter.setType(exc_value, RefType::OWNED);
        emitter.setType(exc_traceback, RefType::OWNED);
2892

2893
        // final_dest==NULL => propagate the exception out of the function.
2894 2895 2896
        if (final_dest) {
            // Catch the exception and forward to final_dest:
            addOutgoingExceptionState(ExceptionState(cxx_exc_dest,
2897 2898 2899
                                                     new ConcreteCompilerVariable(UNKNOWN, exc_type),
                                                     new ConcreteCompilerVariable(UNKNOWN, exc_value),
                                                     new ConcreteCompilerVariable(UNKNOWN, exc_traceback)));
2900

2901
            builder->CreateBr(final_dest);
2902 2903 2904 2905 2906
        } else if (irstate->getExceptionStyle() == CAPI) {
            auto call_inst = builder->CreateCall3(g.funcs.PyErr_Restore, exc_type, exc_value, exc_traceback);
            irstate->getRefcounts()->refConsumed(exc_type, call_inst);
            irstate->getRefcounts()->refConsumed(exc_value, call_inst);
            irstate->getRefcounts()->refConsumed(exc_traceback, call_inst);
2907
            builder->CreateRet(getNullPtr(g.llvm_value_type_ptr));
2908
        } else {
2909 2910 2911
            //auto call_inst = emitter.createCall3(UnwindInfo(unw_info.current_stmt, NO_CXX_INTERCEPTION),
                                                 //g.funcs.rawThrow, exc_type, exc_value, exc_traceback);
            auto call_inst = emitter.getBuilder()->CreateCall3(g.funcs.rawThrow, exc_type, exc_value, exc_traceback);
2912 2913 2914 2915 2916
            irstate->getRefcounts()->refConsumed(exc_type, call_inst);
            irstate->getRefcounts()->refConsumed(exc_value, call_inst);
            irstate->getRefcounts()->refConsumed(exc_traceback, call_inst);

            builder->CreateUnreachable();
2917
        }
2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930

        emitter.setCurrentBasicBlock(orig_block);

        return cxx_exc_dest;
    }

    void addOutgoingExceptionState(ExceptionState exception_state) override {
        this->outgoing_exc_state.push_back(exception_state);
    }

    void setIncomingExceptionState(llvm::SmallVector<ExceptionState, 2> exc_state) override {
        assert(this->incoming_exc_state.empty());
        this->incoming_exc_state = std::move(exc_state);
2931
    }
2932 2933
};

2934
IRGenerator* createIRGenerator(IRGenState* irstate, std::unordered_map<CFGBlock*, llvm::BasicBlock*>& entry_blocks,
2935 2936
                               CFGBlock* myblock, TypeAnalysis* types) {
    return new IRGeneratorImpl(irstate, entry_blocks, myblock, types);
2937
}
Marius Wachtler's avatar
Marius Wachtler committed
2938

2939
FunctionMetadata* wrapFunction(AST* node, AST_arguments* args, const std::vector<AST_stmt*>& body, SourceInfo* source) {
Marius Wachtler's avatar
Marius Wachtler committed
2940
    // Different compilations of the parent scope of a functiondef should lead
2941 2942
    // to the same FunctionMetadata* being used:
    static std::unordered_map<AST*, FunctionMetadata*> made;
Marius Wachtler's avatar
Marius Wachtler committed
2943

2944 2945
    FunctionMetadata*& md = made[node];
    if (md == NULL) {
2946
        std::unique_ptr<SourceInfo> si(
2947
            new SourceInfo(source->parent_module, source->scoping, source->future_flags, node, body, source->getFn()));
Marius Wachtler's avatar
Marius Wachtler committed
2948
        if (args)
2949
            md = new FunctionMetadata(args->args.size(), args->vararg.s().size(), args->kwarg.s().size(),
2950
                                      std::move(si));
Marius Wachtler's avatar
Marius Wachtler committed
2951
        else
2952
            md = new FunctionMetadata(0, false, false, std::move(si));
Marius Wachtler's avatar
Marius Wachtler committed
2953
    }
2954
    return md;
Marius Wachtler's avatar
Marius Wachtler committed
2955
}
2956
}